blob: 13a009090f9eeb13263f91e0632d029c8902a120 [file] [log] [blame]
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for Objective-C expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnera3fc41d2008-01-04 22:32:30 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
Steve Naroff021ca182008-05-29 21:12:08 +000017#include "clang/AST/ExprObjC.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor0c78ad92010-04-21 19:57:20 +000019#include "clang/AST/TypeLoc.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
21#include "clang/Edit/Commit.h"
22#include "clang/Edit/Rewriters.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000023#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/Initialization.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/Scope.h"
27#include "clang/Sema/ScopeInfo.h"
28#include "llvm/ADT/SmallString.h"
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
Patrick Beard0caa3942012-04-19 00:25:12 +0000528 if (!StringWithUTF8StringMethod) {
529 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
530 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
531
532 // Look for the appropriate method within NSString.
Jordy Rose08e500c2012-05-12 17:32:44 +0000533 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
534 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000535 // Debugger needs to work even if NSString hasn't been defined.
Craig Topperc3ec1492014-05-26 06:22:03 +0000536 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000537 ObjCMethodDecl *M = ObjCMethodDecl::Create(
538 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
539 NSStringPointer, ReturnTInfo, NSStringDecl,
540 /*isInstance=*/false, /*isVariadic=*/false,
541 /*isPropertyAccessor=*/false,
542 /*isImplicitlyDeclared=*/true,
543 /*isDefined=*/false, ObjCMethodDecl::Required,
544 /*HasRelatedResultType=*/false);
Jordy Roseaca01f92012-05-12 17:32:52 +0000545 QualType ConstCharType = Context.CharTy.withConst();
Patrick Beard0caa3942012-04-19 00:25:12 +0000546 ParmVarDecl *value =
547 ParmVarDecl::Create(Context, M,
548 SourceLocation(), SourceLocation(),
549 &Context.Idents.get("value"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000550 Context.getPointerType(ConstCharType),
Craig Topperc3ec1492014-05-26 06:22:03 +0000551 /*TInfo=*/nullptr,
552 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000553 M->setMethodParams(Context, value, None);
Jordy Rose08e500c2012-05-12 17:32:44 +0000554 BoxingMethod = M;
Patrick Beard0caa3942012-04-19 00:25:12 +0000555 }
Jordy Rose890f4572012-05-12 15:53:41 +0000556
Alex Denisovb7d85632015-07-24 05:09:40 +0000557 if (!validateBoxingMethod(*this, Loc, NSStringDecl,
Jordy Rose08e500c2012-05-12 17:32:44 +0000558 stringWithUTF8String, BoxingMethod))
559 return ExprError();
560
561 StringWithUTF8StringMethod = BoxingMethod;
Patrick Beard0caa3942012-04-19 00:25:12 +0000562 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000563
Patrick Beard0caa3942012-04-19 00:25:12 +0000564 BoxingMethod = StringWithUTF8StringMethod;
565 BoxedType = NSStringPointer;
Alex Lorenz49370ac2017-11-08 21:33:15 +0000566 // Transfer the nullability from method's return type.
567 Optional<NullabilityKind> Nullability =
568 BoxingMethod->getReturnType()->getNullability(Context);
569 if (Nullability)
570 BoxedType = Context.getAttributedType(
571 AttributedType::getNullabilityAttrKind(*Nullability), BoxedType,
572 BoxedType);
Patrick Beard0caa3942012-04-19 00:25:12 +0000573 }
Patrick Beard2565c592012-05-01 21:47:19 +0000574 } else if (ValueType->isBuiltinType()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000575 // The other types we support are numeric, char and BOOL/bool. We could also
576 // provide limited support for structure types, such as NSRange, NSRect, and
577 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
578 // for more details.
579
580 // Check for a top-level character literal.
581 if (const CharacterLiteral *Char =
582 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
583 // In C, character literals have type 'int'. That's not the type we want
584 // to use to determine the Objective-c literal kind.
585 switch (Char->getKind()) {
586 case CharacterLiteral::Ascii:
Aaron Ballman9a17c852016-01-07 20:59:26 +0000587 case CharacterLiteral::UTF8:
Patrick Beard0caa3942012-04-19 00:25:12 +0000588 ValueType = Context.CharTy;
589 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000590
Patrick Beard0caa3942012-04-19 00:25:12 +0000591 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000592 ValueType = Context.getWideCharType();
Patrick Beard0caa3942012-04-19 00:25:12 +0000593 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000594
Patrick Beard0caa3942012-04-19 00:25:12 +0000595 case CharacterLiteral::UTF16:
596 ValueType = Context.Char16Ty;
597 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000598
Patrick Beard0caa3942012-04-19 00:25:12 +0000599 case CharacterLiteral::UTF32:
600 ValueType = Context.Char32Ty;
601 break;
602 }
603 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000604 // FIXME: Do I need to do anything special with BoolTy expressions?
Fangrui Song6907ce22018-07-30 19:24:48 +0000605
Patrick Beard0caa3942012-04-19 00:25:12 +0000606 // Look for the appropriate method within NSNumber.
Alex Denisovb7d85632015-07-24 05:09:40 +0000607 BoxingMethod = getNSNumberFactoryMethod(*this, Loc, ValueType);
Patrick Beard0caa3942012-04-19 00:25:12 +0000608 BoxedType = NSNumberPointer;
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000609 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
610 if (!ET->getDecl()->isComplete()) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000611 Diag(Loc, diag::err_objc_incomplete_boxed_expression_type)
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000612 << ValueType << ValueExpr->getSourceRange();
613 return ExprError();
614 }
615
Alex Denisovb7d85632015-07-24 05:09:40 +0000616 BoxingMethod = getNSNumberFactoryMethod(*this, Loc,
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000617 ET->getDecl()->getIntegerType());
618 BoxedType = NSNumberPointer;
Alex Denisovfde64952015-06-26 05:28:36 +0000619 } else if (ValueType->isObjCBoxableRecordType()) {
620 // Support for structure types, that marked as objc_boxable
621 // struct __attribute__((objc_boxable)) s { ... };
Fangrui Song6907ce22018-07-30 19:24:48 +0000622
Alex Denisovfde64952015-06-26 05:28:36 +0000623 // Look up the NSValue class, if we haven't done so already. It's cached
624 // in the Sema instance.
625 if (!NSValueDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000626 NSValueDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
627 Sema::LK_Boxed);
Alex Denisovfde64952015-06-26 05:28:36 +0000628 if (!NSValueDecl) {
Alex Denisovfde64952015-06-26 05:28:36 +0000629 return ExprError();
630 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000631
Alex Denisovfde64952015-06-26 05:28:36 +0000632 // generate the pointer to NSValue type.
633 QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
634 NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
635 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000636
Alex Denisovfde64952015-06-26 05:28:36 +0000637 if (!ValueWithBytesObjCTypeMethod) {
638 IdentifierInfo *II[] = {
639 &Context.Idents.get("valueWithBytes"),
640 &Context.Idents.get("objCType")
641 };
642 Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
Fangrui Song6907ce22018-07-30 19:24:48 +0000643
Alex Denisovfde64952015-06-26 05:28:36 +0000644 // Look for the appropriate method within NSValue.
645 BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
646 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
647 // Debugger needs to work even if NSValue hasn't been defined.
648 TypeSourceInfo *ReturnTInfo = nullptr;
649 ObjCMethodDecl *M = ObjCMethodDecl::Create(
650 Context,
651 SourceLocation(),
652 SourceLocation(),
653 ValueWithBytesObjCType,
654 NSValuePointer,
655 ReturnTInfo,
656 NSValueDecl,
657 /*isInstance=*/false,
658 /*isVariadic=*/false,
659 /*isPropertyAccessor=*/false,
660 /*isImplicitlyDeclared=*/true,
661 /*isDefined=*/false,
662 ObjCMethodDecl::Required,
663 /*HasRelatedResultType=*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +0000664
Alex Denisovfde64952015-06-26 05:28:36 +0000665 SmallVector<ParmVarDecl *, 2> Params;
Fangrui Song6907ce22018-07-30 19:24:48 +0000666
Alex Denisovfde64952015-06-26 05:28:36 +0000667 ParmVarDecl *bytes =
668 ParmVarDecl::Create(Context, M,
669 SourceLocation(), SourceLocation(),
670 &Context.Idents.get("bytes"),
671 Context.VoidPtrTy.withConst(),
672 /*TInfo=*/nullptr,
673 SC_None, nullptr);
674 Params.push_back(bytes);
Fangrui Song6907ce22018-07-30 19:24:48 +0000675
Alex Denisovfde64952015-06-26 05:28:36 +0000676 QualType ConstCharType = Context.CharTy.withConst();
677 ParmVarDecl *type =
678 ParmVarDecl::Create(Context, M,
679 SourceLocation(), SourceLocation(),
680 &Context.Idents.get("type"),
681 Context.getPointerType(ConstCharType),
682 /*TInfo=*/nullptr,
683 SC_None, nullptr);
684 Params.push_back(type);
Fangrui Song6907ce22018-07-30 19:24:48 +0000685
Alex Denisovfde64952015-06-26 05:28:36 +0000686 M->setMethodParams(Context, Params, None);
687 BoxingMethod = M;
688 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000689
Alex Denisovb7d85632015-07-24 05:09:40 +0000690 if (!validateBoxingMethod(*this, Loc, NSValueDecl,
Alex Denisovfde64952015-06-26 05:28:36 +0000691 ValueWithBytesObjCType, BoxingMethod))
692 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +0000693
Alex Denisovfde64952015-06-26 05:28:36 +0000694 ValueWithBytesObjCTypeMethod = BoxingMethod;
695 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000696
Alex Denisovfde64952015-06-26 05:28:36 +0000697 if (!ValueType.isTriviallyCopyableType(Context)) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000698 Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type)
Alex Denisovfde64952015-06-26 05:28:36 +0000699 << ValueType << ValueExpr->getSourceRange();
700 return ExprError();
701 }
702
703 BoxingMethod = ValueWithBytesObjCTypeMethod;
704 BoxedType = NSValuePointer;
Patrick Beard0caa3942012-04-19 00:25:12 +0000705 }
706
707 if (!BoxingMethod) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000708 Diag(Loc, diag::err_objc_illegal_boxed_expression_type)
Patrick Beard0caa3942012-04-19 00:25:12 +0000709 << ValueType << ValueExpr->getSourceRange();
710 return ExprError();
711 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000712
Alex Denisovb7d85632015-07-24 05:09:40 +0000713 DiagnoseUseOfDecl(BoxingMethod, Loc);
Alex Denisovfde64952015-06-26 05:28:36 +0000714
715 ExprResult ConvertedValueExpr;
716 if (ValueType->isObjCBoxableRecordType()) {
717 InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
Fangrui Song6907ce22018-07-30 19:24:48 +0000718 ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
Alex Denisovfde64952015-06-26 05:28:36 +0000719 ValueExpr);
720 } else {
721 // Convert the expression to the type that the parameter requires.
722 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
723 InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
724 ParamDecl);
725 ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
726 ValueExpr);
727 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000728
Patrick Beard0caa3942012-04-19 00:25:12 +0000729 if (ConvertedValueExpr.isInvalid())
730 return ExprError();
731 ValueExpr = ConvertedValueExpr.get();
Fangrui Song6907ce22018-07-30 19:24:48 +0000732
733 ObjCBoxedExpr *BoxedExpr =
Patrick Beard0caa3942012-04-19 00:25:12 +0000734 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
735 BoxingMethod, SR);
736 return MaybeBindToTemporary(BoxedExpr);
737}
738
John McCallf2538342012-07-31 05:14:30 +0000739/// Build an ObjC subscript pseudo-object expression, given that
740/// that's supported by the runtime.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000741ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
742 Expr *IndexExpr,
743 ObjCMethodDecl *getterMethod,
744 ObjCMethodDecl *setterMethod) {
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +0000745 assert(!LangOpts.isSubscriptPointerArithmetic());
John McCall5fb5df92012-06-20 06:18:46 +0000746
John McCallf2538342012-07-31 05:14:30 +0000747 // We can't get dependent types here; our callers should have
748 // filtered them out.
749 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
750 "base or index cannot have dependent type here");
751
752 // Filter out placeholders in the index. In theory, overloads could
753 // be preserved here, although that might not actually work correctly.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000754 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
755 if (Result.isInvalid())
756 return ExprError();
757 IndexExpr = Result.get();
Fangrui Song6907ce22018-07-30 19:24:48 +0000758
John McCallf2538342012-07-31 05:14:30 +0000759 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000760 Result = DefaultLvalueConversion(BaseExpr);
761 if (Result.isInvalid())
762 return ExprError();
763 BaseExpr = Result.get();
John McCallf2538342012-07-31 05:14:30 +0000764
765 // Build the pseudo-object expression.
James Y Knight6c2f06b2015-12-31 04:43:19 +0000766 return new (Context) ObjCSubscriptRefExpr(
767 BaseExpr, IndexExpr, Context.PseudoObjectTy, VK_LValue, OK_ObjCSubscript,
768 getterMethod, setterMethod, RB);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000769}
770
771ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000772 SourceLocation Loc = SR.getBegin();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000773
Alex Denisovb7d85632015-07-24 05:09:40 +0000774 if (!NSArrayDecl) {
775 NSArrayDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
776 Sema::LK_Array);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000777 if (!NSArrayDecl) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000778 return ExprError();
779 }
780 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000781
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000782 // Find the arrayWithObjects:count: method, if we haven't done so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000783 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000784 if (!ArrayWithObjectsMethod) {
785 Selector
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000786 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
787 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000788 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000789 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000790 Method = ObjCMethodDecl::Create(
791 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000792 Context.getTranslationUnitDecl(), false /*Instance*/,
Alp Toker314cc812014-01-25 16:55:45 +0000793 false /*isVariadic*/,
794 /*isPropertyAccessor=*/false,
795 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
796 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000797 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000798 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000799 SourceLocation(),
800 SourceLocation(),
801 &Context.Idents.get("objects"),
802 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000803 /*TInfo=*/nullptr,
804 SC_None, nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000805 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000806 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000807 SourceLocation(),
808 SourceLocation(),
809 &Context.Idents.get("cnt"),
810 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000811 /*TInfo=*/nullptr, SC_None,
812 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000813 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000814 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000815 }
816
Alex Denisovb7d85632015-07-24 05:09:40 +0000817 if (!validateBoxingMethod(*this, Loc, NSArrayDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000818 return ExprError();
Jordy Rose08e500c2012-05-12 17:32:44 +0000819
Jordy Rose4af44872012-05-12 17:32:56 +0000820 // Dig out the type that all elements should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000821 QualType T = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000822 const PointerType *PtrT = T->getAs<PointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +0000823 if (!PtrT ||
Jordy Rose4af44872012-05-12 17:32:56 +0000824 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
825 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
826 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000827 Diag(Method->parameters()[0]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000828 diag::note_objc_literal_method_param)
Fangrui Song6907ce22018-07-30 19:24:48 +0000829 << 0 << T
Jordy Rose4af44872012-05-12 17:32:56 +0000830 << Context.getPointerType(IdT.withConst());
831 return ExprError();
832 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000833
Jordy Rose4af44872012-05-12 17:32:56 +0000834 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000835 if (!Method->parameters()[1]->getType()->isIntegerType()) {
Jordy Rose4af44872012-05-12 17:32:56 +0000836 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
837 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000838 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000839 diag::note_objc_literal_method_param)
Fangrui Song6907ce22018-07-30 19:24:48 +0000840 << 1
Alp Toker03376dc2014-07-07 09:02:20 +0000841 << Method->parameters()[1]->getType()
Jordy Rose4af44872012-05-12 17:32:56 +0000842 << "integral";
843 return ExprError();
844 }
845
846 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rose08e500c2012-05-12 17:32:44 +0000847 ArrayWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000848 }
849
Alp Toker03376dc2014-07-07 09:02:20 +0000850 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000851 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000852
853 // Check that each of the elements provided is valid in a collection literal,
854 // performing conversions as necessary.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000855 Expr **ElementsBuffer = Elements.data();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000856 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
857 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
858 ElementsBuffer[I],
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000859 RequiredType, true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000860 if (Converted.isInvalid())
861 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +0000862
Ted Kremeneke65b0862012-03-06 20:05:56 +0000863 ElementsBuffer[I] = Converted.get();
864 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000865
866 QualType Ty
Ted Kremeneke65b0862012-03-06 20:05:56 +0000867 = Context.getObjCObjectPointerType(
868 Context.getObjCInterfaceType(NSArrayDecl));
869
870 return MaybeBindToTemporary(
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000871 ObjCArrayLiteral::Create(Context, Elements, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000872 ArrayWithObjectsMethod, SR));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000873}
874
Craig Topperd4336e02015-12-24 23:58:15 +0000875ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
876 MutableArrayRef<ObjCDictionaryElement> Elements) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000877 SourceLocation Loc = SR.getBegin();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000878
Alex Denisovb7d85632015-07-24 05:09:40 +0000879 if (!NSDictionaryDecl) {
880 NSDictionaryDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
881 Sema::LK_Dictionary);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000882 if (!NSDictionaryDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000883 return ExprError();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000884 }
885 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000886
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000887 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
888 // so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000889 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000890 if (!DictionaryWithObjectsMethod) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000891 Selector Sel = NSAPIObj->getNSDictionarySelector(
892 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
893 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000894 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000895 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000896 SourceLocation(), SourceLocation(), Sel,
897 IdT,
Craig Topperc3ec1492014-05-26 06:22:03 +0000898 nullptr /*TypeSourceInfo */,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000899 Context.getTranslationUnitDecl(),
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000900 false /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000901 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000902 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
903 ObjCMethodDecl::Required,
904 false);
905 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000906 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000907 SourceLocation(),
908 SourceLocation(),
909 &Context.Idents.get("objects"),
910 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000911 /*TInfo=*/nullptr, SC_None,
912 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000913 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000914 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000915 SourceLocation(),
916 SourceLocation(),
917 &Context.Idents.get("keys"),
918 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000919 /*TInfo=*/nullptr, SC_None,
920 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000921 Params.push_back(keys);
Jordy Rose08e500c2012-05-12 17:32:44 +0000922 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000923 SourceLocation(),
924 SourceLocation(),
925 &Context.Idents.get("cnt"),
926 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000927 /*TInfo=*/nullptr, SC_None,
928 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000929 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000930 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000931 }
932
Jordy Rose08e500c2012-05-12 17:32:44 +0000933 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
934 Method))
935 return ExprError();
936
Jordy Rose4af44872012-05-12 17:32:56 +0000937 // Dig out the type that all values should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000938 QualType ValueT = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000939 const PointerType *PtrValue = ValueT->getAs<PointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +0000940 if (!PtrValue ||
Jordy Rose4af44872012-05-12 17:32:56 +0000941 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000942 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000943 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000944 Diag(Method->parameters()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000945 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000946 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000947 << Context.getPointerType(IdT.withConst());
948 return ExprError();
949 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000950
Jordy Rose4af44872012-05-12 17:32:56 +0000951 // Dig out the type that all keys should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000952 QualType KeyT = Method->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000953 const PointerType *PtrKey = KeyT->getAs<PointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +0000954 if (!PtrKey ||
Jordy Rose4af44872012-05-12 17:32:56 +0000955 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
956 IdT)) {
957 bool err = true;
958 if (PtrKey) {
959 if (QIDNSCopying.isNull()) {
960 // key argument of selector is id<NSCopying>?
961 if (ObjCProtocolDecl *NSCopyingPDecl =
962 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
963 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
Fangrui Song6907ce22018-07-30 19:24:48 +0000964 QIDNSCopying =
Douglas Gregore9d95f12015-07-07 03:57:35 +0000965 Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { },
966 llvm::makeArrayRef(
967 (ObjCProtocolDecl**) PQ,
Douglas Gregorab209d82015-07-07 03:58:42 +0000968 1),
969 false);
Jordy Rose4af44872012-05-12 17:32:56 +0000970 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
971 }
972 }
973 if (!QIDNSCopying.isNull())
974 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
975 QIDNSCopying);
976 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000977
Jordy Rose4af44872012-05-12 17:32:56 +0000978 if (err) {
979 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
980 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000981 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000982 diag::note_objc_literal_method_param)
983 << 1 << KeyT
984 << Context.getPointerType(IdT.withConst());
985 return ExprError();
986 }
987 }
988
989 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000990 QualType CountType = Method->parameters()[2]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000991 if (!CountType->isIntegerType()) {
992 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
993 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000994 Diag(Method->parameters()[2]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000995 diag::note_objc_literal_method_param)
996 << 2 << CountType
997 << "integral";
998 return ExprError();
999 }
1000
1001 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
1002 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001003 }
1004
Alp Toker03376dc2014-07-07 09:02:20 +00001005 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +00001006 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
Alp Toker03376dc2014-07-07 09:02:20 +00001007 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +00001008 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
1009
Fangrui Song6907ce22018-07-30 19:24:48 +00001010 // Check that each of the keys and values provided is valid in a collection
Ted Kremeneke65b0862012-03-06 20:05:56 +00001011 // literal, performing conversions as necessary.
1012 bool HasPackExpansions = false;
Craig Topperd4336e02015-12-24 23:58:15 +00001013 for (ObjCDictionaryElement &Element : Elements) {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001014 // Check the key.
Craig Topperd4336e02015-12-24 23:58:15 +00001015 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Element.Key,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001016 KeyT);
1017 if (Key.isInvalid())
1018 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +00001019
Ted Kremeneke65b0862012-03-06 20:05:56 +00001020 // Check the value.
1021 ExprResult Value
Craig Topperd4336e02015-12-24 23:58:15 +00001022 = CheckObjCCollectionLiteralElement(*this, Element.Value, ValueT);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001023 if (Value.isInvalid())
1024 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +00001025
Craig Topperd4336e02015-12-24 23:58:15 +00001026 Element.Key = Key.get();
1027 Element.Value = Value.get();
Fangrui Song6907ce22018-07-30 19:24:48 +00001028
Craig Topperd4336e02015-12-24 23:58:15 +00001029 if (Element.EllipsisLoc.isInvalid())
Ted Kremeneke65b0862012-03-06 20:05:56 +00001030 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00001031
Craig Topperd4336e02015-12-24 23:58:15 +00001032 if (!Element.Key->containsUnexpandedParameterPack() &&
1033 !Element.Value->containsUnexpandedParameterPack()) {
1034 Diag(Element.EllipsisLoc,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001035 diag::err_pack_expansion_without_parameter_packs)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001036 << SourceRange(Element.Key->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001037 Element.Value->getEndLoc());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001038 return ExprError();
1039 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001040
Ted Kremeneke65b0862012-03-06 20:05:56 +00001041 HasPackExpansions = true;
1042 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001043
Ted Kremeneke65b0862012-03-06 20:05:56 +00001044 QualType Ty
1045 = Context.getObjCObjectPointerType(
Robert Wilhelm88e02492013-08-19 07:57:02 +00001046 Context.getObjCInterfaceType(NSDictionaryDecl));
1047 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
Craig Topperd4336e02015-12-24 23:58:15 +00001048 Context, Elements, HasPackExpansions, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +00001049 DictionaryWithObjectsMethod, SR));
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001050}
1051
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001052ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregorabd9e962010-04-20 15:39:42 +00001053 TypeSourceInfo *EncodedTypeInfo,
Anders Carlsson315d2292009-06-07 18:45:35 +00001054 SourceLocation RParenLoc) {
Douglas Gregorabd9e962010-04-20 15:39:42 +00001055 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlsson315d2292009-06-07 18:45:35 +00001056 QualType StrTy;
Mike Stump11289f42009-09-09 15:08:12 +00001057 if (EncodedType->isDependentType())
Anders Carlsson315d2292009-06-07 18:45:35 +00001058 StrTy = Context.DependentTy;
1059 else {
Fariborz Jahaniand9bc6c32011-06-16 22:34:44 +00001060 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
1061 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001062 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001063 diag::err_incomplete_type_objc_at_encode,
1064 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001065 return ExprError();
1066
Anders Carlsson315d2292009-06-07 18:45:35 +00001067 std::string Str;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00001068 QualType NotEncodedT;
1069 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
1070 if (!NotEncodedT.isNull())
1071 Diag(AtLoc, diag::warn_incomplete_encoded_type)
1072 << EncodedType << NotEncodedT;
Anders Carlsson315d2292009-06-07 18:45:35 +00001073
1074 // The type of @encode is the same as the type of the corresponding string,
1075 // which is an array type.
1076 StrTy = Context.CharTy;
1077 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001078 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlsson315d2292009-06-07 18:45:35 +00001079 StrTy.addConst();
1080 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
1081 ArrayType::Normal, 0);
1082 }
Mike Stump11289f42009-09-09 15:08:12 +00001083
Douglas Gregorabd9e962010-04-20 15:39:42 +00001084 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlsson315d2292009-06-07 18:45:35 +00001085}
1086
John McCallfaf5fb42010-08-26 23:41:50 +00001087ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1088 SourceLocation EncodeLoc,
1089 SourceLocation LParenLoc,
1090 ParsedType ty,
1091 SourceLocation RParenLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001092 // FIXME: Preserve type source info ?
Douglas Gregorabd9e962010-04-20 15:39:42 +00001093 TypeSourceInfo *TInfo;
1094 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1095 if (!TInfo)
1096 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
Craig Topper07fa1762015-11-15 02:31:46 +00001097 getLocForEndOfToken(LParenLoc));
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001098
Douglas Gregorabd9e962010-04-20 15:39:42 +00001099 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001100}
1101
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001102static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1103 SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001104 SourceLocation LParenLoc,
1105 SourceLocation RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001106 ObjCMethodDecl *Method,
1107 ObjCMethodList &MethList) {
1108 ObjCMethodList *M = &MethList;
1109 bool Warned = false;
1110 for (M = M->getNext(); M; M=M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00001111 ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001112 if (MatchingMethodDecl == Method ||
1113 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1114 MatchingMethodDecl->getSelector() != Method->getSelector())
1115 continue;
1116 if (!S.MatchTwoMethodDeclarations(Method,
1117 MatchingMethodDecl, Sema::MMS_loose)) {
1118 if (!Warned) {
1119 Warned = true;
Richard Smith01d96982016-12-02 23:00:28 +00001120 S.Diag(AtLoc, diag::warn_multiple_selectors)
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001121 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1122 << FixItHint::CreateInsertion(RParenLoc, ")");
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001123 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1124 << Method->getDeclName();
1125 }
1126 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1127 << MatchingMethodDecl->getDeclName();
1128 }
1129 }
1130 return Warned;
1131}
1132
1133static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001134 ObjCMethodDecl *Method,
1135 SourceLocation LParenLoc,
1136 SourceLocation RParenLoc,
1137 bool WarnMultipleSelectors) {
1138 if (!WarnMultipleSelectors ||
Richard Smith01d96982016-12-02 23:00:28 +00001139 S.Diags.isIgnored(diag::warn_multiple_selectors, SourceLocation()))
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001140 return;
1141 bool Warned = false;
1142 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1143 e = S.MethodPool.end(); b != e; b++) {
1144 // first, instance methods
1145 ObjCMethodList &InstMethList = b->second.first;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001146 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001147 Method, InstMethList))
1148 Warned = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00001149
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001150 // second, class methods
1151 ObjCMethodList &ClsMethList = b->second.second;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001152 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1153 Method, ClsMethList) || Warned)
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001154 return;
1155 }
1156}
1157
John McCallfaf5fb42010-08-26 23:41:50 +00001158ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1159 SourceLocation AtLoc,
1160 SourceLocation SelLoc,
1161 SourceLocation LParenLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001162 SourceLocation RParenLoc,
1163 bool WarnMultipleSelectors) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001164 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00001165 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001166 if (!Method)
1167 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian0571d9b2009-06-16 16:25:00 +00001168 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00001169 if (!Method) {
1170 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1171 Selector MatchedSel = OM->getSelector();
1172 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1173 RParenLoc.getLocWithOffset(-1));
1174 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1175 << Sel << MatchedSel
1176 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00001177
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00001178 } else
1179 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001180 } else
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001181 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1182 WarnMultipleSelectors);
Chandler Carruth12c8f652015-03-27 00:55:05 +00001183
Fariborz Jahanian65a78b52014-05-09 19:51:39 +00001184 if (Method &&
1185 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
Chandler Carruth12c8f652015-03-27 00:55:05 +00001186 !getSourceManager().isInSystemHeader(Method->getLocation()))
1187 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001188
Fangrui Song6907ce22018-07-30 19:24:48 +00001189 // In ARC, forbid the user from using @selector for
John McCall31168b02011-06-15 23:02:42 +00001190 // retain/release/autorelease/dealloc/retainCount.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001191 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001192 switch (Sel.getMethodFamily()) {
1193 case OMF_retain:
1194 case OMF_release:
1195 case OMF_autorelease:
1196 case OMF_retainCount:
1197 case OMF_dealloc:
Fangrui Song6907ce22018-07-30 19:24:48 +00001198 Diag(AtLoc, diag::err_arc_illegal_selector) <<
John McCall31168b02011-06-15 23:02:42 +00001199 Sel << SourceRange(LParenLoc, RParenLoc);
1200 break;
1201
1202 case OMF_None:
1203 case OMF_alloc:
1204 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00001205 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00001206 case OMF_init:
1207 case OMF_mutableCopy:
1208 case OMF_new:
1209 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00001210 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001211 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001212 break;
1213 }
1214 }
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001215 QualType Ty = Context.getObjCSelType();
Daniel Dunbar45858d22010-02-03 20:11:42 +00001216 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001217}
1218
John McCallfaf5fb42010-08-26 23:41:50 +00001219ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1220 SourceLocation AtLoc,
1221 SourceLocation ProtoLoc,
1222 SourceLocation LParenLoc,
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001223 SourceLocation ProtoIdLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00001224 SourceLocation RParenLoc) {
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001225 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001226 if (!PDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001227 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001228 return true;
1229 }
Alex Lorenzb111da12018-08-17 22:18:08 +00001230 if (!PDecl->hasDefinition()) {
1231 Diag(ProtoLoc, diag::err_atprotocol_protocol) << PDecl;
1232 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
1233 } else {
Fariborz Jahaniana57d91c22014-07-25 19:45:01 +00001234 PDecl = PDecl->getDefinition();
Alex Lorenzb111da12018-08-17 22:18:08 +00001235 }
Mike Stump11289f42009-09-09 15:08:12 +00001236
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001237 QualType Ty = Context.getObjCProtoType();
1238 if (Ty.isNull())
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001239 return true;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001240 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001241 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001242}
1243
John McCall5f2d5562011-02-03 09:00:02 +00001244/// Try to capture an implicit reference to 'self'.
Eli Friedman24af8502012-02-03 22:47:37 +00001245ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1246 DeclContext *DC = getFunctionLevelDeclContext();
John McCall5f2d5562011-02-03 09:00:02 +00001247
1248 // If we're not in an ObjC method, error out. Note that, unlike the
1249 // C++ case, we don't require an instance method --- class methods
1250 // still have a 'self', and we really do still need to capture it!
1251 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1252 if (!method)
Craig Topperc3ec1492014-05-26 06:22:03 +00001253 return nullptr;
John McCall5f2d5562011-02-03 09:00:02 +00001254
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001255 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall5f2d5562011-02-03 09:00:02 +00001256
1257 return method;
1258}
1259
Douglas Gregor64910ca2011-09-09 20:05:21 +00001260static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
Douglas Gregor813a0662015-06-19 18:14:38 +00001261 QualType origType = T;
1262 if (auto nullability = AttributedType::stripOuterNullability(T)) {
1263 if (T == Context.getObjCInstanceType()) {
1264 return Context.getAttributedType(
1265 AttributedType::getNullabilityAttrKind(*nullability),
1266 Context.getObjCIdType(),
1267 Context.getObjCIdType());
1268 }
1269
1270 return origType;
1271 }
1272
Douglas Gregor64910ca2011-09-09 20:05:21 +00001273 if (T == Context.getObjCInstanceType())
1274 return Context.getObjCIdType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001275
Douglas Gregor813a0662015-06-19 18:14:38 +00001276 return origType;
Douglas Gregor64910ca2011-09-09 20:05:21 +00001277}
1278
Douglas Gregor813a0662015-06-19 18:14:38 +00001279/// Determine the result type of a message send based on the receiver type,
1280/// method, and the kind of message send.
1281///
1282/// This is the "base" result type, which will still need to be adjusted
1283/// to account for nullability.
1284static QualType getBaseMessageSendResultType(Sema &S,
1285 QualType ReceiverType,
1286 ObjCMethodDecl *Method,
1287 bool isClassMessage,
1288 bool isSuperMessage) {
Douglas Gregor33823722011-06-11 01:09:30 +00001289 assert(Method && "Must have a method");
1290 if (!Method->hasRelatedResultType())
Douglas Gregore83b9562015-07-07 03:57:53 +00001291 return Method->getSendResultType(ReceiverType);
Douglas Gregor813a0662015-06-19 18:14:38 +00001292
1293 ASTContext &Context = S.Context;
1294
1295 // Local function that transfers the nullability of the method's
1296 // result type to the returned result.
1297 auto transferNullability = [&](QualType type) -> QualType {
1298 // If the method's result type has nullability, extract it.
Douglas Gregore83b9562015-07-07 03:57:53 +00001299 if (auto nullability = Method->getSendResultType(ReceiverType)
1300 ->getNullability(Context)){
Douglas Gregor813a0662015-06-19 18:14:38 +00001301 // Strip off any outer nullability sugar from the provided type.
1302 (void)AttributedType::stripOuterNullability(type);
1303
1304 // Form a new attributed type using the method result type's nullability.
1305 return Context.getAttributedType(
1306 AttributedType::getNullabilityAttrKind(*nullability),
1307 type,
1308 type);
1309 }
1310
1311 return type;
1312 };
1313
Douglas Gregor33823722011-06-11 01:09:30 +00001314 // If a method has a related return type:
1315 // - if the method found is an instance method, but the message send
1316 // was a class message send, T is the declared return type of the method
1317 // found
1318 if (Method->isInstanceMethod() && isClassMessage)
Fangrui Song6907ce22018-07-30 19:24:48 +00001319 return stripObjCInstanceType(Context,
Douglas Gregore83b9562015-07-07 03:57:53 +00001320 Method->getSendResultType(ReceiverType));
Douglas Gregor813a0662015-06-19 18:14:38 +00001321
1322 // - if the receiver is super, T is a pointer to the class of the
Douglas Gregor33823722011-06-11 01:09:30 +00001323 // enclosing method definition
1324 if (isSuperMessage) {
Douglas Gregor813a0662015-06-19 18:14:38 +00001325 if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
1326 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1327 return transferNullability(
1328 Context.getObjCObjectPointerType(
1329 Context.getObjCInterfaceType(Class)));
1330 }
Douglas Gregor33823722011-06-11 01:09:30 +00001331 }
Douglas Gregor813a0662015-06-19 18:14:38 +00001332
Douglas Gregor33823722011-06-11 01:09:30 +00001333 // - if the receiver is the name of a class U, T is a pointer to U
Douglas Gregore83b9562015-07-07 03:57:53 +00001334 if (ReceiverType->getAsObjCInterfaceType())
Douglas Gregor813a0662015-06-19 18:14:38 +00001335 return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
1336 // - if the receiver is of type Class or qualified Class type,
Douglas Gregor33823722011-06-11 01:09:30 +00001337 // T is the declared return type of the method.
1338 if (ReceiverType->isObjCClassType() ||
1339 ReceiverType->isObjCQualifiedClassType())
Fangrui Song6907ce22018-07-30 19:24:48 +00001340 return stripObjCInstanceType(Context,
Douglas Gregore83b9562015-07-07 03:57:53 +00001341 Method->getSendResultType(ReceiverType));
Douglas Gregor813a0662015-06-19 18:14:38 +00001342
Douglas Gregor33823722011-06-11 01:09:30 +00001343 // - if the receiver is id, qualified id, Class, or qualified Class, T
1344 // is the receiver type, otherwise
1345 // - T is the type of the receiver expression.
Douglas Gregor813a0662015-06-19 18:14:38 +00001346 return transferNullability(ReceiverType);
1347}
1348
1349QualType Sema::getMessageSendResultType(QualType ReceiverType,
1350 ObjCMethodDecl *Method,
1351 bool isClassMessage,
1352 bool isSuperMessage) {
1353 // Produce the result type.
1354 QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
1355 Method,
1356 isClassMessage,
1357 isSuperMessage);
1358
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001359 // If this is a class message, ignore the nullability of the receiver.
1360 if (isClassMessage)
1361 return resultType;
1362
Akira Hatanaka66d405d2018-07-26 17:51:13 +00001363 // There is nothing left to do if the result type cannot have a nullability
1364 // specifier.
1365 if (!resultType->canHaveNullability())
1366 return resultType;
1367
Douglas Gregor813a0662015-06-19 18:14:38 +00001368 // Map the nullability of the result into a table index.
1369 unsigned receiverNullabilityIdx = 0;
1370 if (auto nullability = ReceiverType->getNullability(Context))
1371 receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1372
1373 unsigned resultNullabilityIdx = 0;
1374 if (auto nullability = resultType->getNullability(Context))
1375 resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1376
1377 // The table of nullability mappings, indexed by the receiver's nullability
1378 // and then the result type's nullability.
1379 static const uint8_t None = 0;
1380 static const uint8_t NonNull = 1;
1381 static const uint8_t Nullable = 2;
1382 static const uint8_t Unspecified = 3;
1383 static const uint8_t nullabilityMap[4][4] = {
1384 // None NonNull Nullable Unspecified
1385 /* None */ { None, None, Nullable, None },
1386 /* NonNull */ { None, NonNull, Nullable, Unspecified },
1387 /* Nullable */ { Nullable, Nullable, Nullable, Nullable },
1388 /* Unspecified */ { None, Unspecified, Nullable, Unspecified }
1389 };
1390
1391 unsigned newResultNullabilityIdx
1392 = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
1393 if (newResultNullabilityIdx == resultNullabilityIdx)
1394 return resultType;
1395
1396 // Strip off the existing nullability. This removes as little type sugar as
1397 // possible.
1398 do {
1399 if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
1400 resultType = attributed->getModifiedType();
1401 } else {
1402 resultType = resultType.getDesugaredType(Context);
1403 }
1404 } while (resultType->getNullability(Context));
1405
1406 // Add nullability back if needed.
1407 if (newResultNullabilityIdx > 0) {
1408 auto newNullability
1409 = static_cast<NullabilityKind>(newResultNullabilityIdx-1);
1410 return Context.getAttributedType(
1411 AttributedType::getNullabilityAttrKind(newNullability),
1412 resultType, resultType);
1413 }
1414
1415 return resultType;
Douglas Gregor33823722011-06-11 01:09:30 +00001416}
John McCall5f2d5562011-02-03 09:00:02 +00001417
John McCall5ec7e7d2013-03-19 07:04:25 +00001418/// Look for an ObjC method whose result type exactly matches the given type.
1419static const ObjCMethodDecl *
1420findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1421 QualType instancetype) {
Alp Toker314cc812014-01-25 16:55:45 +00001422 if (MD->getReturnType() == instancetype)
1423 return MD;
John McCall5ec7e7d2013-03-19 07:04:25 +00001424
1425 // For these purposes, a method in an @implementation overrides a
1426 // declaration in the @interface.
1427 if (const ObjCImplDecl *impl =
1428 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1429 const ObjCContainerDecl *iface;
Fangrui Song6907ce22018-07-30 19:24:48 +00001430 if (const ObjCCategoryImplDecl *catImpl =
John McCall5ec7e7d2013-03-19 07:04:25 +00001431 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1432 iface = catImpl->getCategoryDecl();
1433 } else {
1434 iface = impl->getClassInterface();
1435 }
1436
Fangrui Song6907ce22018-07-30 19:24:48 +00001437 const ObjCMethodDecl *ifaceMD =
John McCall5ec7e7d2013-03-19 07:04:25 +00001438 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1439 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1440 }
1441
1442 SmallVector<const ObjCMethodDecl *, 4> overrides;
1443 MD->getOverriddenMethods(overrides);
1444 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1445 if (const ObjCMethodDecl *result =
1446 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1447 return result;
1448 }
1449
Craig Topperc3ec1492014-05-26 06:22:03 +00001450 return nullptr;
John McCall5ec7e7d2013-03-19 07:04:25 +00001451}
1452
1453void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1454 // Only complain if we're in an ObjC method and the required return
1455 // type doesn't match the method's declared return type.
1456 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1457 if (!MD || !MD->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +00001458 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
John McCall5ec7e7d2013-03-19 07:04:25 +00001459 return;
1460
1461 // Look for a method overridden by this method which explicitly uses
1462 // 'instancetype'.
1463 if (const ObjCMethodDecl *overridden =
1464 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +00001465 SourceRange range = overridden->getReturnTypeSourceRange();
1466 SourceLocation loc = range.getBegin();
John McCall5ec7e7d2013-03-19 07:04:25 +00001467 if (loc.isInvalid())
1468 loc = overridden->getLocation();
1469 Diag(loc, diag::note_related_result_type_explicit)
1470 << /*current method*/ 1 << range;
1471 return;
1472 }
1473
1474 // Otherwise, if we have an interesting method family, note that.
1475 // This should always trigger if the above didn't.
1476 if (ObjCMethodFamily family = MD->getMethodFamily())
1477 Diag(MD->getLocation(), diag::note_related_result_type_family)
1478 << /*current method*/ 1
1479 << family;
1480}
1481
Douglas Gregor33823722011-06-11 01:09:30 +00001482void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1483 E = E->IgnoreParenImpCasts();
1484 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1485 if (!MsgSend)
1486 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001487
Douglas Gregor33823722011-06-11 01:09:30 +00001488 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1489 if (!Method)
1490 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001491
Douglas Gregor33823722011-06-11 01:09:30 +00001492 if (!Method->hasRelatedResultType())
1493 return;
Alp Toker314cc812014-01-25 16:55:45 +00001494
1495 if (Context.hasSameUnqualifiedType(
1496 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
Douglas Gregor33823722011-06-11 01:09:30 +00001497 return;
Alp Toker314cc812014-01-25 16:55:45 +00001498
1499 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
Douglas Gregorbab8a962011-09-08 01:46:34 +00001500 Context.getObjCInstanceType()))
1501 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001502
Douglas Gregor33823722011-06-11 01:09:30 +00001503 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1504 << Method->isInstanceMethod() << Method->getSelector()
1505 << MsgSend->getType();
1506}
1507
1508bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001509 MultiExprArg Args,
1510 Selector Sel,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001511 ArrayRef<SourceLocation> SelectorLocs,
1512 ObjCMethodDecl *Method,
Douglas Gregor33823722011-06-11 01:09:30 +00001513 bool isClassMessage, bool isSuperMessage,
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001514 SourceLocation lbrac, SourceLocation rbrac,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001515 SourceRange RecRange,
John McCall7decc9e2010-11-18 06:31:45 +00001516 QualType &ReturnType, ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001517 SourceLocation SelLoc;
1518 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1519 SelLoc = SelectorLocs.front();
1520 else
1521 SelLoc = lbrac;
1522
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001523 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001524 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001525 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001526 if (Args[i]->isTypeDependent())
1527 continue;
1528
John McCallcc5788c2013-03-04 07:34:02 +00001529 ExprResult result;
1530 if (getLangOpts().DebuggerSupport) {
1531 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001532 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001533 } else {
1534 result = DefaultArgumentPromotion(Args[i]);
1535 }
1536 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001537 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001538 Args[i] = result.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001539 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001540
John McCall31168b02011-06-15 23:02:42 +00001541 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001542 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001543 DiagID = diag::err_arc_method_not_found;
1544 else
1545 DiagID = isClassMessage ? diag::warn_class_method_not_found
1546 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001547 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001548 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahanian06499232013-06-18 17:10:58 +00001549 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001550 if (getLangOpts().ObjCAutoRefCount)
Richard Smithf8812672016-12-02 22:38:31 +00001551 DiagID = diag::err_method_not_found_with_typo;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001552 else
1553 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1554 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001555 Selector MatchedSel = OMD->getSelector();
1556 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian5ab87502014-08-12 22:16:41 +00001557 if (MatchedSel.isUnarySelector())
1558 Diag(SelLoc, DiagID)
1559 << Sel<< isClassMessage << MatchedSel
1560 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1561 else
1562 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001563 }
1564 else
1565 Diag(SelLoc, DiagID)
Fangrui Song6907ce22018-07-30 19:24:48 +00001566 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001567 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001568 // Find the class to which we are sending this message.
1569 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001570 if (ObjCInterfaceDecl *ThisClass =
1571 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
1572 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1573 if (!RecRange.isInvalid())
1574 if (ThisClass->lookupClassMethod(Sel))
1575 Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
1576 << FixItHint::CreateReplacement(RecRange,
1577 ThisClass->getNameAsString());
1578 }
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001579 }
1580 }
John McCall3f4138c2011-07-13 17:56:40 +00001581
1582 // In debuggers, we want to use __unknown_anytype for these
1583 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001584 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001585 ReturnType = Context.UnknownAnyTy;
1586 } else {
1587 ReturnType = Context.getObjCIdType();
1588 }
John McCall7decc9e2010-11-18 06:31:45 +00001589 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001590 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001591 }
Mike Stump11289f42009-09-09 15:08:12 +00001592
Fangrui Song6907ce22018-07-30 19:24:48 +00001593 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
Douglas Gregor33823722011-06-11 01:09:30 +00001594 isSuperMessage);
Alp Toker314cc812014-01-25 16:55:45 +00001595 VK = Expr::getValueKindForType(Method->getReturnType());
Mike Stump11289f42009-09-09 15:08:12 +00001596
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001597 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001598 // Method might have more arguments than selector indicates. This is due
1599 // to addition of c-style arguments in method.
1600 if (Method->param_size() > Sel.getNumArgs())
1601 NumNamedArgs = Method->param_size();
1602 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001603 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001604 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001605 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001606 return false;
1607 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001608
Douglas Gregore83b9562015-07-07 03:57:53 +00001609 // Compute the set of type arguments to be substituted into each parameter
1610 // type.
1611 Optional<ArrayRef<QualType>> typeArgs
1612 = ReceiverType->getObjCSubstitutions(Method->getDeclContext());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001613 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001614 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001615 // We can't do any type-checking on a type-dependent argument.
1616 if (Args[i]->isTypeDependent())
1617 continue;
1618
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001619 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001620
Alp Toker03376dc2014-07-07 09:02:20 +00001621 ParmVarDecl *param = Method->parameters()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001622 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001623
Akira Hatanaka627586b2018-03-02 01:53:15 +00001624 if (param->hasAttr<NoEscapeAttr>())
1625 if (auto *BE = dyn_cast<BlockExpr>(
1626 argExpr->IgnoreParenNoopCasts(Context)))
1627 BE->getBlockDecl()->setDoesNotEscape();
1628
John McCall4124c492011-10-17 18:40:02 +00001629 // Strip the unbridged-cast placeholder expression off unless it's
1630 // a consumed argument.
1631 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1632 !param->hasAttr<CFConsumedAttr>())
1633 argExpr = stripARCUnbridgedCast(argExpr);
1634
John McCallea0a39e2012-11-14 00:49:39 +00001635 // If the parameter is __unknown_anytype, infer its type
1636 // from the argument.
1637 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001638 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001639 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001640 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001641 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001642 } else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001643 Args[i] = argE.get();
John McCallea0a39e2012-11-14 00:49:39 +00001644
John McCallcc5788c2013-03-04 07:34:02 +00001645 // Update the parameter type in-place.
1646 param->setType(paramType);
1647 }
1648 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001649 }
1650
Douglas Gregore83b9562015-07-07 03:57:53 +00001651 QualType origParamType = param->getType();
1652 QualType paramType = param->getType();
1653 if (typeArgs)
1654 paramType = paramType.substObjCTypeArgs(
1655 Context,
1656 *typeArgs,
1657 ObjCSubstitutionContext::Parameter);
1658
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001659 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
Douglas Gregore83b9562015-07-07 03:57:53 +00001660 paramType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001661 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001662 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001663
Douglas Gregore83b9562015-07-07 03:57:53 +00001664 InitializedEntity Entity
1665 = InitializedEntity::InitializeParameter(Context, param, paramType);
Fariborz Jahaniana1db7df2014-07-31 17:39:50 +00001666 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001667 if (ArgE.isInvalid())
1668 IsError = true;
Douglas Gregore83b9562015-07-07 03:57:53 +00001669 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001670 Args[i] = ArgE.getAs<Expr>();
Douglas Gregore83b9562015-07-07 03:57:53 +00001671
1672 // If we are type-erasing a block to a block-compatible
1673 // Objective-C pointer type, we may need to extend the lifetime
1674 // of the block object.
1675 if (typeArgs && Args[i]->isRValue() && paramType->isBlockPointerType() &&
Bob Wilson7e9fd562015-10-02 01:05:29 +00001676 Args[i]->getType()->isBlockPointerType() &&
1677 origParamType->isObjCObjectPointerType()) {
Douglas Gregore83b9562015-07-07 03:57:53 +00001678 ExprResult arg = Args[i];
1679 maybeExtendBlockObject(arg);
1680 Args[i] = arg.get();
1681 }
1682 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001683 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001684
1685 // Promote additional arguments to variadic methods.
1686 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001687 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001688 if (Args[i]->isTypeDependent())
1689 continue;
1690
Jordy Roseaca01f92012-05-12 17:32:52 +00001691 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
Craig Topperc3ec1492014-05-26 06:22:03 +00001692 nullptr);
John Wiegley01296292011-04-08 18:41:53 +00001693 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001694 Args[i] = Arg.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001695 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001696 } else {
1697 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001698 if (Args.size() != NumNamedArgs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001699 Diag(Args[NumNamedArgs]->getBeginLoc(),
Chris Lattner3b054132008-11-19 05:08:23 +00001700 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001701 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
1702 << Method->getSourceRange()
1703 << SourceRange(Args[NumNamedArgs]->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001704 Args.back()->getEndLoc());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001705 }
1706 }
1707
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001708 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001709
1710 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001711 IsError |= CheckObjCMethodCall(
Craig Topper8c2a2a02014-08-30 16:55:39 +00001712 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001713
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001714 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001715}
1716
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001717bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001718 // 'self' is objc 'self' in an objc method only.
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001719 ObjCMethodDecl *Method =
1720 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1721 return isSelfExpr(RExpr, Method);
1722}
1723
1724bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
John McCallfe96e0b2011-11-06 09:01:30 +00001725 if (!method) return false;
1726
John McCall31168b02011-06-15 23:02:42 +00001727 receiver = receiver->IgnoreParenLValueCasts();
1728 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001729 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001730 return true;
1731 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001732}
1733
John McCall526ab472011-10-25 17:37:35 +00001734/// LookupMethodInType - Look up a method in an ObjCObjectType.
1735ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1736 bool isInstance) {
1737 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1738 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1739 // Look it up in the main interface (and categories, etc.)
1740 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1741 return method;
1742
1743 // Okay, look for "private" methods declared in any
1744 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001745 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1746 return method;
John McCall526ab472011-10-25 17:37:35 +00001747 }
1748
1749 // Check qualifiers.
Aaron Ballman1683f7b2014-03-17 15:55:30 +00001750 for (const auto *I : objType->quals())
1751 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
John McCall526ab472011-10-25 17:37:35 +00001752 return method;
1753
Craig Topperc3ec1492014-05-26 06:22:03 +00001754 return nullptr;
John McCall526ab472011-10-25 17:37:35 +00001755}
1756
Fangrui Song6907ce22018-07-30 19:24:48 +00001757/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001758/// list of a qualified objective pointer type.
1759ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1760 const ObjCObjectPointerType *OPT,
1761 bool Instance)
1762{
Craig Topperc3ec1492014-05-26 06:22:03 +00001763 ObjCMethodDecl *MD = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +00001764 for (const auto *PROTO : OPT->quals()) {
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001765 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1766 return MD;
1767 }
1768 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001769 return nullptr;
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001770}
1771
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001772/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1773/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001774ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001775HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001776 Expr *BaseExpr, SourceLocation OpLoc,
1777 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001778 SourceLocation MemberLoc,
1779 SourceLocation SuperLoc, QualType SuperType,
1780 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001781 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1782 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001783
Benjamin Kramer365082d2012-05-19 16:34:46 +00001784 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001785 Diag(MemberLoc, diag::err_invalid_property_name)
1786 << MemberName << QualType(OPT, 0);
1787 return ExprError();
1788 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001789
1790 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Fangrui Song6907ce22018-07-30 19:24:48 +00001791
Douglas Gregor4123a862011-11-14 22:10:01 +00001792 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1793 : BaseExpr->getSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +00001794 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001795 diag::err_property_not_found_forward_class,
1796 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001797 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +00001798
Manman Ren5b786402016-01-28 18:49:28 +00001799 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(
1800 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001801 // Check whether we can reference this property.
1802 if (DiagnoseUseOfDecl(PD, MemberLoc))
1803 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001804 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001805 return new (Context)
1806 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1807 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001808 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001809 return new (Context)
1810 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1811 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001812 }
1813 // Check protocols on qualified interfaces.
Aaron Ballman83731462014-03-17 16:14:00 +00001814 for (const auto *I : OPT->quals())
Manman Ren5b786402016-01-28 18:49:28 +00001815 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
1816 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001817 // Check whether we can reference this property.
1818 if (DiagnoseUseOfDecl(PD, MemberLoc))
1819 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001820
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001821 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001822 return new (Context) ObjCPropertyRefExpr(
1823 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1824 SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001825 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001826 return new (Context)
1827 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1828 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001829 }
1830 // If that failed, look for an "implicit" property by seeing if the nullary
1831 // selector is implemented.
1832
1833 // FIXME: The logic for looking up nullary and unary selectors should be
1834 // shared with the code in ActOnInstanceMessage.
1835
1836 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1837 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fangrui Song6907ce22018-07-30 19:24:48 +00001838
Manman Ren2b2b1a92016-06-28 23:01:49 +00001839 // May be found in property's qualified list.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001840 if (!Getter)
1841 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001842
1843 // If this reference is in an @implementation, check for 'private' methods.
1844 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001845 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001846
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001847 if (Getter) {
1848 // Check if we can reference this property.
1849 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1850 return ExprError();
1851 }
1852 // If we found a getter then this may be a valid dot-reference, we
1853 // will look for the matching setter, in case it is needed.
1854 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001855 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1856 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001857 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fangrui Song6907ce22018-07-30 19:24:48 +00001858
Manman Ren2b2b1a92016-06-28 23:01:49 +00001859 // May be found in property's qualified list.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001860 if (!Setter)
1861 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001862
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001863 if (!Setter) {
1864 // If this reference is in an @implementation, also check for 'private'
1865 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001866 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001867 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001868
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001869 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1870 return ExprError();
1871
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001872 // Special warning if member name used in a property-dot for a setter accessor
1873 // does not use a property with same name; e.g. obj.X = ... for a property with
1874 // name 'x'.
Manman Ren5b786402016-01-28 18:49:28 +00001875 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor() &&
1876 !IFace->FindPropertyDeclaration(
1877 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001878 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
1879 // Do not warn if user is using property-dot syntax to make call to
1880 // user named setter.
1881 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001882 Diag(MemberLoc,
1883 diag::warn_property_access_suggest)
1884 << MemberName << QualType(OPT, 0) << PDecl->getName()
1885 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001886 }
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001887 }
1888
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001889 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001890 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001891 return new (Context)
1892 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1893 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001894 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001895 return new (Context)
1896 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1897 OK_ObjCProperty, MemberLoc, BaseExpr);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001898
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001899 }
1900
1901 // Attempt to correct for typos in property names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001902 if (TypoCorrection Corrected =
1903 CorrectTypo(DeclarationNameInfo(MemberName, MemberLoc),
1904 LookupOrdinaryName, nullptr, nullptr,
1905 llvm::make_unique<DeclFilterCCC<ObjCPropertyDecl>>(),
1906 CTK_ErrorRecovery, IFace, false, OPT)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001907 DeclarationName TypoResult = Corrected.getCorrection();
Manman Ren2b2b1a92016-06-28 23:01:49 +00001908 if (TypoResult.isIdentifier() &&
1909 TypoResult.getAsIdentifierInfo() == Member) {
1910 // There is no need to try the correction if it is the same.
1911 NamedDecl *ChosenDecl =
1912 Corrected.isKeyword() ? nullptr : Corrected.getFoundDecl();
1913 if (ChosenDecl && isa<ObjCPropertyDecl>(ChosenDecl))
1914 if (cast<ObjCPropertyDecl>(ChosenDecl)->isClassProperty()) {
1915 // This is a class property, we should not use the instance to
1916 // access it.
1917 Diag(MemberLoc, diag::err_class_property_found) << MemberName
1918 << OPT->getInterfaceDecl()->getName()
1919 << FixItHint::CreateReplacement(BaseExpr->getSourceRange(),
1920 OPT->getInterfaceDecl()->getName());
1921 return ExprError();
1922 }
1923 } else {
1924 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1925 << MemberName << QualType(OPT, 0));
1926 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1927 TypoResult, MemberLoc,
1928 SuperLoc, SuperType, Super);
1929 }
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001930 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001931 ObjCInterfaceDecl *ClassDeclared;
Fangrui Song6907ce22018-07-30 19:24:48 +00001932 if (ObjCIvarDecl *Ivar =
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001933 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1934 QualType T = Ivar->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001935 if (const ObjCObjectPointerType * OBJPT =
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001936 T->getAsObjCInterfacePointerType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001937 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001938 diag::err_property_not_as_forward_class,
1939 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001940 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001941 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001942 Diag(MemberLoc,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001943 diag::err_ivar_access_using_property_syntax_suggest)
1944 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1945 << FixItHint::CreateReplacement(OpLoc, "->");
1946 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001947 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001948
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001949 Diag(MemberLoc, diag::err_property_not_found)
1950 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001951 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001952 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001953 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001954 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001955}
1956
John McCalldadc5752010-08-24 06:29:42 +00001957ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001958ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1959 IdentifierInfo &propertyName,
1960 SourceLocation receiverNameLoc,
1961 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001962
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001963 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001964 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1965 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001966
Douglas Gregore83b9562015-07-07 03:57:53 +00001967 QualType SuperType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001968 if (!IFace) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001969 // If the "receiver" is 'super' in a method, handle it as an expression-like
1970 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001971 if (receiverNamePtr->isStr("super")) {
Eli Friedman24af8502012-02-03 22:47:37 +00001972 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Douglas Gregore83b9562015-07-07 03:57:53 +00001973 if (auto classDecl = CurMethod->getClassInterface()) {
1974 SuperType = QualType(classDecl->getSuperClassType(), 0);
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001975 if (CurMethod->isInstanceMethod()) {
Douglas Gregore83b9562015-07-07 03:57:53 +00001976 if (SuperType.isNull()) {
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001977 // The current class does not have a superclass.
Richard Smithf8812672016-12-02 22:38:31 +00001978 Diag(receiverNameLoc, diag::err_root_class_cannot_use_super)
Douglas Gregore83b9562015-07-07 03:57:53 +00001979 << CurMethod->getClassInterface()->getIdentifier();
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001980 return ExprError();
1981 }
Douglas Gregore83b9562015-07-07 03:57:53 +00001982 QualType T = Context.getObjCObjectPointerType(SuperType);
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001983
Douglas Gregore83b9562015-07-07 03:57:53 +00001984 return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(),
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001985 /*BaseExpr*/nullptr,
1986 SourceLocation()/*OpLoc*/,
1987 &propertyName,
1988 propertyNameLoc,
1989 receiverNameLoc, T, true);
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00001990 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001991
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001992 // Otherwise, if this is a class method, try dispatching to our
1993 // superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00001994 IFace = CurMethod->getClassInterface()->getSuperClass();
Chris Lattnera36ec422010-04-11 08:28:14 +00001995 }
Chris Lattnera36ec422010-04-11 08:28:14 +00001996 }
John McCall5f2d5562011-02-03 09:00:02 +00001997 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001998
1999 if (!IFace) {
Alp Tokerec543272013-12-24 09:48:30 +00002000 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
2001 << tok::l_paren;
Chris Lattnera36ec422010-04-11 08:28:14 +00002002 return ExprError();
2003 }
2004 }
2005
Saleem Abdulrasoolb3a2d042017-02-20 23:45:49 +00002006 Selector GetterSel;
2007 Selector SetterSel;
2008 if (auto PD = IFace->FindPropertyDeclaration(
2009 &propertyName, ObjCPropertyQueryKind::OBJC_PR_query_class)) {
2010 GetterSel = PD->getGetterName();
2011 SetterSel = PD->getSetterName();
2012 } else {
2013 GetterSel = PP.getSelectorTable().getNullarySelector(&propertyName);
2014 SetterSel = SelectorTable::constructSetterSelector(
2015 PP.getIdentifierTable(), PP.getSelectorTable(), &propertyName);
2016 }
2017
Chris Lattnera36ec422010-04-11 08:28:14 +00002018 // Search for a declared property first.
Saleem Abdulrasoolb3a2d042017-02-20 23:45:49 +00002019 ObjCMethodDecl *Getter = IFace->lookupClassMethod(GetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002020
2021 // If this reference is in an @implementation, check for 'private' methods.
2022 if (!Getter)
Saleem Abdulrasoolb3a2d042017-02-20 23:45:49 +00002023 Getter = IFace->lookupPrivateClassMethod(GetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002024
2025 if (Getter) {
2026 // FIXME: refactor/share with ActOnMemberReference().
2027 // Check if we can reference this property.
2028 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
2029 return ExprError();
2030 }
Mike Stump11289f42009-09-09 15:08:12 +00002031
Steve Naroff9527bbf2009-03-09 21:12:44 +00002032 // Look for the matching setter, in case it is needed.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002033 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002034 if (!Setter) {
2035 // If this reference is in an @implementation, also check for 'private'
2036 // methods.
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00002037 Setter = IFace->lookupPrivateClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002038 }
2039 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002040 if (!Setter)
2041 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002042
2043 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
2044 return ExprError();
2045
2046 if (Getter || Setter) {
Douglas Gregore83b9562015-07-07 03:57:53 +00002047 if (!SuperType.isNull())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002048 return new (Context)
2049 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2050 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
Douglas Gregore83b9562015-07-07 03:57:53 +00002051 SuperType);
Douglas Gregor33823722011-06-11 01:09:30 +00002052
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002053 return new (Context) ObjCPropertyRefExpr(
2054 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
2055 propertyNameLoc, receiverNameLoc, IFace);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002056 }
2057 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
2058 << &propertyName << Context.getObjCInterfaceType(IFace));
2059}
2060
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002061namespace {
2062
2063class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
2064 public:
2065 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
2066 // Determine whether "super" is acceptable in the current context.
2067 if (Method && Method->getClassInterface())
2068 WantObjCSuper = Method->getClassInterface()->getSuperClass();
2069 }
2070
Craig Toppere14c0f82014-03-12 04:55:44 +00002071 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002072 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
2073 candidate.isKeyword("super");
2074 }
2075};
2076
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002077} // end anonymous namespace
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002078
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002079Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00002080 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002081 SourceLocation NameLoc,
2082 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00002083 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00002084 ParsedType &ReceiverType) {
David Blaikieefdccaa2016-01-15 23:43:34 +00002085 ReceiverType = nullptr;
Douglas Gregore5798dc2010-04-21 20:38:13 +00002086
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002087 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00002088 // messaging super. If the identifier is "super" and there is a
2089 // trailing dot, it's an instance message.
2090 if (IsSuper && S->isInObjcMethodScope())
2091 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Fangrui Song6907ce22018-07-30 19:24:48 +00002092
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002093 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
2094 LookupName(Result, S);
Fangrui Song6907ce22018-07-30 19:24:48 +00002095
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002096 switch (Result.getResultKind()) {
2097 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00002098 // Normal name lookup didn't find anything. If we're in an
2099 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00002100 // FIXME: This is a hack. Ivar lookup should be part of normal
2101 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00002102 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00002103 if (!Method->getClassInterface()) {
2104 // Fall back: let the parser try to parse it as an instance message.
2105 return ObjCInstanceMessage;
2106 }
2107
Douglas Gregorca7136b2010-04-19 20:09:36 +00002108 ObjCInterfaceDecl *ClassDeclared;
Fangrui Song6907ce22018-07-30 19:24:48 +00002109 if (Method->getClassInterface()->lookupInstanceVariable(Name,
Douglas Gregorca7136b2010-04-19 20:09:36 +00002110 ClassDeclared))
2111 return ObjCInstanceMessage;
2112 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002113
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002114 // Break out; we'll perform typo correction below.
2115 break;
2116
2117 case LookupResult::NotFoundInCurrentInstantiation:
2118 case LookupResult::FoundOverloaded:
2119 case LookupResult::FoundUnresolvedValue:
2120 case LookupResult::Ambiguous:
2121 Result.suppressDiagnostics();
2122 return ObjCInstanceMessage;
2123
2124 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00002125 // If the identifier is a class or not, and there is a trailing dot,
2126 // it's an instance message.
2127 if (HasTrailingDot)
2128 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002129 // We found something. If it's a type, then we have a class
2130 // message. Otherwise, it's an instance message.
2131 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00002132 QualType T;
2133 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
2134 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00002135 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00002136 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00002137 DiagnoseUseOfDecl(Type, NameLoc);
2138 }
2139 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00002140 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002141
Douglas Gregore5798dc2010-04-21 20:38:13 +00002142 // We have a class message, and T is the type we're
2143 // messaging. Build source-location information for it.
2144 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00002145 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00002146 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002147 }
2148 }
2149
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002150 if (TypoCorrection Corrected = CorrectTypo(
2151 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr,
2152 llvm::make_unique<ObjCInterfaceOrSuperCCC>(getCurMethodDecl()),
2153 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002154 if (Corrected.isKeyword()) {
2155 // If we've found the keyword "super" (the only keyword that would be
2156 // returned by CorrectTypo), this is a send to super.
Richard Smithf9b15102013-08-17 00:46:16 +00002157 diagnoseTypo(Corrected,
2158 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002159 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002160 } else if (ObjCInterfaceDecl *Class =
Richard Smithf9b15102013-08-17 00:46:16 +00002161 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002162 // If we found a declaration, correct when it refers to an Objective-C
2163 // class.
Richard Smithf9b15102013-08-17 00:46:16 +00002164 diagnoseTypo(Corrected,
2165 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002166 QualType T = Context.getObjCInterfaceType(Class);
2167 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2168 ReceiverType = CreateParsedType(T, TSInfo);
2169 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002170 }
2171 }
Richard Smithf9b15102013-08-17 00:46:16 +00002172
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002173 // Fall back: let the parser try to parse it as an instance message.
2174 return ObjCInstanceMessage;
2175}
Steve Naroff9527bbf2009-03-09 21:12:44 +00002176
Fangrui Song6907ce22018-07-30 19:24:48 +00002177ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002178 SourceLocation SuperLoc,
2179 Selector Sel,
2180 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002181 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002182 SourceLocation RBracLoc,
2183 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002184 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00002185 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00002186 if (!Method) {
2187 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
2188 return ExprError();
2189 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002190
Douglas Gregor4fdba132010-04-21 20:01:04 +00002191 ObjCInterfaceDecl *Class = Method->getClassInterface();
2192 if (!Class) {
Richard Smithf8812672016-12-02 22:38:31 +00002193 Diag(SuperLoc, diag::err_no_super_class_message)
Douglas Gregor4fdba132010-04-21 20:01:04 +00002194 << Method->getDeclName();
2195 return ExprError();
2196 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002197
Douglas Gregore83b9562015-07-07 03:57:53 +00002198 QualType SuperTy(Class->getSuperClassType(), 0);
2199 if (SuperTy.isNull()) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002200 // The current class does not have a superclass.
Richard Smithf8812672016-12-02 22:38:31 +00002201 Diag(SuperLoc, diag::err_root_class_cannot_use_super)
Ted Kremenek499897b2011-01-23 17:21:34 +00002202 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002203 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002204 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002205
Douglas Gregor4fdba132010-04-21 20:01:04 +00002206 // We are in a method whose class has a superclass, so 'super'
2207 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00002208 if (Method->getSelector() == Sel)
2209 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00002210
Jordan Rose2afd6612012-10-19 16:05:26 +00002211 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00002212 // Since we are in an instance method, this is an instance
2213 // message to the superclass instance.
Douglas Gregor4fdba132010-04-21 20:01:04 +00002214 SuperTy = Context.getObjCObjectPointerType(SuperTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00002215 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2216 Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002217 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002218 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002219
Douglas Gregor4fdba132010-04-21 20:01:04 +00002220 // Since we are in a class method, this is a class message to
2221 // the superclass.
Craig Topperc3ec1492014-05-26 06:22:03 +00002222 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
Douglas Gregore83b9562015-07-07 03:57:53 +00002223 SuperTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00002224 SuperLoc, Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002225 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002226}
2227
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002228ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2229 bool isSuperReceiver,
2230 SourceLocation Loc,
2231 Selector Sel,
2232 ObjCMethodDecl *Method,
2233 MultiExprArg Args) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002234 TypeSourceInfo *receiverTypeInfo = nullptr;
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002235 if (!ReceiverType.isNull())
2236 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2237
2238 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2239 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2240 Sel, Method, Loc, Loc, Loc, Args,
2241 /*isImplicit=*/true);
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002242}
2243
Ted Kremeneke65b0862012-03-06 20:05:56 +00002244static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2245 unsigned DiagID,
2246 bool (*refactor)(const ObjCMessageExpr *,
2247 const NSAPI &, edit::Commit &)) {
2248 SourceLocation MsgLoc = Msg->getExprLoc();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002249 if (S.Diags.isIgnored(DiagID, MsgLoc))
Ted Kremeneke65b0862012-03-06 20:05:56 +00002250 return;
2251
2252 SourceManager &SM = S.SourceMgr;
2253 edit::Commit ECommit(SM, S.LangOpts);
2254 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2255 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2256 << Msg->getSelector() << Msg->getSourceRange();
2257 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2258 if (!ECommit.isCommitable())
2259 return;
2260 for (edit::Commit::edit_iterator
2261 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2262 const edit::Commit::Edit &Edit = *I;
2263 switch (Edit.Kind) {
2264 case edit::Commit::Act_Insert:
2265 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2266 Edit.Text,
2267 Edit.BeforePrev));
2268 break;
2269 case edit::Commit::Act_InsertFromRange:
2270 Builder.AddFixItHint(
2271 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2272 Edit.getInsertFromRange(SM),
2273 Edit.BeforePrev));
2274 break;
2275 case edit::Commit::Act_Remove:
2276 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2277 break;
2278 }
2279 }
2280 }
2281}
2282
2283static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2284 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2285 edit::rewriteObjCRedundantCallWithLiteral);
2286}
2287
Alex Lorenz0e23c612017-03-06 15:58:34 +00002288static void checkFoundationAPI(Sema &S, SourceLocation Loc,
2289 const ObjCMethodDecl *Method,
2290 ArrayRef<Expr *> Args, QualType ReceiverType,
2291 bool IsClassObjectCall) {
2292 // Check if this is a performSelector method that uses a selector that returns
2293 // a record or a vector type.
Alex Lorenz5ffe4e12017-03-23 10:46:05 +00002294 if (Method->getSelector().getMethodFamily() != OMF_performSelector ||
2295 Args.empty())
Alex Lorenz0e23c612017-03-06 15:58:34 +00002296 return;
2297 const auto *SE = dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens());
2298 if (!SE)
2299 return;
2300 ObjCMethodDecl *ImpliedMethod;
2301 if (!IsClassObjectCall) {
2302 const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>();
2303 if (!OPT || !OPT->getInterfaceDecl())
2304 return;
2305 ImpliedMethod =
2306 OPT->getInterfaceDecl()->lookupInstanceMethod(SE->getSelector());
2307 if (!ImpliedMethod)
2308 ImpliedMethod =
2309 OPT->getInterfaceDecl()->lookupPrivateMethod(SE->getSelector());
2310 } else {
2311 const auto *IT = ReceiverType->getAs<ObjCInterfaceType>();
2312 if (!IT)
2313 return;
2314 ImpliedMethod = IT->getDecl()->lookupClassMethod(SE->getSelector());
2315 if (!ImpliedMethod)
2316 ImpliedMethod =
2317 IT->getDecl()->lookupPrivateClassMethod(SE->getSelector());
2318 }
2319 if (!ImpliedMethod)
2320 return;
2321 QualType Ret = ImpliedMethod->getReturnType();
2322 if (Ret->isRecordType() || Ret->isVectorType() || Ret->isExtVectorType()) {
2323 QualType Ret = ImpliedMethod->getReturnType();
2324 S.Diag(Loc, diag::warn_objc_unsafe_perform_selector)
2325 << Method->getSelector()
2326 << (!Ret->isRecordType()
2327 ? /*Vector*/ 2
2328 : Ret->isUnionType() ? /*Union*/ 1 : /*Struct*/ 0);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002329 S.Diag(ImpliedMethod->getBeginLoc(),
Alex Lorenz0e23c612017-03-06 15:58:34 +00002330 diag::note_objc_unsafe_perform_selector_method_declared_here)
2331 << ImpliedMethod->getSelector() << Ret;
2332 }
2333}
2334
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002335/// Diagnose use of %s directive in an NSString which is being passed
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002336/// as formatting string to formatting method.
2337static void
2338DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2339 ObjCMethodDecl *Method,
2340 Selector Sel,
2341 Expr **Args, unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002342 unsigned Idx = 0;
2343 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002344 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2345 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002346 Idx = 0;
2347 Format = true;
2348 }
2349 else if (Method) {
2350 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2351 if (S.GetFormatNSStringIdx(I, Idx)) {
2352 Format = true;
2353 break;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002354 }
2355 }
2356 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002357 if (!Format || NumArgs <= Idx)
2358 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002359
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002360 Expr *FormatExpr = Args[Idx];
2361 if (ObjCStringLiteral *OSL =
2362 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2363 StringLiteral *FormatString = OSL->getString();
2364 if (S.FormatStringHasSArg(FormatString)) {
2365 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2366 << "%s" << 0 << 0;
2367 if (Method)
2368 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2369 << Method->getDeclName();
2370 }
2371 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002372}
2373
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002374/// Build an Objective-C class message expression.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002375///
2376/// This routine takes care of both normal class messages and
2377/// class messages to the superclass.
2378///
2379/// \param ReceiverTypeInfo Type source information that describes the
2380/// receiver of this message. This may be NULL, in which case we are
2381/// sending to the superclass and \p SuperLoc must be a valid source
2382/// location.
2383
2384/// \param ReceiverType The type of the object receiving the
2385/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2386/// type as that refers to. For a superclass send, this is the type of
2387/// the superclass.
2388///
2389/// \param SuperLoc The location of the "super" keyword in a
2390/// superclass message.
2391///
2392/// \param Sel The selector to which the message is being sent.
2393///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002394/// \param Method The method that this class message is invoking, if
2395/// already known.
2396///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002397/// \param LBracLoc The location of the opening square bracket ']'.
2398///
James Dennettffad8b72012-06-22 08:10:18 +00002399/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002400///
James Dennettffad8b72012-06-22 08:10:18 +00002401/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002402ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002403 QualType ReceiverType,
2404 SourceLocation SuperLoc,
2405 Selector Sel,
2406 ObjCMethodDecl *Method,
Fangrui Song6907ce22018-07-30 19:24:48 +00002407 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002408 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002409 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002410 MultiExprArg ArgsIn,
2411 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002412 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002413 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002414 if (LBracLoc.isInvalid()) {
2415 Diag(Loc, diag::err_missing_open_square_message_send)
2416 << FixItHint::CreateInsertion(Loc, "[");
2417 LBracLoc = Loc;
2418 }
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002419 ArrayRef<SourceLocation> SelectorSlotLocs;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002420 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002421 SelectorSlotLocs = SelectorLocs;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002422 else
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002423 SelectorSlotLocs = Loc;
2424 SourceLocation SelLoc = SelectorSlotLocs.front();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002425
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002426 if (ReceiverType->isDependentType()) {
2427 // If the receiver type is dependent, we can't type-check anything
2428 // at this point. Build a dependent expression.
2429 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002430 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002431 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002432 return ObjCMessageExpr::Create(
2433 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2434 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2435 isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002436 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002437
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002438 // Find the class to which we are sending this message.
Craig Topperc3ec1492014-05-26 06:22:03 +00002439 ObjCInterfaceDecl *Class = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00002440 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2441 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002442 Diag(Loc, diag::err_invalid_receiver_class_message)
2443 << ReceiverType;
2444 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002445 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002446 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002447 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002448 if (!getLangOpts().CPlusPlus)
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002449 (void)DiagnoseUseOfDecl(Class, SelectorSlotLocs);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002450 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002451 if (!Method) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002452 SourceRange TypeRange
Douglas Gregor4123a862011-11-14 22:10:01 +00002453 = SuperLoc.isValid()? SourceRange(SuperLoc)
2454 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002455 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002456 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002457 ? diag::err_arc_receiver_forward_class
2458 : diag::warn_receiver_forward_class),
2459 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002460 // A forward class used in messaging is treated as a 'Class'
Fangrui Song6907ce22018-07-30 19:24:48 +00002461 Method = LookupFactoryMethodInGlobalPool(Sel,
Douglas Gregorb5186b12010-04-22 17:01:48 +00002462 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002463 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002464 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2465 << Method->getDeclName();
2466 }
2467 if (!Method)
2468 Method = Class->lookupClassMethod(Sel);
2469
2470 // If we have an implementation in scope, check "private" methods.
2471 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002472 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002473
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002474 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002475 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002476 }
Mike Stump11289f42009-09-09 15:08:12 +00002477
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002478 // Check the argument types and determine the result type.
2479 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002480 ExprValueKind VK = VK_RValue;
2481
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002482 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002483 Expr **Args = ArgsIn.data();
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002484 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2485 Sel, SelectorLocs,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00002486 Method, true,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002487 SuperLoc.isValid(), LBracLoc, RBracLoc,
2488 SourceRange(),
Douglas Gregor33823722011-06-11 01:09:30 +00002489 ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002490 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002491
Alp Toker314cc812014-01-25 16:55:45 +00002492 if (Method && !Method->getReturnType()->isVoidType() &&
2493 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002494 diag::err_illegal_message_expr_incomplete_type))
2495 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +00002496
Fariborz Jahaniane8b45502014-08-22 19:52:49 +00002497 // Warn about explicit call of +initialize on its own class. But not on 'super'.
Fariborz Jahanian42292282014-08-25 21:27:38 +00002498 if (Method && Method->getMethodFamily() == OMF_initialize) {
2499 if (!SuperLoc.isValid()) {
2500 const ObjCInterfaceDecl *ID =
2501 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2502 if (ID == Class) {
2503 Diag(Loc, diag::warn_direct_initialize_call);
2504 Diag(Method->getLocation(), diag::note_method_declared_at)
2505 << Method->getDeclName();
2506 }
2507 }
2508 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2509 // [super initialize] is allowed only within an +initialize implementation
2510 if (CurMeth->getMethodFamily() != OMF_initialize) {
2511 Diag(Loc, diag::warn_direct_super_initialize_call);
2512 Diag(Method->getLocation(), diag::note_method_declared_at)
2513 << Method->getDeclName();
2514 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2515 << CurMeth->getDeclName();
2516 }
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002517 }
2518 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002519
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002520 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
Fangrui Song6907ce22018-07-30 19:24:48 +00002521
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002522 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002523 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002524 if (SuperLoc.isValid())
Fangrui Song6907ce22018-07-30 19:24:48 +00002525 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2526 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002527 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002528 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002529 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002530 else {
Fangrui Song6907ce22018-07-30 19:24:48 +00002531 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002532 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002533 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002534 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002535 if (!isImplicit)
2536 checkCocoaAPI(*this, Result);
2537 }
Alex Lorenz0e23c612017-03-06 15:58:34 +00002538 if (Method)
2539 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
2540 ReceiverType, /*IsClassObjectCall=*/true);
Douglas Gregoraae38d62010-05-22 05:17:18 +00002541 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002542}
2543
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002544// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002545// ArgExprs is optional - if it is present, the number of expressions
2546// is obtained from Sel.getNumArgs().
Fangrui Song6907ce22018-07-30 19:24:48 +00002547ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002548 ParsedType Receiver,
2549 Selector Sel,
2550 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002551 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002552 SourceLocation RBracLoc,
2553 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002554 TypeSourceInfo *ReceiverTypeInfo;
2555 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2556 if (ReceiverType.isNull())
2557 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002558
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002559 if (!ReceiverTypeInfo)
2560 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2561
Fangrui Song6907ce22018-07-30 19:24:48 +00002562 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002563 /*SuperLoc=*/SourceLocation(), Sel,
2564 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2565 Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002566}
2567
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002568ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2569 QualType ReceiverType,
2570 SourceLocation Loc,
2571 Selector Sel,
2572 ObjCMethodDecl *Method,
2573 MultiExprArg Args) {
2574 return BuildInstanceMessage(Receiver, ReceiverType,
2575 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2576 Sel, Method, Loc, Loc, Loc, Args,
2577 /*isImplicit=*/true);
2578}
2579
Alex Lorenz5e895cf2017-03-15 17:16:41 +00002580static bool isMethodDeclaredInRootProtocol(Sema &S, const ObjCMethodDecl *M) {
2581 if (!S.NSAPIObj)
2582 return false;
2583 const auto *Protocol = dyn_cast<ObjCProtocolDecl>(M->getDeclContext());
2584 if (!Protocol)
2585 return false;
2586 const IdentifierInfo *II = S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
2587 if (const auto *RootClass = dyn_cast_or_null<ObjCInterfaceDecl>(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002588 S.LookupSingleName(S.TUScope, II, Protocol->getBeginLoc(),
Alex Lorenz5e895cf2017-03-15 17:16:41 +00002589 Sema::LookupOrdinaryName))) {
2590 for (const ObjCProtocolDecl *P : RootClass->all_referenced_protocols()) {
2591 if (P->getCanonicalDecl() == Protocol->getCanonicalDecl())
2592 return true;
2593 }
2594 }
2595 return false;
2596}
2597
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002598/// Build an Objective-C instance message expression.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002599///
2600/// This routine takes care of both normal instance messages and
2601/// instance messages to the superclass instance.
2602///
2603/// \param Receiver The expression that computes the object that will
2604/// receive this message. This may be empty, in which case we are
2605/// sending to the superclass instance and \p SuperLoc must be a valid
2606/// source location.
2607///
2608/// \param ReceiverType The (static) type of the object receiving the
2609/// message. When a \p Receiver expression is provided, this is the
2610/// same type as that expression. For a superclass instance send, this
2611/// is a pointer to the type of the superclass.
2612///
2613/// \param SuperLoc The location of the "super" keyword in a
2614/// superclass instance message.
2615///
2616/// \param Sel The selector to which the message is being sent.
2617///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002618/// \param Method The method that this instance message is invoking, if
2619/// already known.
2620///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002621/// \param LBracLoc The location of the opening square bracket ']'.
2622///
James Dennettffad8b72012-06-22 08:10:18 +00002623/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002624///
James Dennettffad8b72012-06-22 08:10:18 +00002625/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002626ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002627 QualType ReceiverType,
2628 SourceLocation SuperLoc,
2629 Selector Sel,
2630 ObjCMethodDecl *Method,
Fangrui Song6907ce22018-07-30 19:24:48 +00002631 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002632 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002633 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002634 MultiExprArg ArgsIn,
2635 bool isImplicit) {
Chandler Carruth3d402842016-11-04 06:11:54 +00002636 assert((Receiver || SuperLoc.isValid()) && "If the Receiver is null, the "
2637 "SuperLoc must be valid so we can "
2638 "use it instead.");
2639
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002640 // The location of the receiver.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002641 SourceLocation Loc = SuperLoc.isValid() ? SuperLoc : Receiver->getBeginLoc();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002642 SourceRange RecRange =
2643 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002644 ArrayRef<SourceLocation> SelectorSlotLocs;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002645 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002646 SelectorSlotLocs = SelectorLocs;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002647 else
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002648 SelectorSlotLocs = Loc;
2649 SourceLocation SelLoc = SelectorSlotLocs.front();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002650
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002651 if (LBracLoc.isInvalid()) {
2652 Diag(Loc, diag::err_missing_open_square_message_send)
2653 << FixItHint::CreateInsertion(Loc, "[");
2654 LBracLoc = Loc;
2655 }
2656
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002657 // If we have a receiver expression, perform appropriate promotions
2658 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002659 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002660 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002661 ExprResult Result;
2662 if (Receiver->getType() == Context.UnknownAnyTy)
2663 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2664 else
2665 Result = CheckPlaceholderExpr(Receiver);
2666 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002667 Receiver = Result.get();
John McCall4124c492011-10-17 18:40:02 +00002668 }
2669
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002670 if (Receiver->isTypeDependent()) {
2671 // If the receiver is type-dependent, we can't type-check anything
2672 // at this point. Build a dependent expression.
2673 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002674 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002675 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002676 return ObjCMessageExpr::Create(
2677 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2678 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2679 RBracLoc, isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002680 }
2681
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002682 // If necessary, apply function/array conversion to the receiver.
2683 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002684 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2685 if (Result.isInvalid())
2686 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002687 Receiver = Result.get();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002688 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002689
2690 // If the receiver is an ObjC pointer, a block pointer, or an
2691 // __attribute__((NSObject)) pointer, we don't need to do any
2692 // special conversion in order to look up a receiver.
2693 if (ReceiverType->isObjCRetainableType()) {
2694 // do nothing
2695 } else if (!getLangOpts().ObjCAutoRefCount &&
2696 !Context.getObjCIdType().isNull() &&
Fangrui Song6907ce22018-07-30 19:24:48 +00002697 (ReceiverType->isPointerType() ||
John McCall80c93a02013-03-01 09:20:14 +00002698 ReceiverType->isIntegerType())) {
2699 // Implicitly convert integers and pointers to 'id' but emit a warning.
2700 // But not in ARC.
2701 Diag(Loc, diag::warn_bad_receiver_type)
Fangrui Song6907ce22018-07-30 19:24:48 +00002702 << ReceiverType
John McCall80c93a02013-03-01 09:20:14 +00002703 << Receiver->getSourceRange();
2704 if (ReceiverType->isPointerType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002705 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002706 CK_CPointerToObjCPointerCast).get();
John McCall80c93a02013-03-01 09:20:14 +00002707 } else {
2708 // TODO: specialized warning on null receivers?
2709 bool IsNull = Receiver->isNullPointerConstant(Context,
2710 Expr::NPC_ValueDependentIsNull);
2711 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2712 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002713 Kind).get();
John McCall80c93a02013-03-01 09:20:14 +00002714 }
2715 ReceiverType = Receiver->getType();
2716 } else if (getLangOpts().CPlusPlus) {
Douglas Gregor4b60a152013-11-07 22:34:54 +00002717 // The receiver must be a complete type.
2718 if (RequireCompleteType(Loc, Receiver->getType(),
2719 diag::err_incomplete_receiver_type))
2720 return ExprError();
2721
John McCall80c93a02013-03-01 09:20:14 +00002722 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2723 if (result.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002724 Receiver = result.get();
John McCall80c93a02013-03-01 09:20:14 +00002725 ReceiverType = Receiver->getType();
2726 }
2727 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002728 }
2729
Alex Lorenzd9f12842017-08-25 16:12:17 +00002730 if (ReceiverType->isObjCIdType() && !isImplicit)
2731 Diag(Receiver->getExprLoc(), diag::warn_messaging_unqualified_id);
2732
John McCall80c93a02013-03-01 09:20:14 +00002733 // There's a somewhat weird interaction here where we assume that we
2734 // won't actually have a method unless we also don't need to do some
2735 // of the more detailed type-checking on the receiver.
2736
Douglas Gregorb5186b12010-04-22 17:01:48 +00002737 if (!Method) {
Douglas Gregorab209d82015-07-07 03:58:42 +00002738 // Handle messages to id and __kindof types (where we use the
2739 // global method pool).
Douglas Gregorab209d82015-07-07 03:58:42 +00002740 const ObjCObjectType *typeBound = nullptr;
2741 bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
2742 typeBound);
2743 if (receiverIsIdLike || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002744 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
Manman Rend2a3cd72016-04-07 19:30:20 +00002745 SmallVector<ObjCMethodDecl*, 4> Methods;
Manman Ren7ed4f982016-04-07 19:32:24 +00002746 // If we have a type bound, further filter the methods.
Manman Rend2a3cd72016-04-07 19:30:20 +00002747 CollectMultipleMethodsInGlobalPool(Sel, Methods, true/*InstanceFirst*/,
Manman Ren7ed4f982016-04-07 19:32:24 +00002748 true/*CheckTheOther*/, typeBound);
Manman Rend2a3cd72016-04-07 19:30:20 +00002749 if (!Methods.empty()) {
George Burgess IV52d07de2016-09-01 01:26:58 +00002750 // We choose the first method as the initial candidate, then try to
Manman Rend2a3cd72016-04-07 19:30:20 +00002751 // select a better one.
2752 Method = Methods[0];
2753
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002754 if (ObjCMethodDecl *BestMethod =
Manman Rend2a3cd72016-04-07 19:30:20 +00002755 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(), Methods))
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002756 Method = BestMethod;
Manman Rend2a3cd72016-04-07 19:30:20 +00002757
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002758 if (!AreMultipleMethodsInGlobalPool(Sel, Method,
2759 SourceRange(LBracLoc, RBracLoc),
Manman Rend2a3cd72016-04-07 19:30:20 +00002760 receiverIsIdLike, Methods))
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002761 DiagnoseUseOfDecl(Method, SelectorSlotLocs);
Fariborz Jahanian05e77f82014-11-07 23:51:15 +00002762 }
Douglas Gregorab209d82015-07-07 03:58:42 +00002763 } else if (ReceiverType->isObjCClassOrClassKindOfType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002764 ReceiverType->isObjCQualifiedClassType()) {
2765 // Handle messages to Class.
Nico Weber2e0c8f72014-12-27 03:58:08 +00002766 // We allow sending a message to a qualified Class ("Class<foo>"), which
2767 // is ok as long as one of the protocols implements the selector (if not,
2768 // warn).
Douglas Gregorab209d82015-07-07 03:58:42 +00002769 if (!ReceiverType->isObjCClassOrClassKindOfType()) {
2770 const ObjCObjectPointerType *QClassTy
2771 = ReceiverType->getAsObjCQualifiedClassType();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002772 // Search protocols for class methods.
2773 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2774 if (!Method) {
2775 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2776 // warn if instance method found for a Class message.
Alex Lorenz5e895cf2017-03-15 17:16:41 +00002777 if (Method && !isMethodDeclaredInRootProtocol(*this, Method)) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002778 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002779 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002780 Diag(Method->getLocation(), diag::note_method_declared_at)
2781 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002782 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002783 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002784 } else {
2785 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2786 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2787 // First check the public methods in the class interface.
2788 Method = ClassDecl->lookupClassMethod(Sel);
2789
2790 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002791 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002792 }
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002793 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs))
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002794 return ExprError();
2795 }
2796 if (!Method) {
2797 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002798 if (!Receiver || !isSelfExpr(Receiver)) {
Manman Rend2a3cd72016-04-07 19:30:20 +00002799 // If no class (factory) method was found, check if an _instance_
2800 // method of the same name exists in the root class only.
2801 SmallVector<ObjCMethodDecl*, 4> Methods;
2802 CollectMultipleMethodsInGlobalPool(Sel, Methods,
2803 false/*InstanceFirst*/,
2804 true/*CheckTheOther*/);
2805 if (!Methods.empty()) {
George Burgess IV52d07de2016-09-01 01:26:58 +00002806 // We choose the first method as the initial candidate, then try
Manman Rend2a3cd72016-04-07 19:30:20 +00002807 // to select a better one.
2808 Method = Methods[0];
2809
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002810 // If we find an instance method, emit warning.
Manman Rend2a3cd72016-04-07 19:30:20 +00002811 if (Method->isInstanceMethod()) {
2812 if (const ObjCInterfaceDecl *ID =
2813 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2814 if (ID->getSuperClass())
2815 Diag(SelLoc, diag::warn_root_inst_method_not_found)
2816 << Sel << SourceRange(LBracLoc, RBracLoc);
2817 }
2818 }
2819
2820 if (ObjCMethodDecl *BestMethod =
2821 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2822 Methods))
2823 Method = BestMethod;
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002824 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002825 }
2826 }
2827 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002828 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002829 ObjCInterfaceDecl *ClassDecl = nullptr;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002830
2831 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2832 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002833 // And as long as message is not deprecated/unavailable (warn if it is).
Fangrui Song6907ce22018-07-30 19:24:48 +00002834 if (const ObjCObjectPointerType *QIdTy
Douglas Gregorb5186b12010-04-22 17:01:48 +00002835 = ReceiverType->getAsObjCQualifiedIdType()) {
2836 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002837 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2838 if (!Method)
2839 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002840 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002841 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002842 } else if (const ObjCObjectPointerType *OCIType
2843 = ReceiverType->getAsObjCInterfacePointerType()) {
2844 // We allow sending a message to a pointer to an interface (an object).
2845 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002846
Douglas Gregor4123a862011-11-14 22:10:01 +00002847 // Try to complete the type. Under ARC, this is a hard error from which
2848 // we don't try to recover.
Richard Smithdb0ac552015-12-18 22:40:25 +00002849 // FIXME: In the non-ARC case, this will still be a hard error if the
2850 // definition is found in a module that's not visible.
Craig Topperc3ec1492014-05-26 06:22:03 +00002851 const ObjCInterfaceDecl *forwardClass = nullptr;
Douglas Gregor4123a862011-11-14 22:10:01 +00002852 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002853 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002854 ? diag::err_arc_receiver_forward_instance
2855 : diag::warn_receiver_forward_instance,
2856 Receiver? Receiver->getSourceRange()
2857 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002858 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002859 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +00002860
Douglas Gregor4123a862011-11-14 22:10:01 +00002861 forwardClass = OCIType->getInterfaceDecl();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002862 Diag(Receiver ? Receiver->getBeginLoc() : SuperLoc,
2863 diag::note_receiver_is_id);
Craig Topperc3ec1492014-05-26 06:22:03 +00002864 Method = nullptr;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002865 } else {
2866 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002867 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002868
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002869 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002870 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002871 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00002872
Douglas Gregorb5186b12010-04-22 17:01:48 +00002873 if (!Method) {
2874 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002875 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002876
David Blaikiebbafb8a2012-03-11 07:00:24 +00002877 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002878 Diag(SelLoc, diag::err_arc_may_not_respond)
2879 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002880 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002881 return ExprError();
2882 }
2883
Douglas Gregor486b74e2011-09-27 16:10:05 +00002884 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002885 // If we still haven't found a method, look in the global pool. This
2886 // behavior isn't very desirable, however we need it for GCC
2887 // compatibility. FIXME: should we deviate??
2888 if (OCIType->qual_empty()) {
Manman Rend2a3cd72016-04-07 19:30:20 +00002889 SmallVector<ObjCMethodDecl*, 4> Methods;
2890 CollectMultipleMethodsInGlobalPool(Sel, Methods,
2891 true/*InstanceFirst*/,
2892 false/*CheckTheOther*/);
2893 if (!Methods.empty()) {
George Burgess IV52d07de2016-09-01 01:26:58 +00002894 // We choose the first method as the initial candidate, then try
Manman Rend2a3cd72016-04-07 19:30:20 +00002895 // to select a better one.
2896 Method = Methods[0];
2897
2898 if (ObjCMethodDecl *BestMethod =
2899 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2900 Methods))
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002901 Method = BestMethod;
Manman Rend2a3cd72016-04-07 19:30:20 +00002902
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002903 AreMultipleMethodsInGlobalPool(Sel, Method,
2904 SourceRange(LBracLoc, RBracLoc),
Manman Rend2a3cd72016-04-07 19:30:20 +00002905 true/*receiverIdOrClass*/,
2906 Methods);
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002907 }
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002908 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002909 Diag(SelLoc, diag::warn_maynot_respond)
2910 << OCIType->getInterfaceDecl()->getIdentifier()
2911 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002912 }
2913 }
2914 }
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002915 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002916 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002917 } else {
John McCall80c93a02013-03-01 09:20:14 +00002918 // Reject other random receiver types (e.g. structs).
2919 Diag(Loc, diag::err_bad_receiver_type)
2920 << ReceiverType << Receiver->getSourceRange();
2921 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002922 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002923 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002924 }
Mike Stump11289f42009-09-09 15:08:12 +00002925
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002926 FunctionScopeInfo *DIFunctionScopeInfo =
2927 (Method && Method->getMethodFamily() == OMF_init)
Craig Topperc3ec1492014-05-26 06:22:03 +00002928 ? getEnclosingFunction() : nullptr;
2929
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002930 if (DIFunctionScopeInfo &&
2931 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002932 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2933 bool isDesignatedInitChain = false;
2934 if (SuperLoc.isValid()) {
2935 if (const ObjCObjectPointerType *
2936 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2937 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
Argyrios Kyrtzidisd664a342013-12-13 03:48:17 +00002938 // Either we know this is a designated initializer or we
2939 // conservatively assume it because we don't know for sure.
2940 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2941 ID->isDesignatedInitializer(Sel)) {
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002942 isDesignatedInitChain = true;
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002943 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002944 }
2945 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002946 }
2947 }
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002948 if (!isDesignatedInitChain) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002949 const ObjCMethodDecl *InitMethod = nullptr;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002950 bool isDesignated =
2951 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2952 assert(isDesignated && InitMethod);
2953 (void)isDesignated;
2954 Diag(SelLoc, SuperLoc.isValid() ?
2955 diag::warn_objc_designated_init_non_designated_init_call :
2956 diag::warn_objc_designated_init_non_super_designated_init_call);
2957 Diag(InitMethod->getLocation(),
2958 diag::note_objc_designated_init_marked_here);
2959 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002960 }
2961
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002962 if (DIFunctionScopeInfo &&
2963 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002964 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2965 if (SuperLoc.isValid()) {
2966 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2967 } else {
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002968 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002969 }
2970 }
2971
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002972 // Check the message arguments.
2973 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002974 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002975 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002976 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00002977 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2978 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002979 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2980 Sel, SelectorLocs, Method,
Fangrui Song6907ce22018-07-30 19:24:48 +00002981 ClassMessage, SuperLoc.isValid(),
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002982 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002983 return ExprError();
Alp Toker314cc812014-01-25 16:55:45 +00002984
2985 if (Method && !Method->getReturnType()->isVoidType() &&
2986 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002987 diag::err_illegal_message_expr_incomplete_type))
2988 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00002989
Fangrui Song6907ce22018-07-30 19:24:48 +00002990 // In ARC, forbid the user from sending messages to
John McCall31168b02011-06-15 23:02:42 +00002991 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002992 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002993 ObjCMethodFamily family =
2994 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2995 switch (family) {
2996 case OMF_init:
2997 if (Method)
2998 checkInitMethod(Method, ReceiverType);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00002999 break;
John McCall31168b02011-06-15 23:02:42 +00003000
3001 case OMF_None:
3002 case OMF_alloc:
3003 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00003004 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00003005 case OMF_mutableCopy:
3006 case OMF_new:
3007 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00003008 case OMF_initialize:
John McCall31168b02011-06-15 23:02:42 +00003009 break;
3010
3011 case OMF_dealloc:
3012 case OMF_retain:
3013 case OMF_release:
3014 case OMF_autorelease:
3015 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00003016 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
3017 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00003018 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00003019
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003020 case OMF_performSelector:
3021 if (Method && NumArgs >= 1) {
Alex Lorenz51c01282017-02-20 17:55:15 +00003022 if (const auto *SelExp =
3023 dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens())) {
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003024 Selector ArgSel = SelExp->getSelector();
Fangrui Song6907ce22018-07-30 19:24:48 +00003025 ObjCMethodDecl *SelMethod =
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003026 LookupInstanceMethodInGlobalPool(ArgSel,
3027 SelExp->getSourceRange());
3028 if (!SelMethod)
3029 SelMethod =
3030 LookupFactoryMethodInGlobalPool(ArgSel,
3031 SelExp->getSourceRange());
3032 if (SelMethod) {
3033 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
3034 switch (SelFamily) {
3035 case OMF_alloc:
3036 case OMF_copy:
3037 case OMF_mutableCopy:
3038 case OMF_new:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003039 case OMF_init:
3040 // Issue error, unless ns_returns_not_retained.
3041 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003042 // selector names a +1 method
3043 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003044 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00003045 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3046 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003047 }
3048 break;
3049 default:
3050 // +0 call. OK. unless ns_returns_retained.
3051 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
3052 // selector names a +1 method
Fangrui Song6907ce22018-07-30 19:24:48 +00003053 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003054 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00003055 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3056 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003057 }
3058 break;
3059 }
3060 }
3061 } else {
3062 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00003063 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003064 Diag(Args[0]->getExprLoc(), diag::note_used_here);
3065 }
3066 }
3067 break;
John McCall31168b02011-06-15 23:02:42 +00003068 }
3069 }
3070
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003071 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
Fangrui Song6907ce22018-07-30 19:24:48 +00003072
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003073 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00003074 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003075 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00003076 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00003077 SuperLoc, /*IsInstanceSuper=*/true,
Fangrui Song6907ce22018-07-30 19:24:48 +00003078 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00003079 makeArrayRef(Args, NumArgs), RBracLoc,
3080 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00003081 else {
John McCall7decc9e2010-11-18 06:31:45 +00003082 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00003083 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00003084 makeArrayRef(Args, NumArgs), RBracLoc,
3085 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00003086 if (!isImplicit)
3087 checkCocoaAPI(*this, Result);
3088 }
Alex Lorenz0e23c612017-03-06 15:58:34 +00003089 if (Method) {
3090 bool IsClassObjectCall = ClassMessage;
3091 // 'self' message receivers in class methods should be treated as message
3092 // sends to the class object in order for the semantic checks to be
3093 // performed correctly. Messages to 'super' already count as class messages,
3094 // so they don't need to be handled here.
3095 if (Receiver && isSelfExpr(Receiver)) {
3096 if (const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>()) {
3097 if (OPT->getObjectType()->isObjCClass()) {
3098 if (const auto *CurMeth = getCurMethodDecl()) {
3099 IsClassObjectCall = true;
3100 ReceiverType =
3101 Context.getObjCInterfaceType(CurMeth->getClassInterface());
3102 }
3103 }
3104 }
3105 }
3106 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
3107 ReceiverType, IsClassObjectCall);
3108 }
John McCall31168b02011-06-15 23:02:42 +00003109
David Blaikiebbafb8a2012-03-11 07:00:24 +00003110 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00003111 // In ARC, annotate delegate init calls.
3112 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00003113 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00003114 // Only consider init calls *directly* in init implementations,
3115 // not within blocks.
3116 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
3117 if (method && method->getMethodFamily() == OMF_init) {
3118 // The implicit assignment to self means we also don't want to
3119 // consume the result.
3120 Result->setDelegateInitCall(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003121 return Result;
John McCall31168b02011-06-15 23:02:42 +00003122 }
3123 }
3124
3125 // In ARC, check for message sends which are likely to introduce
3126 // retain cycles.
3127 checkRetainCycles(Result);
Brian Kelleycafd9122017-03-29 17:55:11 +00003128 }
Jordan Rose22487652012-10-11 16:06:21 +00003129
Brian Kelleycafd9122017-03-29 17:55:11 +00003130 if (getLangOpts().ObjCWeak) {
Jordan Rose22487652012-10-11 16:06:21 +00003131 if (!isImplicit && Method) {
3132 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
3133 bool IsWeak =
3134 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
3135 if (!IsWeak && Sel.isUnarySelector())
3136 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003137 if (IsWeak &&
3138 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
3139 getCurFunction()->recordUseOfWeak(Result, Prop);
Jordan Rose22487652012-10-11 16:06:21 +00003140 }
3141 }
John McCall31168b02011-06-15 23:02:42 +00003142 }
Alex Denisove1d882c2015-03-04 17:55:52 +00003143
3144 CheckObjCCircularContainer(Result);
3145
Douglas Gregoraae38d62010-05-22 05:17:18 +00003146 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003147}
3148
Fariborz Jahanian02447d82013-01-22 18:35:43 +00003149static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
3150 if (ObjCSelectorExpr *OSE =
3151 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
3152 Selector Sel = OSE->getSelector();
3153 SourceLocation Loc = OSE->getAtLoc();
Chandler Carruth12c8f652015-03-27 00:55:05 +00003154 auto Pos = S.ReferencedSelectors.find(Sel);
Fariborz Jahanian02447d82013-01-22 18:35:43 +00003155 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
3156 S.ReferencedSelectors.erase(Pos);
3157 }
3158}
3159
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003160// ActOnInstanceMessage - used for both unary and keyword messages.
3161// ArgExprs is optional - if it is present, the number of expressions
3162// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00003163ExprResult Sema::ActOnInstanceMessage(Scope *S,
Fangrui Song6907ce22018-07-30 19:24:48 +00003164 Expr *Receiver,
John McCalldadc5752010-08-24 06:29:42 +00003165 Selector Sel,
3166 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00003167 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00003168 SourceLocation RBracLoc,
3169 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003170 if (!Receiver)
3171 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00003172
3173 // A ParenListExpr can show up while doing error recovery with invalid code.
3174 if (isa<ParenListExpr>(Receiver)) {
3175 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
3176 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003177 Receiver = Result.get();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00003178 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003179
Fariborz Jahanian17748062013-01-22 19:05:17 +00003180 if (RespondsToSelectorSel.isNull()) {
3181 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
3182 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
3183 }
3184 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00003185 RemoveSelectorFromWarningCache(*this, Args[0]);
Craig Topperc3ec1492014-05-26 06:22:03 +00003186
John McCallb268a282010-08-23 23:25:46 +00003187 return BuildInstanceMessage(Receiver, Receiver->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003188 /*SuperLoc=*/SourceLocation(), Sel,
3189 /*Method=*/nullptr, LBracLoc, SelectorLocs,
3190 RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00003191}
Chris Lattner2a3569b2008-04-07 05:30:13 +00003192
John McCall31168b02011-06-15 23:02:42 +00003193enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00003194 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00003195 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00003196
3197 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00003198 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00003199
3200 /// id*, id***, void (^*)(),
3201 ACTC_indirectRetainable,
3202
3203 /// void* might be a normal C type, or it might a CF type.
3204 ACTC_voidPtr,
3205
3206 /// struct A*
3207 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00003208};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003209
John McCalle4fe2452011-10-01 01:01:08 +00003210static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
3211 return (ACTC == ACTC_retainable ||
3212 ACTC == ACTC_coreFoundation ||
3213 ACTC == ACTC_voidPtr);
3214}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003215
John McCalle4fe2452011-10-01 01:01:08 +00003216static bool isAnyCLike(ARCConversionTypeClass ACTC) {
3217 return ACTC == ACTC_none ||
3218 ACTC == ACTC_voidPtr ||
3219 ACTC == ACTC_coreFoundation;
3220}
3221
John McCall31168b02011-06-15 23:02:42 +00003222static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00003223 bool isIndirect = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003224
John McCall31168b02011-06-15 23:02:42 +00003225 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00003226 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00003227 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00003228 isIndirect = true;
3229 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003230
John McCall31168b02011-06-15 23:02:42 +00003231 // Drill through pointers and arrays recursively.
3232 while (true) {
3233 if (const PointerType *ptr = type->getAs<PointerType>()) {
3234 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00003235
3236 // The first level of pointer may be the innermost pointer on a CF type.
3237 if (!isIndirect) {
3238 if (type->isVoidType()) return ACTC_voidPtr;
3239 if (type->isRecordType()) return ACTC_coreFoundation;
3240 }
John McCall31168b02011-06-15 23:02:42 +00003241 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
3242 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
3243 } else {
3244 break;
3245 }
John McCalle4fe2452011-10-01 01:01:08 +00003246 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00003247 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003248
John McCalle4fe2452011-10-01 01:01:08 +00003249 if (isIndirect) {
3250 if (type->isObjCARCBridgableType())
3251 return ACTC_indirectRetainable;
3252 return ACTC_none;
3253 }
3254
3255 if (type->isObjCARCBridgableType())
3256 return ACTC_retainable;
3257
3258 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00003259}
3260
3261namespace {
John McCalle4fe2452011-10-01 01:01:08 +00003262 /// A result from the cast checker.
3263 enum ACCResult {
3264 /// Cannot be casted.
3265 ACC_invalid,
3266
3267 /// Can be safely retained or not retained.
3268 ACC_bottom,
3269
3270 /// Can be casted at +0.
3271 ACC_plusZero,
3272
3273 /// Can be casted at +1.
3274 ACC_plusOne
3275 };
3276 ACCResult merge(ACCResult left, ACCResult right) {
3277 if (left == right) return left;
3278 if (left == ACC_bottom) return right;
3279 if (right == ACC_bottom) return left;
3280 return ACC_invalid;
3281 }
3282
3283 /// A checker which white-lists certain expressions whose conversion
3284 /// to or from retainable type would otherwise be forbidden in ARC.
3285 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
3286 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
3287
John McCall31168b02011-06-15 23:02:42 +00003288 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00003289 ARCConversionTypeClass SourceClass;
3290 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003291 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00003292
3293 static bool isCFType(QualType type) {
3294 // Someday this can use ns_bridged. For now, it has to do this.
3295 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00003296 }
John McCalle4fe2452011-10-01 01:01:08 +00003297
3298 public:
3299 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003300 ARCConversionTypeClass target, bool diagnose)
3301 : Context(Context), SourceClass(source), TargetClass(target),
3302 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00003303
3304 using super::Visit;
3305 ACCResult Visit(Expr *e) {
3306 return super::Visit(e->IgnoreParens());
3307 }
3308
3309 ACCResult VisitStmt(Stmt *s) {
3310 return ACC_invalid;
3311 }
3312
3313 /// Null pointer constants can be casted however you please.
3314 ACCResult VisitExpr(Expr *e) {
3315 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
3316 return ACC_bottom;
3317 return ACC_invalid;
3318 }
3319
3320 /// Objective-C string literals can be safely casted.
3321 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3322 // If we're casting to any retainable type, go ahead. Global
3323 // strings are immune to retains, so this is bottom.
3324 if (isAnyRetainable(TargetClass)) return ACC_bottom;
3325
3326 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00003327 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003328
John McCalle4fe2452011-10-01 01:01:08 +00003329 /// Look through certain implicit and explicit casts.
3330 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003331 switch (e->getCastKind()) {
3332 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00003333 return ACC_bottom;
3334
John McCall31168b02011-06-15 23:02:42 +00003335 case CK_NoOp:
3336 case CK_LValueToRValue:
3337 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00003338 case CK_CPointerToObjCPointerCast:
3339 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00003340 case CK_AnyPointerToBlockPointerCast:
3341 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00003342
John McCall31168b02011-06-15 23:02:42 +00003343 default:
John McCalle4fe2452011-10-01 01:01:08 +00003344 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00003345 }
3346 }
John McCalle4fe2452011-10-01 01:01:08 +00003347
3348 /// Look through unary extension.
3349 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003350 return Visit(e->getSubExpr());
3351 }
John McCalle4fe2452011-10-01 01:01:08 +00003352
3353 /// Ignore the LHS of a comma operator.
3354 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003355 return Visit(e->getRHS());
3356 }
John McCalle4fe2452011-10-01 01:01:08 +00003357
3358 /// Conditional operators are okay if both sides are okay.
3359 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3360 ACCResult left = Visit(e->getTrueExpr());
3361 if (left == ACC_invalid) return ACC_invalid;
3362 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00003363 }
John McCalle4fe2452011-10-01 01:01:08 +00003364
John McCallfe96e0b2011-11-06 09:01:30 +00003365 /// Look through pseudo-objects.
3366 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3367 // If we're getting here, we should always have a result.
3368 return Visit(e->getResultExpr());
3369 }
3370
John McCalle4fe2452011-10-01 01:01:08 +00003371 /// Statement expressions are okay if their result expression is okay.
3372 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003373 return Visit(e->getSubStmt()->body_back());
3374 }
John McCall31168b02011-06-15 23:02:42 +00003375
John McCalle4fe2452011-10-01 01:01:08 +00003376 /// Some declaration references are okay.
3377 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
John McCalle4fe2452011-10-01 01:01:08 +00003378 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
Ben Langmuir443aa4b2015-02-25 20:09:06 +00003379 // References to global constants are okay.
John McCalle4fe2452011-10-01 01:01:08 +00003380 if (isAnyRetainable(TargetClass) &&
3381 isAnyRetainable(SourceClass) &&
3382 var &&
Akira Hatanakaad515392017-04-11 22:01:33 +00003383 !var->hasDefinition(Context) &&
Ben Langmuir443aa4b2015-02-25 20:09:06 +00003384 var->getType().isConstQualified()) {
3385
3386 // In system headers, they can also be assumed to be immune to retains.
3387 // These are things like 'kCFStringTransformToLatin'.
3388 if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
3389 return ACC_bottom;
3390
3391 return ACC_plusZero;
John McCalle4fe2452011-10-01 01:01:08 +00003392 }
3393
3394 // Nothing else.
3395 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00003396 }
John McCalle4fe2452011-10-01 01:01:08 +00003397
3398 /// Some calls are okay.
3399 ACCResult VisitCallExpr(CallExpr *e) {
3400 if (FunctionDecl *fn = e->getDirectCallee())
3401 if (ACCResult result = checkCallToFunction(fn))
3402 return result;
3403
3404 return super::VisitCallExpr(e);
3405 }
3406
3407 ACCResult checkCallToFunction(FunctionDecl *fn) {
3408 // Require a CF*Ref return type.
Alp Toker314cc812014-01-25 16:55:45 +00003409 if (!isCFType(fn->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003410 return ACC_invalid;
3411
3412 if (!isAnyRetainable(TargetClass))
3413 return ACC_invalid;
3414
3415 // Honor an explicit 'not retained' attribute.
3416 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3417 return ACC_plusZero;
3418
3419 // Honor an explicit 'retained' attribute, except that for
3420 // now we're not going to permit implicit handling of +1 results,
3421 // because it's a bit frightening.
3422 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003423 return Diagnose ? ACC_plusOne
3424 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003425
3426 // Recognize this specific builtin function, which is used by CFSTR.
3427 unsigned builtinID = fn->getBuiltinID();
3428 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3429 return ACC_bottom;
3430
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003431 // Otherwise, don't do anything implicit with an unaudited function.
3432 if (!fn->hasAttr<CFAuditedTransferAttr>())
3433 return ACC_invalid;
Fangrui Song6907ce22018-07-30 19:24:48 +00003434
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003435 // Otherwise, it's +0 unless it follows the create convention.
3436 if (ento::coreFoundation::followsCreateRule(fn))
Fangrui Song6907ce22018-07-30 19:24:48 +00003437 return Diagnose ? ACC_plusOne
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003438 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003439
John McCalle4fe2452011-10-01 01:01:08 +00003440 return ACC_plusZero;
3441 }
3442
3443 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3444 return checkCallToMethod(e->getMethodDecl());
3445 }
3446
3447 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3448 ObjCMethodDecl *method;
3449 if (e->isExplicitProperty())
3450 method = e->getExplicitProperty()->getGetterMethodDecl();
3451 else
3452 method = e->getImplicitPropertyGetter();
3453 return checkCallToMethod(method);
3454 }
3455
3456 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3457 if (!method) return ACC_invalid;
3458
3459 // Check for message sends to functions returning CF types. We
3460 // just obey the Cocoa conventions with these, even though the
3461 // return type is CF.
Alp Toker314cc812014-01-25 16:55:45 +00003462 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003463 return ACC_invalid;
Fangrui Song6907ce22018-07-30 19:24:48 +00003464
John McCalle4fe2452011-10-01 01:01:08 +00003465 // If the method is explicitly marked not-retained, it's +0.
3466 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3467 return ACC_plusZero;
3468
3469 // If the method is explicitly marked as returning retained, or its
3470 // selector follows a +1 Cocoa convention, treat it as +1.
3471 if (method->hasAttr<CFReturnsRetainedAttr>())
3472 return ACC_plusOne;
3473
3474 switch (method->getSelector().getMethodFamily()) {
3475 case OMF_alloc:
3476 case OMF_copy:
3477 case OMF_mutableCopy:
3478 case OMF_new:
3479 return ACC_plusOne;
3480
3481 default:
3482 // Otherwise, treat it as +0.
3483 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00003484 }
3485 }
John McCalle4fe2452011-10-01 01:01:08 +00003486 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003487} // end anonymous namespace
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00003488
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003489bool Sema::isKnownName(StringRef name) {
3490 if (name.empty())
3491 return false;
3492 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003493 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003494 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003495}
3496
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003497static void addFixitForObjCARCConversion(Sema &S,
3498 DiagnosticBuilder &DiagB,
3499 Sema::CheckedConversionKind CCK,
3500 SourceLocation afterLParen,
3501 QualType castType,
3502 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003503 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003504 const char *bridgeKeyword,
3505 const char *CFBridgeName) {
3506 // We handle C-style and implicit casts here.
3507 switch (CCK) {
3508 case Sema::CCK_ImplicitConversion:
Richard Smith1ef75542018-06-27 20:30:34 +00003509 case Sema::CCK_ForBuiltinOverloadedOp:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003510 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003511 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003512 break;
3513 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003514 return;
3515 }
3516
3517 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003518 if (CCK == Sema::CCK_OtherCast) {
3519 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3520 SourceRange range(NCE->getOperatorLoc(),
3521 NCE->getAngleBrackets().getEnd());
3522 SmallString<32> BridgeCall;
Fangrui Song6907ce22018-07-30 19:24:48 +00003523
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003524 SourceManager &SM = S.getSourceManager();
3525 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3526 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3527 BridgeCall += ' ';
Fangrui Song6907ce22018-07-30 19:24:48 +00003528
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003529 BridgeCall += CFBridgeName;
3530 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3531 }
3532 return;
3533 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003534 Expr *castedE = castExpr;
3535 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3536 castedE = CCE->getSubExpr();
3537 castedE = castedE->IgnoreImpCasts();
3538 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00003539
3540 SmallString<32> BridgeCall;
3541
3542 SourceManager &SM = S.getSourceManager();
3543 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3544 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3545 BridgeCall += ' ';
3546
3547 BridgeCall += CFBridgeName;
3548
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003549 if (isa<ParenExpr>(castedE)) {
3550 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003551 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003552 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00003553 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003554 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003555 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003556 DiagB.AddFixItHint(FixItHint::CreateInsertion(
Craig Topper07fa1762015-11-15 02:31:46 +00003557 S.getLocForEndOfToken(range.getEnd()),
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003558 ")"));
3559 }
3560 return;
3561 }
3562
3563 if (CCK == Sema::CCK_CStyleCast) {
3564 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003565 } else if (CCK == Sema::CCK_OtherCast) {
3566 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3567 std::string castCode = "(";
3568 castCode += bridgeKeyword;
3569 castCode += castType.getAsString();
3570 castCode += ")";
3571 SourceRange Range(NCE->getOperatorLoc(),
3572 NCE->getAngleBrackets().getEnd());
3573 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3574 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003575 } else {
3576 std::string castCode = "(";
3577 castCode += bridgeKeyword;
3578 castCode += castType.getAsString();
3579 castCode += ")";
3580 Expr *castedE = castExpr->IgnoreImpCasts();
3581 SourceRange range = castedE->getSourceRange();
3582 if (isa<ParenExpr>(castedE)) {
3583 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3584 castCode));
3585 } else {
3586 castCode += "(";
3587 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3588 castCode));
3589 DiagB.AddFixItHint(FixItHint::CreateInsertion(
Craig Topper07fa1762015-11-15 02:31:46 +00003590 S.getLocForEndOfToken(range.getEnd()),
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003591 ")"));
3592 }
3593 }
3594}
3595
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003596template <typename T>
3597static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3598 TypedefNameDecl *TDNDecl = TD->getDecl();
3599 QualType QT = TDNDecl->getUnderlyingType();
3600 if (QT->isPointerType()) {
3601 QT = QT->getPointeeType();
3602 if (const RecordType *RT = QT->getAs<RecordType>())
Fariborz Jahanian9af6a782014-06-11 19:10:46 +00003603 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
Aaron Ballman2084f8f2013-12-19 13:20:36 +00003604 return RD->getAttr<T>();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003605 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003606 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003607}
3608
3609static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3610 TypedefNameDecl *&TDNDecl) {
3611 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3612 TDNDecl = TD->getDecl();
3613 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3614 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3615 return ObjCBAttr;
3616 T = TDNDecl->getUnderlyingType();
3617 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003618 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003619}
3620
John McCall4124c492011-10-17 18:40:02 +00003621static void
3622diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3623 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003624 Expr *castExpr, Expr *realCast,
3625 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003626 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003627 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003628 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00003629
John McCall4124c492011-10-17 18:40:02 +00003630 if (S.makeUnavailableInSystemHeader(loc,
John McCallc6af8c62015-10-28 05:03:19 +00003631 UnavailableAttr::IR_ARCForbiddenConversion))
John McCall31168b02011-06-15 23:02:42 +00003632 return;
John McCall4124c492011-10-17 18:40:02 +00003633
3634 QualType castExprType = castExpr->getType();
Bob Wilsonf5c53b82016-02-13 01:41:41 +00003635 // Defer emitting a diagnostic for bridge-related casts; that will be
3636 // handled by CheckObjCBridgeRelatedConversions.
Craig Topperc3ec1492014-05-26 06:22:03 +00003637 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003638 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3639 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3640 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
Fariborz Jahanian1ad83a32014-06-18 23:22:38 +00003641 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003642 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00003643
John McCall640767f2011-06-17 06:50:50 +00003644 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003645 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003646 case ACTC_none:
3647 case ACTC_coreFoundation:
3648 case ACTC_voidPtr:
3649 srcKind = (castExprType->isPointerType() ? 1 : 0);
3650 break;
3651 case ACTC_retainable:
3652 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3653 break;
3654 case ACTC_indirectRetainable:
3655 srcKind = 4;
3656 break;
John McCall31168b02011-06-15 23:02:42 +00003657 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003658
John McCall4124c492011-10-17 18:40:02 +00003659 // Check whether this could be fixed with a bridge cast.
Craig Topper07fa1762015-11-15 02:31:46 +00003660 SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin());
John McCall4124c492011-10-17 18:40:02 +00003661 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003662
Richard Smith1ef75542018-06-27 20:30:34 +00003663 unsigned convKindForDiag = Sema::isCast(CCK) ? 0 : 1;
3664
John McCall4124c492011-10-17 18:40:02 +00003665 // Bridge from an ARC type to a CF type.
3666 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003667
John McCall4124c492011-10-17 18:40:02 +00003668 S.Diag(loc, diag::err_arc_cast_requires_bridge)
Richard Smith1ef75542018-06-27 20:30:34 +00003669 << convKindForDiag
John McCall4124c492011-10-17 18:40:02 +00003670 << 2 // of C pointer type
3671 << castExprType
3672 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3673 << castType
3674 << castRange
3675 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003676 bool br = S.isKnownName("CFBridgingRelease");
Fangrui Song6907ce22018-07-30 19:24:48 +00003677 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003678 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003679 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003680 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003681 {
Fangrui Song6907ce22018-07-30 19:24:48 +00003682 DiagnosticBuilder DiagB =
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003683 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3684 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Craig Topperc3ec1492014-05-26 06:22:03 +00003685
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003686 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003687 castType, castExpr, realCast, "__bridge ",
3688 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003689 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003690 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003691 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003692 DiagnosticBuilder DiagB =
3693 (CCK == Sema::CCK_OtherCast && !br) ?
3694 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3695 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3696 diag::note_arc_bridge_transfer)
3697 << castExprType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003698
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003699 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003700 castType, castExpr, realCast, "__bridge_transfer ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003701 br ? "CFBridgingRelease" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003702 }
John McCall4124c492011-10-17 18:40:02 +00003703
3704 return;
3705 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003706
John McCall4124c492011-10-17 18:40:02 +00003707 // Bridge from a CF type to an ARC type.
3708 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003709 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003710 S.Diag(loc, diag::err_arc_cast_requires_bridge)
Richard Smith1ef75542018-06-27 20:30:34 +00003711 << convKindForDiag
John McCall4124c492011-10-17 18:40:02 +00003712 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3713 << castExprType
3714 << 2 // to C pointer type
3715 << castType
3716 << castRange
3717 << castExpr->getSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +00003718 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003719 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003720 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003721 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003722 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003723 DiagnosticBuilder DiagB =
3724 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3725 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003726 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003727 castType, castExpr, realCast, "__bridge ",
3728 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003729 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003730 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003731 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003732 DiagnosticBuilder DiagB =
3733 (CCK == Sema::CCK_OtherCast && !br) ?
3734 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3735 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3736 diag::note_arc_bridge_retained)
3737 << castType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003738
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003739 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003740 castType, castExpr, realCast, "__bridge_retained ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003741 br ? "CFBridgingRetain" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003742 }
John McCall4124c492011-10-17 18:40:02 +00003743
3744 return;
John McCall31168b02011-06-15 23:02:42 +00003745 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003746
John McCall4124c492011-10-17 18:40:02 +00003747 S.Diag(loc, diag::err_arc_mismatched_cast)
Richard Smith1ef75542018-06-27 20:30:34 +00003748 << !convKindForDiag
John McCall4124c492011-10-17 18:40:02 +00003749 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003750 << castRange << castExpr->getSourceRange();
3751}
3752
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003753template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003754static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3755 bool &HadTheAttribute, bool warn) {
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003756 QualType T = castExpr->getType();
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003757 HadTheAttribute = false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003758 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3759 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003760 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003761 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003762 HadTheAttribute = true;
Fariborz Jahanianc9e266b2014-12-11 22:56:26 +00003763 if (Parm->isStr("id"))
3764 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00003765
Craig Topperc3ec1492014-05-26 06:22:03 +00003766 NamedDecl *Target = nullptr;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003767 // Check for an existing type with this name.
3768 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3769 Sema::LookupOrdinaryName);
3770 if (S.LookupName(R, S.TUScope)) {
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003771 Target = R.getFoundDecl();
3772 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3773 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3774 if (const ObjCObjectPointerType *InterfacePointerType =
3775 castType->getAsObjCInterfacePointerType()) {
3776 ObjCInterfaceDecl *CastClass
3777 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003778 if ((CastClass == ExprClass) ||
Fariborz Jahanian27aa9b42015-04-10 22:07:47 +00003779 (CastClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003780 return true;
3781 if (warn)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003782 S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
3783 << T << Target->getName() << castType->getPointeeType();
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003784 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003785 } else if (castType->isObjCIdType() ||
3786 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3787 castType, ExprClass)))
3788 // ok to cast to 'id'.
3789 // casting to id<p-list> is ok if bridge type adopts all of
3790 // p-list protocols.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003791 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003792 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003793 if (warn) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003794 S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
3795 << T << Target->getName() << castType;
3796 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
3797 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003798 }
3799 return false;
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003800 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003801 }
Fariborz Jahanian696c8872015-04-09 23:39:53 +00003802 } else if (!castType->isObjCIdType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003803 S.Diag(castExpr->getBeginLoc(),
3804 diag::err_objc_cf_bridged_not_interface)
3805 << castExpr->getType() << Parm;
3806 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
Fariborz Jahanian696c8872015-04-09 23:39:53 +00003807 if (Target)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003808 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003809 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003810 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003811 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003812 return false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003813 }
3814 T = TDNDecl->getUnderlyingType();
3815 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003816 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003817}
3818
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003819template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003820static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3821 bool &HadTheAttribute, bool warn) {
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003822 QualType T = castType;
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003823 HadTheAttribute = false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003824 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3825 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003826 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003827 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003828 HadTheAttribute = true;
John McCallaf6b3f82015-03-10 18:41:23 +00003829 if (Parm->isStr("id"))
3830 return true;
3831
Craig Topperc3ec1492014-05-26 06:22:03 +00003832 NamedDecl *Target = nullptr;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003833 // Check for an existing type with this name.
3834 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3835 Sema::LookupOrdinaryName);
3836 if (S.LookupName(R, S.TUScope)) {
3837 Target = R.getFoundDecl();
3838 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3839 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3840 if (const ObjCObjectPointerType *InterfacePointerType =
3841 castExpr->getType()->getAsObjCInterfacePointerType()) {
3842 ObjCInterfaceDecl *ExprClass
3843 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003844 if ((CastClass == ExprClass) ||
3845 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003846 return true;
3847 if (warn) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003848 S.Diag(castExpr->getBeginLoc(),
3849 diag::warn_objc_invalid_bridge_to_cf)
3850 << castExpr->getType()->getPointeeType() << T;
3851 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003852 }
3853 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003854 } else if (castExpr->getType()->isObjCIdType() ||
3855 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3856 castExpr->getType(), CastClass)))
3857 // ok to cast an 'id' expression to a CFtype.
3858 // ok to cast an 'id<plist>' expression to CFtype provided plist
3859 // adopts all of CFtype's ObjetiveC's class plist.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003860 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003861 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003862 if (warn) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003863 S.Diag(castExpr->getBeginLoc(),
3864 diag::warn_objc_invalid_bridge_to_cf)
3865 << castExpr->getType() << castType;
3866 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
3867 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003868 }
3869 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003870 }
3871 }
3872 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003873 S.Diag(castExpr->getBeginLoc(),
3874 diag::err_objc_ns_bridged_invalid_cfobject)
3875 << castExpr->getType() << castType;
3876 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003877 if (Target)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003878 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003879 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003880 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003881 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003882 }
3883 T = TDNDecl->getUnderlyingType();
3884 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003885 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003886}
3887
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003888void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003889 if (!getLangOpts().ObjC1)
3890 return;
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003891 // warn in presence of __bridge casting to or from a toll free bridge cast.
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003892 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3893 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003894 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003895 bool HasObjCBridgeAttr;
3896 bool ObjCBridgeAttrWillNotWarn =
3897 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3898 false);
3899 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3900 return;
3901 bool HasObjCBridgeMutableAttr;
3902 bool ObjCBridgeMutableAttrWillNotWarn =
3903 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3904 HasObjCBridgeMutableAttr, false);
3905 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3906 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00003907
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003908 if (HasObjCBridgeAttr)
3909 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3910 true);
3911 else if (HasObjCBridgeMutableAttr)
3912 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3913 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003914 }
3915 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003916 bool HasObjCBridgeAttr;
3917 bool ObjCBridgeAttrWillNotWarn =
3918 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3919 false);
3920 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3921 return;
3922 bool HasObjCBridgeMutableAttr;
3923 bool ObjCBridgeMutableAttrWillNotWarn =
3924 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3925 HasObjCBridgeMutableAttr, false);
3926 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3927 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00003928
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003929 if (HasObjCBridgeAttr)
3930 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3931 true);
3932 else if (HasObjCBridgeMutableAttr)
3933 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3934 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003935 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003936}
3937
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003938void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3939 QualType SrcType = castExpr->getType();
3940 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3941 if (PRE->isExplicitProperty()) {
3942 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3943 SrcType = PDecl->getType();
3944 }
3945 else if (PRE->isImplicitProperty()) {
3946 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3947 SrcType = Getter->getReturnType();
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003948 }
3949 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003950
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003951 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3952 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3953 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3954 return;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003955 CheckObjCBridgeRelatedConversions(castExpr->getBeginLoc(), castType, SrcType,
3956 castExpr);
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003957}
3958
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00003959bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3960 CastKind &Kind) {
3961 if (!getLangOpts().ObjC1)
3962 return false;
3963 ARCConversionTypeClass exprACTC =
3964 classifyTypeForARCConversion(castExpr->getType());
3965 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3966 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3967 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3968 CheckTollFreeBridgeCast(castType, castExpr);
3969 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3970 : CK_CPointerToObjCPointerCast;
3971 return true;
3972 }
3973 return false;
3974}
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003975
3976bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3977 QualType DestType, QualType SrcType,
3978 ObjCInterfaceDecl *&RelatedClass,
3979 ObjCMethodDecl *&ClassMethod,
3980 ObjCMethodDecl *&InstanceMethod,
3981 TypedefNameDecl *&TDNDecl,
George Burgess IV60bc9722016-01-13 23:36:34 +00003982 bool CfToNs, bool Diagnose) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003983 QualType T = CfToNs ? SrcType : DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003984 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3985 if (!ObjCBAttr)
3986 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003987
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003988 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3989 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3990 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3991 if (!RCId)
3992 return false;
Craig Topperc3ec1492014-05-26 06:22:03 +00003993 NamedDecl *Target = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003994 // Check for an existing type with this name.
3995 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3996 Sema::LookupOrdinaryName);
3997 if (!LookupName(R, TUScope)) {
George Burgess IV60bc9722016-01-13 23:36:34 +00003998 if (Diagnose) {
3999 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
4000 << SrcType << DestType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004001 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
George Burgess IV60bc9722016-01-13 23:36:34 +00004002 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004003 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004004 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004005 Target = R.getFoundDecl();
4006 if (Target && isa<ObjCInterfaceDecl>(Target))
4007 RelatedClass = cast<ObjCInterfaceDecl>(Target);
4008 else {
George Burgess IV60bc9722016-01-13 23:36:34 +00004009 if (Diagnose) {
4010 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
4011 << SrcType << DestType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004012 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
George Burgess IV60bc9722016-01-13 23:36:34 +00004013 if (Target)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004014 Diag(Target->getBeginLoc(), diag::note_declared_at);
George Burgess IV60bc9722016-01-13 23:36:34 +00004015 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004016 return false;
4017 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004018
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004019 // Check for an existing class method with the given selector name.
4020 if (CfToNs && CMId) {
4021 Selector Sel = Context.Selectors.getUnarySelector(CMId);
4022 ClassMethod = RelatedClass->lookupMethod(Sel, false);
4023 if (!ClassMethod) {
George Burgess IV60bc9722016-01-13 23:36:34 +00004024 if (Diagnose) {
4025 Diag(Loc, diag::err_objc_bridged_related_known_method)
4026 << SrcType << DestType << Sel << false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004027 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
George Burgess IV60bc9722016-01-13 23:36:34 +00004028 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004029 return false;
4030 }
4031 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004032
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004033 // Check for an existing instance method with the given selector name.
4034 if (!CfToNs && IMId) {
4035 Selector Sel = Context.Selectors.getNullarySelector(IMId);
4036 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
4037 if (!InstanceMethod) {
George Burgess IV60bc9722016-01-13 23:36:34 +00004038 if (Diagnose) {
4039 Diag(Loc, diag::err_objc_bridged_related_known_method)
4040 << SrcType << DestType << Sel << true;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004041 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
George Burgess IV60bc9722016-01-13 23:36:34 +00004042 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004043 return false;
4044 }
4045 }
4046 return true;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004047}
4048
4049bool
4050Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
Fariborz Jahaniandb765772013-12-10 17:08:13 +00004051 QualType DestType, QualType SrcType,
George Burgess IV60bc9722016-01-13 23:36:34 +00004052 Expr *&SrcExpr, bool Diagnose) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004053 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
4054 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
4055 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
4056 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
4057 if (!CfToNs && !NsToCf)
4058 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004059
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004060 ObjCInterfaceDecl *RelatedClass;
Craig Topperc3ec1492014-05-26 06:22:03 +00004061 ObjCMethodDecl *ClassMethod = nullptr;
4062 ObjCMethodDecl *InstanceMethod = nullptr;
4063 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004064 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
George Burgess IV60bc9722016-01-13 23:36:34 +00004065 ClassMethod, InstanceMethod, TDNDecl,
4066 CfToNs, Diagnose))
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004067 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004068
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004069 if (CfToNs) {
4070 // Implicit conversion from CF to ObjC object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00004071 if (ClassMethod) {
George Burgess IV60bc9722016-01-13 23:36:34 +00004072 if (Diagnose) {
4073 std::string ExpressionString = "[";
4074 ExpressionString += RelatedClass->getNameAsString();
4075 ExpressionString += " ";
4076 ExpressionString += ClassMethod->getSelector().getAsString();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004077 SourceLocation SrcExprEndLoc =
4078 getLocForEndOfToken(SrcExpr->getEndLoc());
George Burgess IV60bc9722016-01-13 23:36:34 +00004079 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
4080 Diag(Loc, diag::err_objc_bridged_related_known_method)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004081 << SrcType << DestType << ClassMethod->getSelector() << false
4082 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(),
4083 ExpressionString)
4084 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
4085 Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
4086 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
Fangrui Song6907ce22018-07-30 19:24:48 +00004087
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004088 QualType receiverType = Context.getObjCInterfaceType(RelatedClass);
4089 // Argument.
4090 Expr *args[] = { SrcExpr };
4091 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
Fariborz Jahanian381edf52013-12-16 22:54:37 +00004092 ClassMethod->getLocation(),
4093 ClassMethod->getSelector(), ClassMethod,
4094 MultiExprArg(args, 1));
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004095 SrcExpr = msg.get();
4096 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00004097 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00004098 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004099 }
4100 else {
4101 // Implicit conversion from ObjC type to CF object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00004102 if (InstanceMethod) {
George Burgess IV60bc9722016-01-13 23:36:34 +00004103 if (Diagnose) {
4104 std::string ExpressionString;
4105 SourceLocation SrcExprEndLoc =
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004106 getLocForEndOfToken(SrcExpr->getEndLoc());
George Burgess IV60bc9722016-01-13 23:36:34 +00004107 if (InstanceMethod->isPropertyAccessor())
4108 if (const ObjCPropertyDecl *PDecl =
4109 InstanceMethod->findPropertyDecl()) {
4110 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
4111 ExpressionString = ".";
4112 ExpressionString += PDecl->getNameAsString();
4113 Diag(Loc, diag::err_objc_bridged_related_known_method)
4114 << SrcType << DestType << InstanceMethod->getSelector() << true
4115 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4116 }
4117 if (ExpressionString.empty()) {
4118 // Provide a fixit: [ObjectExpr InstanceMethod]
4119 ExpressionString = " ";
4120 ExpressionString += InstanceMethod->getSelector().getAsString();
4121 ExpressionString += "]";
4122
Fariborz Jahanian88b68982013-12-10 23:18:06 +00004123 Diag(Loc, diag::err_objc_bridged_related_known_method)
George Burgess IV60bc9722016-01-13 23:36:34 +00004124 << SrcType << DestType << InstanceMethod->getSelector() << true
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004125 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "[")
George Burgess IV60bc9722016-01-13 23:36:34 +00004126 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
Fariborz Jahanian88b68982013-12-10 23:18:06 +00004127 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004128 Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
4129 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
Fangrui Song6907ce22018-07-30 19:24:48 +00004130
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004131 ExprResult msg =
4132 BuildInstanceMessageImplicit(SrcExpr, SrcType,
4133 InstanceMethod->getLocation(),
4134 InstanceMethod->getSelector(),
4135 InstanceMethod, None);
4136 SrcExpr = msg.get();
4137 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00004138 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00004139 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004140 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00004141 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004142}
4143
John McCall4124c492011-10-17 18:40:02 +00004144Sema::ARCConversionResult
Brian Kelley11352a82017-03-29 18:09:02 +00004145Sema::CheckObjCConversion(SourceRange castRange, QualType castType,
4146 Expr *&castExpr, CheckedConversionKind CCK,
4147 bool Diagnose, bool DiagnoseCFAudited,
4148 BinaryOperatorKind Opc) {
John McCall4124c492011-10-17 18:40:02 +00004149 QualType castExprType = castExpr->getType();
4150
4151 // For the purposes of the classification, we assume reference types
4152 // will bind to temporaries.
4153 QualType effCastType = castType;
4154 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
4155 effCastType = ref->getPointeeType();
Fangrui Song6907ce22018-07-30 19:24:48 +00004156
John McCall4124c492011-10-17 18:40:02 +00004157 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
4158 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004159 if (exprACTC == castACTC) {
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004160 // Check for viability and report error if casting an rvalue to a
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004161 // life-time qualifier.
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004162 if (castACTC == ACTC_retainable &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004163 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
George Burgess IV60bc9722016-01-13 23:36:34 +00004164 castType != castExprType) {
Fariborz Jahanian244b1872011-10-29 00:06:10 +00004165 const Type *DT = castType.getTypePtr();
4166 QualType QDT = castType;
4167 // We desugar some types but not others. We ignore those
4168 // that cannot happen in a cast; i.e. auto, and those which
4169 // should not be de-sugared; i.e typedef.
4170 if (const ParenType *PT = dyn_cast<ParenType>(DT))
4171 QDT = PT->desugar();
4172 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
4173 QDT = TP->desugar();
4174 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
4175 QDT = AT->desugar();
4176 if (QDT != castType &&
4177 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004178 if (Diagnose) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004179 SourceLocation loc = (castRange.isValid() ? castRange.getBegin()
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004180 : castExpr->getExprLoc());
4181 Diag(loc, diag::err_arc_nolifetime_behavior);
4182 }
4183 return ACR_error;
Fariborz Jahanian244b1872011-10-29 00:06:10 +00004184 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004185 }
4186 return ACR_okay;
4187 }
Brian Kelley11352a82017-03-29 18:09:02 +00004188
4189 // The life-time qualifier cast check above is all we need for ObjCWeak.
4190 // ObjCAutoRefCount has more restrictions on what is legal.
4191 if (!getLangOpts().ObjCAutoRefCount)
4192 return ACR_okay;
4193
John McCall4124c492011-10-17 18:40:02 +00004194 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
4195
4196 // Allow all of these types to be cast to integer types (but not
4197 // vice-versa).
4198 if (castACTC == ACTC_none && castType->isIntegralType(Context))
4199 return ACR_okay;
Fangrui Song6907ce22018-07-30 19:24:48 +00004200
John McCall4124c492011-10-17 18:40:02 +00004201 // Allow casts between pointers to lifetime types (e.g., __strong id*)
4202 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
4203 // must be explicit.
4204 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
4205 return ACR_okay;
4206 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
Richard Smith1ef75542018-06-27 20:30:34 +00004207 isCast(CCK))
John McCall4124c492011-10-17 18:40:02 +00004208 return ACR_okay;
4209
Fariborz Jahanian36986c62012-07-27 22:37:07 +00004210 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00004211 // For invalid casts, fall through.
4212 case ACC_invalid:
4213 break;
4214
4215 // Do nothing for both bottom and +0.
4216 case ACC_bottom:
4217 case ACC_plusZero:
4218 return ACR_okay;
4219
4220 // If the result is +1, consume it here.
4221 case ACC_plusOne:
4222 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
4223 CK_ARCConsumeObject, castExpr,
Craig Topperc3ec1492014-05-26 06:22:03 +00004224 nullptr, VK_RValue);
Tim Shen4a05bb82016-06-21 20:29:17 +00004225 Cleanup.setExprNeedsCleanups(true);
John McCall4124c492011-10-17 18:40:02 +00004226 return ACR_okay;
4227 }
4228
4229 // If this is a non-implicit cast from id or block type to a
4230 // CoreFoundation type, delay complaining in case the cast is used
4231 // in an acceptable context.
Richard Smith1ef75542018-06-27 20:30:34 +00004232 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) && isCast(CCK))
John McCall4124c492011-10-17 18:40:02 +00004233 return ACR_unbridged;
4234
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004235 // Issue a diagnostic about a missing @-sign when implicit casting a cstring
4236 // to 'NSString *', instead of falling through to report a "bridge cast"
4237 // diagnostic.
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004238 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
George Burgess IV60bc9722016-01-13 23:36:34 +00004239 ConversionToObjCStringLiteralCheck(castType, castExpr, Diagnose))
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004240 return ACR_error;
Fangrui Song6907ce22018-07-30 19:24:48 +00004241
Fariborz Jahanian25eef192013-07-31 21:40:51 +00004242 // Do not issue "bridge cast" diagnostic when implicit casting
4243 // a retainable object to a CF type parameter belonging to an audited
4244 // CF API function. Let caller issue a normal type mismatched diagnostic
4245 // instead.
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004246 if ((!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
4247 castACTC != ACTC_coreFoundation) &&
4248 !(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
4249 (Opc == BO_NE || Opc == BO_EQ))) {
4250 if (Diagnose)
George Burgess IV60bc9722016-01-13 23:36:34 +00004251 diagnoseObjCARCConversion(*this, castRange, castType, castACTC, castExpr,
4252 castExpr, exprACTC, CCK);
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004253 return ACR_error;
4254 }
John McCall4124c492011-10-17 18:40:02 +00004255 return ACR_okay;
4256}
4257
4258/// Given that we saw an expression with the ARCUnbridgedCastTy
4259/// placeholder type, complain bitterly.
4260void Sema::diagnoseARCUnbridgedCast(Expr *e) {
4261 // We expect the spurious ImplicitCastExpr to already have been stripped.
4262 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4263 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
4264
4265 SourceRange castRange;
4266 QualType castType;
4267 CheckedConversionKind CCK;
4268
4269 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
4270 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
4271 castType = cast->getTypeAsWritten();
4272 CCK = CCK_CStyleCast;
4273 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
4274 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
4275 castType = cast->getTypeAsWritten();
4276 CCK = CCK_OtherCast;
4277 } else {
Akira Hatanaka2cd7e862017-05-09 01:54:51 +00004278 llvm_unreachable("Unexpected ImplicitCastExpr");
John McCall4124c492011-10-17 18:40:02 +00004279 }
4280
4281 ARCConversionTypeClass castACTC =
4282 classifyTypeForARCConversion(castType.getNonReferenceType());
4283
4284 Expr *castExpr = realCast->getSubExpr();
4285 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
4286
4287 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00004288 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00004289}
4290
4291/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
4292/// type, remove the placeholder cast.
4293Expr *Sema::stripARCUnbridgedCast(Expr *e) {
4294 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4295
4296 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
4297 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
4298 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
4299 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
4300 assert(uo->getOpcode() == UO_Extension);
4301 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
Aaron Ballmana5038552018-01-09 13:07:03 +00004302 return new (Context)
4303 UnaryOperator(sub, UO_Extension, sub->getType(), sub->getValueKind(),
4304 sub->getObjectKind(), uo->getOperatorLoc(), false);
John McCall4124c492011-10-17 18:40:02 +00004305 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
4306 assert(!gse->isResultDependent());
4307
4308 unsigned n = gse->getNumAssocs();
4309 SmallVector<Expr*, 4> subExprs(n);
4310 SmallVector<TypeSourceInfo*, 4> subTypes(n);
4311 for (unsigned i = 0; i != n; ++i) {
4312 subTypes[i] = gse->getAssocTypeSourceInfo(i);
4313 Expr *sub = gse->getAssocExpr(i);
4314 if (i == gse->getResultIndex())
4315 sub = stripARCUnbridgedCast(sub);
4316 subExprs[i] = sub;
4317 }
4318
4319 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
4320 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00004321 subTypes, subExprs,
4322 gse->getDefaultLoc(),
John McCall4124c492011-10-17 18:40:02 +00004323 gse->getRParenLoc(),
4324 gse->containsUnexpandedParameterPack(),
4325 gse->getResultIndex());
4326 } else {
4327 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
4328 return cast<ImplicitCastExpr>(e)->getSubExpr();
4329 }
4330}
4331
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004332bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
4333 QualType exprType) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004334 QualType canCastType =
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004335 Context.getCanonicalType(castType).getUnqualifiedType();
Fangrui Song6907ce22018-07-30 19:24:48 +00004336 QualType canExprType =
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004337 Context.getCanonicalType(exprType).getUnqualifiedType();
4338 if (isa<ObjCObjectPointerType>(canCastType) &&
4339 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
4340 canExprType->isObjCObjectPointerType()) {
4341 if (const ObjCObjectPointerType *ObjT =
4342 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00004343 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4344 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004345 }
4346 return true;
4347}
4348
John McCall4db5c3c2011-07-07 06:58:02 +00004349/// Look for an ObjCReclaimReturnedObject cast and destroy it.
4350static Expr *maybeUndoReclaimObject(Expr *e) {
Akira Hatanakacc7171a2017-10-10 01:24:33 +00004351 Expr *curExpr = e, *prevExpr = nullptr;
4352
4353 // Walk down the expression until we hit an implicit cast of kind
4354 // ARCReclaimReturnedObject or an Expr that is neither a Paren nor a Cast.
4355 while (true) {
4356 if (auto *pe = dyn_cast<ParenExpr>(curExpr)) {
4357 prevExpr = curExpr;
4358 curExpr = pe->getSubExpr();
4359 continue;
4360 }
4361
4362 if (auto *ce = dyn_cast<CastExpr>(curExpr)) {
4363 if (auto *ice = dyn_cast<ImplicitCastExpr>(ce))
4364 if (ice->getCastKind() == CK_ARCReclaimReturnedObject) {
4365 if (!prevExpr)
4366 return ice->getSubExpr();
4367 if (auto *pe = dyn_cast<ParenExpr>(prevExpr))
4368 pe->setSubExpr(ice->getSubExpr());
4369 else
4370 cast<CastExpr>(prevExpr)->setSubExpr(ice->getSubExpr());
4371 return e;
4372 }
4373
4374 prevExpr = curExpr;
4375 curExpr = ce->getSubExpr();
4376 continue;
4377 }
4378
4379 // Break out of the loop if curExpr is neither a Paren nor a Cast.
4380 break;
4381 }
John McCall4db5c3c2011-07-07 06:58:02 +00004382
4383 return e;
4384}
4385
John McCall31168b02011-06-15 23:02:42 +00004386ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
4387 ObjCBridgeCastKind Kind,
4388 SourceLocation BridgeKeywordLoc,
4389 TypeSourceInfo *TSInfo,
4390 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00004391 ExprResult SubResult = UsualUnaryConversions(SubExpr);
4392 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004393 SubExpr = SubResult.get();
John McCalleb075542011-08-26 00:48:42 +00004394
John McCall31168b02011-06-15 23:02:42 +00004395 QualType T = TSInfo->getType();
4396 QualType FromType = SubExpr->getType();
4397
John McCall9320b872011-09-09 05:25:32 +00004398 CastKind CK;
4399
John McCall31168b02011-06-15 23:02:42 +00004400 bool MustConsume = false;
4401 if (T->isDependentType() || SubExpr->isTypeDependent()) {
4402 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00004403 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00004404 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
4405 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00004406 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4407 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00004408 switch (Kind) {
4409 case OBC_Bridge:
4410 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004411
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004412 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004413 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00004414 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4415 << 2
4416 << FromType
4417 << (T->isBlockPointerType()? 1 : 0)
4418 << T
4419 << SubExpr->getSourceRange()
4420 << Kind;
4421 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4422 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4423 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004424 << FromType << br
Fangrui Song6907ce22018-07-30 19:24:48 +00004425 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4426 br ? "CFBridgingRelease "
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004427 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00004428
4429 Kind = OBC_Bridge;
4430 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004431 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004432
John McCall31168b02011-06-15 23:02:42 +00004433 case OBC_BridgeTransfer:
4434 // We must consume the Objective-C object produced by the cast.
4435 MustConsume = true;
4436 break;
4437 }
4438 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4439 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00004440 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00004441 switch (Kind) {
Fariborz Jahanian214567c2014-10-28 17:26:21 +00004442 case OBC_Bridge:
4443 // Reclaiming a value that's going to be __bridge-casted to CF
4444 // is very dangerous, so we don't do it.
4445 SubExpr = maybeUndoReclaimObject(SubExpr);
4446 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004447
4448 case OBC_BridgeRetained:
John McCall31168b02011-06-15 23:02:42 +00004449 // Produce the object before casting it.
4450 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00004451 CK_ARCProduceObject,
Craig Topperc3ec1492014-05-26 06:22:03 +00004452 SubExpr, nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004453 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004454
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004455 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004456 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00004457 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4458 << (FromType->isBlockPointerType()? 1 : 0)
4459 << FromType
4460 << 2
4461 << T
4462 << SubExpr->getSourceRange()
4463 << Kind;
Fangrui Song6907ce22018-07-30 19:24:48 +00004464
John McCall31168b02011-06-15 23:02:42 +00004465 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4466 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4467 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004468 << T << br
Fangrui Song6907ce22018-07-30 19:24:48 +00004469 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004470 br ? "CFBridgingRetain " : "__bridge_retained");
Fangrui Song6907ce22018-07-30 19:24:48 +00004471
John McCall31168b02011-06-15 23:02:42 +00004472 Kind = OBC_Bridge;
4473 break;
4474 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004475 }
John McCall31168b02011-06-15 23:02:42 +00004476 } else {
4477 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4478 << FromType << T << Kind
4479 << SubExpr->getSourceRange()
4480 << TSInfo->getTypeLoc().getSourceRange();
4481 return ExprError();
4482 }
4483
John McCall9320b872011-09-09 05:25:32 +00004484 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00004485 BridgeKeywordLoc,
4486 TSInfo, SubExpr);
Fangrui Song6907ce22018-07-30 19:24:48 +00004487
John McCall31168b02011-06-15 23:02:42 +00004488 if (MustConsume) {
Tim Shen4a05bb82016-06-21 20:29:17 +00004489 Cleanup.setExprNeedsCleanups(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00004490 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
Craig Topperc3ec1492014-05-26 06:22:03 +00004491 nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004492 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004493
John McCall31168b02011-06-15 23:02:42 +00004494 return Result;
4495}
4496
4497ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4498 SourceLocation LParenLoc,
4499 ObjCBridgeCastKind Kind,
4500 SourceLocation BridgeKeywordLoc,
4501 ParsedType Type,
4502 SourceLocation RParenLoc,
4503 Expr *SubExpr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004504 TypeSourceInfo *TSInfo = nullptr;
John McCall31168b02011-06-15 23:02:42 +00004505 QualType T = GetTypeFromParser(Type, &TSInfo);
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00004506 if (Kind == OBC_Bridge)
4507 CheckTollFreeBridgeCast(T, SubExpr);
John McCall31168b02011-06-15 23:02:42 +00004508 if (!TSInfo)
4509 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00004510 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
John McCall31168b02011-06-15 23:02:42 +00004511 SubExpr);
4512}