blob: 4ca3b851c183b7632b5175c7e07d4730ff02eb32 [file] [log] [blame]
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnera3fc41d2008-01-04 22:32:30 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for Objective-C expressions.
10//
11//===----------------------------------------------------------------------===//
12
John McCall83024632010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Chris Lattnera3fc41d2008-01-04 22:32:30 +000014#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclObjC.h"
Steve Naroff021ca182008-05-29 21:12:08 +000016#include "clang/AST/ExprObjC.h"
John McCall31168b02011-06-15 23:02:42 +000017#include "clang/AST/StmtVisitor.h"
Douglas Gregor0c78ad92010-04-21 19:57:20 +000018#include "clang/AST/TypeLoc.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
20#include "clang/Edit/Commit.h"
21#include "clang/Edit/Rewriters.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000022#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Sema/Initialization.h"
24#include "clang/Sema/Lookup.h"
25#include "clang/Sema/Scope.h"
26#include "clang/Sema/ScopeInfo.h"
27#include "llvm/ADT/SmallString.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000028
Chris Lattnera3fc41d2008-01-04 22:32:30 +000029using namespace clang;
John McCall5f2d5562011-02-03 09:00:02 +000030using namespace sema;
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +000031using llvm::makeArrayRef;
Chris Lattnera3fc41d2008-01-04 22:32:30 +000032
John McCallfaf5fb42010-08-26 23:41:50 +000033ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
Craig Topper883dd332015-12-24 23:58:11 +000034 ArrayRef<Expr *> Strings) {
Chris Lattnerd7670d92009-02-18 06:13:04 +000035 // Most ObjC strings are formed out of a single piece. However, we *can*
36 // have strings formed out of multiple @ strings with multiple pptokens in
37 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
38 // StringLiteral for ObjCStringLiteral to hold onto.
Craig Topper883dd332015-12-24 23:58:11 +000039 StringLiteral *S = cast<StringLiteral>(Strings[0]);
Mike Stump11289f42009-09-09 15:08:12 +000040
Chris Lattnerd7670d92009-02-18 06:13:04 +000041 // If we have a multi-part string, merge it all together.
Craig Topper883dd332015-12-24 23:58:11 +000042 if (Strings.size() != 1) {
Chris Lattnera3fc41d2008-01-04 22:32:30 +000043 // Concatenate objc strings.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000044 SmallString<128> StrBuf;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000045 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump11289f42009-09-09 15:08:12 +000046
Craig Topper883dd332015-12-24 23:58:11 +000047 for (Expr *E : Strings) {
48 S = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +000049
Douglas Gregorfb65e592011-07-27 05:40:30 +000050 // ObjC strings can't be wide or UTF.
51 if (!S->isAscii()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000052 Diag(S->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
53 << S->getSourceRange();
Chris Lattnerd7670d92009-02-18 06:13:04 +000054 return true;
55 }
Mike Stump11289f42009-09-09 15:08:12 +000056
Benjamin Kramer35b077e2010-08-17 12:54:38 +000057 // Append the string.
58 StrBuf += S->getString();
Mike Stump11289f42009-09-09 15:08:12 +000059
Chris Lattner163ffd22009-02-18 06:48:40 +000060 // Get the locations of the string tokens.
61 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000062 }
Mike Stump11289f42009-09-09 15:08:12 +000063
Chris Lattner163ffd22009-02-18 06:48:40 +000064 // Create the aggregate string with the appropriate content and location
65 // information.
Benjamin Kramercdac7612014-02-25 12:26:20 +000066 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
67 assert(CAT && "String literal not of constant array type!");
68 QualType StrTy = Context.getConstantArrayType(
69 CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1),
70 CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
71 S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
72 /*Pascal=*/false, StrTy, &StrLocs[0],
73 StrLocs.size());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000074 }
Fangrui Song6907ce22018-07-30 19:24:48 +000075
Ted Kremeneke65b0862012-03-06 20:05:56 +000076 return BuildObjCStringLiteral(AtLocs[0], S);
77}
Mike Stump11289f42009-09-09 15:08:12 +000078
Ted Kremeneke65b0862012-03-06 20:05:56 +000079ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
Chris Lattner6436fb62009-02-18 06:01:06 +000080 // Verify that this composite string is acceptable for ObjC strings.
81 if (CheckObjCString(S))
Chris Lattnera3fc41d2008-01-04 22:32:30 +000082 return true;
Chris Lattnerfffd6a72009-02-18 06:06:56 +000083
84 // Initialize the constant string interface lazily. This assumes
Steve Naroff54e59452009-04-07 14:18:33 +000085 // the NSString interface is seen in this translation unit. Note: We
86 // don't use NSConstantString, since the runtime team considers this
87 // interface private (even though it appears in the header files).
Chris Lattnerfffd6a72009-02-18 06:06:56 +000088 QualType Ty = Context.getObjCConstantStringInterface();
89 if (!Ty.isNull()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +000090 Ty = Context.getObjCObjectPointerType(Ty);
David Blaikiebbafb8a2012-03-11 07:00:24 +000091 } else if (getLangOpts().NoConstantCFStrings) {
Craig Topperc3ec1492014-05-26 06:22:03 +000092 IdentifierInfo *NSIdent=nullptr;
David Blaikiebbafb8a2012-03-11 07:00:24 +000093 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Fangrui Song6907ce22018-07-30 19:24:48 +000094
Fariborz Jahanian50c925f2010-10-19 17:19:29 +000095 if (StringClass.empty())
96 NSIdent = &Context.Idents.get("NSConstantString");
97 else
98 NSIdent = &Context.Idents.get(StringClass);
Fangrui Song6907ce22018-07-30 19:24:48 +000099
Ted Kremeneke65b0862012-03-06 20:05:56 +0000100 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Fariborz Jahanian07317632010-04-23 23:19:04 +0000101 LookupOrdinaryName);
102 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
103 Context.setObjCConstantStringInterface(StrIF);
104 Ty = Context.getObjCConstantStringInterface();
105 Ty = Context.getObjCObjectPointerType(Ty);
106 } else {
107 // If there is no NSConstantString interface defined then treat this
108 // as error and recover from it.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000109 Diag(S->getBeginLoc(), diag::err_no_nsconstant_string_class)
110 << NSIdent << S->getSourceRange();
Fariborz Jahanian07317632010-04-23 23:19:04 +0000111 Ty = Context.getObjCIdType();
112 }
Chris Lattner091f6982008-06-21 21:44:18 +0000113 } else {
Patrick Beard0caa3942012-04-19 00:25:12 +0000114 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000115 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000116 LookupOrdinaryName);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000117 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
118 Context.setObjCConstantStringInterface(StrIF);
119 Ty = Context.getObjCConstantStringInterface();
Steve Naroff7cae42b2009-07-10 23:34:53 +0000120 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000121 } else {
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000122 // If there is no NSString interface defined, implicitly declare
123 // a @class NSString; and use that instead. This is to make sure
124 // type of an NSString literal is represented correctly, instead of
125 // being an 'id' type.
126 Ty = Context.getObjCNSStringType();
127 if (Ty.isNull()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000128 ObjCInterfaceDecl *NSStringIDecl =
129 ObjCInterfaceDecl::Create (Context,
130 Context.getTranslationUnitDecl(),
131 SourceLocation(), NSIdent,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000132 nullptr, nullptr, SourceLocation());
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000133 Ty = Context.getObjCInterfaceType(NSStringIDecl);
134 Context.setObjCNSStringType(Ty);
135 }
136 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000137 }
Chris Lattner091f6982008-06-21 21:44:18 +0000138 }
Mike Stump11289f42009-09-09 15:08:12 +0000139
Ted Kremeneke65b0862012-03-06 20:05:56 +0000140 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
141}
142
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000143/// Emits an error if the given method does not exist, or if the return
Jordy Rose08e500c2012-05-12 17:32:44 +0000144/// type is not an Objective-C object.
145static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
146 const ObjCInterfaceDecl *Class,
147 Selector Sel, const ObjCMethodDecl *Method) {
148 if (!Method) {
149 // FIXME: Is there a better way to avoid quotes than using getName()?
150 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
151 return false;
152 }
153
154 // Make sure the return type is reasonable.
Alp Toker314cc812014-01-25 16:55:45 +0000155 QualType ReturnType = Method->getReturnType();
Jordy Rose08e500c2012-05-12 17:32:44 +0000156 if (!ReturnType->isObjCObjectPointerType()) {
157 S.Diag(Loc, diag::err_objc_literal_method_sig)
158 << Sel;
159 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
160 << ReturnType;
161 return false;
162 }
163
164 return true;
165}
166
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000167/// Maps ObjCLiteralKind to NSClassIdKindKind
Alex Denisovb7d85632015-07-24 05:09:40 +0000168static NSAPI::NSClassIdKindKind ClassKindFromLiteralKind(
169 Sema::ObjCLiteralKind LiteralKind) {
170 switch (LiteralKind) {
171 case Sema::LK_Array:
172 return NSAPI::ClassId_NSArray;
173 case Sema::LK_Dictionary:
174 return NSAPI::ClassId_NSDictionary;
175 case Sema::LK_Numeric:
176 return NSAPI::ClassId_NSNumber;
177 case Sema::LK_String:
178 return NSAPI::ClassId_NSString;
179 case Sema::LK_Boxed:
180 return NSAPI::ClassId_NSValue;
181
182 // there is no corresponding matching
183 // between LK_None/LK_Block and NSClassIdKindKind
184 case Sema::LK_Block:
185 case Sema::LK_None:
Aaron Ballman3e839de2015-07-24 12:47:27 +0000186 break;
Alex Denisovb7d85632015-07-24 05:09:40 +0000187 }
Aaron Ballman3e839de2015-07-24 12:47:27 +0000188 llvm_unreachable("LiteralKind can't be converted into a ClassKind");
Alex Denisovb7d85632015-07-24 05:09:40 +0000189}
190
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000191/// Validates ObjCInterfaceDecl availability.
Alex Denisovb7d85632015-07-24 05:09:40 +0000192/// ObjCInterfaceDecl, used to create ObjC literals, should be defined
193/// if clang not in a debugger mode.
194static bool ValidateObjCLiteralInterfaceDecl(Sema &S, ObjCInterfaceDecl *Decl,
195 SourceLocation Loc,
196 Sema::ObjCLiteralKind LiteralKind) {
197 if (!Decl) {
198 NSAPI::NSClassIdKindKind Kind = ClassKindFromLiteralKind(LiteralKind);
199 IdentifierInfo *II = S.NSAPIObj->getNSClassId(Kind);
200 S.Diag(Loc, diag::err_undeclared_objc_literal_class)
201 << II->getName() << LiteralKind;
202 return false;
203 } else if (!Decl->hasDefinition() && !S.getLangOpts().DebuggerObjCLiteral) {
204 S.Diag(Loc, diag::err_undeclared_objc_literal_class)
205 << Decl->getName() << LiteralKind;
206 S.Diag(Decl->getLocation(), diag::note_forward_class);
207 return false;
208 }
209
210 return true;
211}
212
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000213/// Looks up ObjCInterfaceDecl of a given NSClassIdKindKind.
Alex Denisovb7d85632015-07-24 05:09:40 +0000214/// Used to create ObjC literals, such as NSDictionary (@{}),
215/// NSArray (@[]) and Boxed Expressions (@())
216static ObjCInterfaceDecl *LookupObjCInterfaceDeclForLiteral(Sema &S,
217 SourceLocation Loc,
218 Sema::ObjCLiteralKind LiteralKind) {
219 NSAPI::NSClassIdKindKind ClassKind = ClassKindFromLiteralKind(LiteralKind);
220 IdentifierInfo *II = S.NSAPIObj->getNSClassId(ClassKind);
221 NamedDecl *IF = S.LookupSingleName(S.TUScope, II, Loc,
222 Sema::LookupOrdinaryName);
223 ObjCInterfaceDecl *ID = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
224 if (!ID && S.getLangOpts().DebuggerObjCLiteral) {
225 ASTContext &Context = S.Context;
226 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
227 ID = ObjCInterfaceDecl::Create (Context, TU, SourceLocation(), II,
228 nullptr, nullptr, SourceLocation());
229 }
230
231 if (!ValidateObjCLiteralInterfaceDecl(S, ID, Loc, LiteralKind)) {
232 ID = nullptr;
233 }
234
235 return ID;
236}
237
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000238/// Retrieve the NSNumber factory method that should be used to create
Ted Kremeneke65b0862012-03-06 20:05:56 +0000239/// an Objective-C literal for the given type.
240static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
Patrick Beard0caa3942012-04-19 00:25:12 +0000241 QualType NumberType,
242 bool isLiteral = false,
243 SourceRange R = SourceRange()) {
David Blaikie05785d12013-02-20 22:23:23 +0000244 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
245 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
246
Ted Kremeneke65b0862012-03-06 20:05:56 +0000247 if (!Kind) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000248 if (isLiteral) {
249 S.Diag(Loc, diag::err_invalid_nsnumber_type)
250 << NumberType << R;
251 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000252 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000253 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000254
Ted Kremeneke65b0862012-03-06 20:05:56 +0000255 // If we already looked up this method, we're done.
256 if (S.NSNumberLiteralMethods[*Kind])
257 return S.NSNumberLiteralMethods[*Kind];
Fangrui Song6907ce22018-07-30 19:24:48 +0000258
Ted Kremeneke65b0862012-03-06 20:05:56 +0000259 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
260 /*Instance=*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +0000261
Patrick Beard0caa3942012-04-19 00:25:12 +0000262 ASTContext &CX = S.Context;
Fangrui Song6907ce22018-07-30 19:24:48 +0000263
Patrick Beard0caa3942012-04-19 00:25:12 +0000264 // Look up the NSNumber class, if we haven't done so already. It's cached
265 // in the Sema instance.
266 if (!S.NSNumberDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000267 S.NSNumberDecl = LookupObjCInterfaceDeclForLiteral(S, Loc,
268 Sema::LK_Numeric);
Patrick Beard0caa3942012-04-19 00:25:12 +0000269 if (!S.NSNumberDecl) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000270 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000271 }
Alex Denisove36748a2015-02-16 16:17:05 +0000272 }
273
274 if (S.NSNumberPointer.isNull()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000275 // generate the pointer to NSNumber type.
Jordy Roseaca01f92012-05-12 17:32:52 +0000276 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
277 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000278 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000279
Ted Kremeneke65b0862012-03-06 20:05:56 +0000280 // Look for the appropriate method within NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000281 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000282 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000283 // create a stub definition this NSNumber factory method.
Craig Topperc3ec1492014-05-26 06:22:03 +0000284 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000285 Method =
286 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
287 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
288 /*isInstance=*/false, /*isVariadic=*/false,
289 /*isPropertyAccessor=*/false,
290 /*isImplicitlyDeclared=*/true,
291 /*isDefined=*/false, ObjCMethodDecl::Required,
292 /*HasRelatedResultType=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000293 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
294 SourceLocation(), SourceLocation(),
Patrick Beard0caa3942012-04-19 00:25:12 +0000295 &CX.Idents.get("value"),
Craig Topperc3ec1492014-05-26 06:22:03 +0000296 NumberType, /*TInfo=*/nullptr,
297 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000298 Method->setMethodParams(S.Context, value, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000299 }
300
Jordy Rose08e500c2012-05-12 17:32:44 +0000301 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
Craig Topperc3ec1492014-05-26 06:22:03 +0000302 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000303
304 // Note: if the parameter type is out-of-line, we'll catch it later in the
305 // implicit conversion.
Fangrui Song6907ce22018-07-30 19:24:48 +0000306
Ted Kremeneke65b0862012-03-06 20:05:56 +0000307 S.NSNumberLiteralMethods[*Kind] = Method;
308 return Method;
309}
310
Patrick Beard0caa3942012-04-19 00:25:12 +0000311/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
312/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremeneke65b0862012-03-06 20:05:56 +0000313ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000314 // Determine the type of the literal.
315 QualType NumberType = Number->getType();
316 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
317 // In C, character literals have type 'int'. That's not the type we want
318 // to use to determine the Objective-c literal kind.
319 switch (Char->getKind()) {
320 case CharacterLiteral::Ascii:
Aaron Ballman9a17c852016-01-07 20:59:26 +0000321 case CharacterLiteral::UTF8:
Ted Kremeneke65b0862012-03-06 20:05:56 +0000322 NumberType = Context.CharTy;
323 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000324
Ted Kremeneke65b0862012-03-06 20:05:56 +0000325 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000326 NumberType = Context.getWideCharType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000327 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000328
Ted Kremeneke65b0862012-03-06 20:05:56 +0000329 case CharacterLiteral::UTF16:
330 NumberType = Context.Char16Ty;
331 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000332
Ted Kremeneke65b0862012-03-06 20:05:56 +0000333 case CharacterLiteral::UTF32:
334 NumberType = Context.Char32Ty;
335 break;
336 }
337 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000338
Ted Kremeneke65b0862012-03-06 20:05:56 +0000339 // Look for the appropriate method within NSNumber.
340 // Construct the literal.
Patrick Beard2565c592012-05-01 21:47:19 +0000341 SourceRange NR(Number->getSourceRange());
Patrick Beard0caa3942012-04-19 00:25:12 +0000342 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
Patrick Beard2565c592012-05-01 21:47:19 +0000343 true, NR);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000344 if (!Method)
345 return ExprError();
346
347 // Convert the number to the type that the parameter expects.
Alp Toker03376dc2014-07-07 09:02:20 +0000348 ParmVarDecl *ParamDecl = Method->parameters()[0];
Patrick Beard2565c592012-05-01 21:47:19 +0000349 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
350 ParamDecl);
351 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
352 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000353 Number);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000354 if (ConvertedNumber.isInvalid())
355 return ExprError();
356 Number = ConvertedNumber.get();
Fangrui Song6907ce22018-07-30 19:24:48 +0000357
Patrick Beard2565c592012-05-01 21:47:19 +0000358 // Use the effective source range of the literal, including the leading '@'.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000359 return MaybeBindToTemporary(
Patrick Beard2565c592012-05-01 21:47:19 +0000360 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
361 SourceRange(AtLoc, NR.getEnd())));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000362}
363
Fangrui Song6907ce22018-07-30 19:24:48 +0000364ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000365 SourceLocation ValueLoc,
366 bool Value) {
367 ExprResult Inner;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000368 if (getLangOpts().CPlusPlus) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000369 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
370 } else {
Fangrui Song6907ce22018-07-30 19:24:48 +0000371 // C doesn't actually have a way to represent literal values of type
Ted Kremeneke65b0862012-03-06 20:05:56 +0000372 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
373 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
Fangrui Song6907ce22018-07-30 19:24:48 +0000374 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000375 CK_IntegralToBoolean);
376 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000377
Ted Kremeneke65b0862012-03-06 20:05:56 +0000378 return BuildObjCNumericLiteral(AtLoc, Inner.get());
379}
380
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000381/// Check that the given expression is a valid element of an Objective-C
Ted Kremeneke65b0862012-03-06 20:05:56 +0000382/// collection literal.
Fangrui Song6907ce22018-07-30 19:24:48 +0000383static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000384 QualType T,
385 bool ArrayLiteral = false) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000386 // If the expression is type-dependent, there's nothing for us to do.
387 if (Element->isTypeDependent())
388 return Element;
389
390 ExprResult Result = S.CheckPlaceholderExpr(Element);
391 if (Result.isInvalid())
392 return ExprError();
393 Element = Result.get();
394
Fangrui Song6907ce22018-07-30 19:24:48 +0000395 // In C++, check for an implicit conversion to an Objective-C object pointer
Ted Kremeneke65b0862012-03-06 20:05:56 +0000396 // type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000397 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000398 InitializedEntity Entity
Jordy Roseaca01f92012-05-12 17:32:52 +0000399 = InitializedEntity::InitializeParameter(S.Context, T,
400 /*Consumed=*/false);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000401 InitializationKind Kind = InitializationKind::CreateCopy(
402 Element->getBeginLoc(), SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000403 InitializationSequence Seq(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000404 if (!Seq.Failed())
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000405 return Seq.Perform(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000406 }
407
408 Expr *OrigElement = Element;
409
410 // Perform lvalue-to-rvalue conversion.
411 Result = S.DefaultLvalueConversion(Element);
412 if (Result.isInvalid())
413 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +0000414 Element = Result.get();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000415
416 // Make sure that we have an Objective-C pointer type or block.
417 if (!Element->getType()->isObjCObjectPointerType() &&
418 !Element->getType()->isBlockPointerType()) {
419 bool Recovered = false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000420
Ted Kremeneke65b0862012-03-06 20:05:56 +0000421 // If this is potentially an Objective-C numeric literal, add the '@'.
Fangrui Song6907ce22018-07-30 19:24:48 +0000422 if (isa<IntegerLiteral>(OrigElement) ||
Ted Kremeneke65b0862012-03-06 20:05:56 +0000423 isa<CharacterLiteral>(OrigElement) ||
424 isa<FloatingLiteral>(OrigElement) ||
425 isa<ObjCBoolLiteralExpr>(OrigElement) ||
426 isa<CXXBoolLiteralExpr>(OrigElement)) {
427 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
428 int Which = isa<CharacterLiteral>(OrigElement) ? 1
429 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
430 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
431 : 3;
Fangrui Song6907ce22018-07-30 19:24:48 +0000432
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000433 S.Diag(OrigElement->getBeginLoc(), diag::err_box_literal_collection)
434 << Which << OrigElement->getSourceRange()
435 << FixItHint::CreateInsertion(OrigElement->getBeginLoc(), "@");
Fangrui Song6907ce22018-07-30 19:24:48 +0000436
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000437 Result =
438 S.BuildObjCNumericLiteral(OrigElement->getBeginLoc(), OrigElement);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000439 if (Result.isInvalid())
440 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +0000441
Ted Kremeneke65b0862012-03-06 20:05:56 +0000442 Element = Result.get();
443 Recovered = true;
444 }
445 }
446 // If this is potentially an Objective-C string literal, add the '@'.
447 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
448 if (String->isAscii()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000449 S.Diag(OrigElement->getBeginLoc(), diag::err_box_literal_collection)
450 << 0 << OrigElement->getSourceRange()
451 << FixItHint::CreateInsertion(OrigElement->getBeginLoc(), "@");
Ted Kremeneke65b0862012-03-06 20:05:56 +0000452
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000453 Result = S.BuildObjCStringLiteral(OrigElement->getBeginLoc(), String);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000454 if (Result.isInvalid())
455 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +0000456
Ted Kremeneke65b0862012-03-06 20:05:56 +0000457 Element = Result.get();
458 Recovered = true;
459 }
460 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000461
Ted Kremeneke65b0862012-03-06 20:05:56 +0000462 if (!Recovered) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000463 S.Diag(Element->getBeginLoc(), diag::err_invalid_collection_element)
464 << Element->getType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000465 return ExprError();
466 }
467 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000468 if (ArrayLiteral)
Ted Kremenek197fee42013-10-09 22:34:33 +0000469 if (ObjCStringLiteral *getString =
470 dyn_cast<ObjCStringLiteral>(OrigElement)) {
471 if (StringLiteral *SL = getString->getString()) {
472 unsigned numConcat = SL->getNumConcatenated();
473 if (numConcat > 1) {
474 // Only warn if the concatenated string doesn't come from a macro.
475 bool hasMacro = false;
476 for (unsigned i = 0; i < numConcat ; ++i)
477 if (SL->getStrTokenLoc(i).isMacroID()) {
478 hasMacro = true;
479 break;
480 }
481 if (!hasMacro)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000482 S.Diag(Element->getBeginLoc(),
Ted Kremenek197fee42013-10-09 22:34:33 +0000483 diag::warn_concatenated_nsarray_literal)
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000484 << Element->getType();
Ted Kremenek197fee42013-10-09 22:34:33 +0000485 }
486 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000487 }
488
Fangrui Song6907ce22018-07-30 19:24:48 +0000489 // Make sure that the element has the type that the container factory
490 // function expects.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000491 return S.PerformCopyInitialization(
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000492 InitializedEntity::InitializeParameter(S.Context, T,
493 /*Consumed=*/false),
494 Element->getBeginLoc(), Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000495}
496
Patrick Beard0caa3942012-04-19 00:25:12 +0000497ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
498 if (ValueExpr->isTypeDependent()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000499 ObjCBoxedExpr *BoxedExpr =
Craig Topperc3ec1492014-05-26 06:22:03 +0000500 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000501 return BoxedExpr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000502 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000503 ObjCMethodDecl *BoxingMethod = nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000504 QualType BoxedType;
505 // Convert the expression to an RValue, so we can check for pointer types...
506 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
507 if (RValue.isInvalid()) {
508 return ExprError();
509 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000510 SourceLocation Loc = SR.getBegin();
Patrick Beard0caa3942012-04-19 00:25:12 +0000511 ValueExpr = RValue.get();
Patrick Beard2565c592012-05-01 21:47:19 +0000512 QualType ValueType(ValueExpr->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +0000513 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
514 QualType PointeeType = PT->getPointeeType();
515 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
516
517 if (!NSStringDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000518 NSStringDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
519 Sema::LK_String);
Patrick Beard0caa3942012-04-19 00:25:12 +0000520 if (!NSStringDecl) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000521 return ExprError();
522 }
Jordy Roseaca01f92012-05-12 17:32:52 +0000523 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
524 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000525 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000526
Patrick Beard0caa3942012-04-19 00:25:12 +0000527 if (!StringWithUTF8StringMethod) {
528 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
529 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
530
531 // Look for the appropriate method within NSString.
Jordy Rose08e500c2012-05-12 17:32:44 +0000532 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
533 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000534 // Debugger needs to work even if NSString hasn't been defined.
Craig Topperc3ec1492014-05-26 06:22:03 +0000535 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000536 ObjCMethodDecl *M = ObjCMethodDecl::Create(
537 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
538 NSStringPointer, ReturnTInfo, NSStringDecl,
539 /*isInstance=*/false, /*isVariadic=*/false,
540 /*isPropertyAccessor=*/false,
541 /*isImplicitlyDeclared=*/true,
542 /*isDefined=*/false, ObjCMethodDecl::Required,
543 /*HasRelatedResultType=*/false);
Jordy Roseaca01f92012-05-12 17:32:52 +0000544 QualType ConstCharType = Context.CharTy.withConst();
Patrick Beard0caa3942012-04-19 00:25:12 +0000545 ParmVarDecl *value =
546 ParmVarDecl::Create(Context, M,
547 SourceLocation(), SourceLocation(),
548 &Context.Idents.get("value"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000549 Context.getPointerType(ConstCharType),
Craig Topperc3ec1492014-05-26 06:22:03 +0000550 /*TInfo=*/nullptr,
551 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000552 M->setMethodParams(Context, value, None);
Jordy Rose08e500c2012-05-12 17:32:44 +0000553 BoxingMethod = M;
Patrick Beard0caa3942012-04-19 00:25:12 +0000554 }
Jordy Rose890f4572012-05-12 15:53:41 +0000555
Alex Denisovb7d85632015-07-24 05:09:40 +0000556 if (!validateBoxingMethod(*this, Loc, NSStringDecl,
Jordy Rose08e500c2012-05-12 17:32:44 +0000557 stringWithUTF8String, BoxingMethod))
558 return ExprError();
559
560 StringWithUTF8StringMethod = BoxingMethod;
Patrick Beard0caa3942012-04-19 00:25:12 +0000561 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000562
Patrick Beard0caa3942012-04-19 00:25:12 +0000563 BoxingMethod = StringWithUTF8StringMethod;
564 BoxedType = NSStringPointer;
Alex Lorenz49370ac2017-11-08 21:33:15 +0000565 // Transfer the nullability from method's return type.
566 Optional<NullabilityKind> Nullability =
567 BoxingMethod->getReturnType()->getNullability(Context);
568 if (Nullability)
569 BoxedType = Context.getAttributedType(
570 AttributedType::getNullabilityAttrKind(*Nullability), BoxedType,
571 BoxedType);
Patrick Beard0caa3942012-04-19 00:25:12 +0000572 }
Patrick Beard2565c592012-05-01 21:47:19 +0000573 } else if (ValueType->isBuiltinType()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000574 // The other types we support are numeric, char and BOOL/bool. We could also
575 // provide limited support for structure types, such as NSRange, NSRect, and
576 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
577 // for more details.
578
579 // Check for a top-level character literal.
580 if (const CharacterLiteral *Char =
581 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
582 // In C, character literals have type 'int'. That's not the type we want
583 // to use to determine the Objective-c literal kind.
584 switch (Char->getKind()) {
585 case CharacterLiteral::Ascii:
Aaron Ballman9a17c852016-01-07 20:59:26 +0000586 case CharacterLiteral::UTF8:
Patrick Beard0caa3942012-04-19 00:25:12 +0000587 ValueType = Context.CharTy;
588 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000589
Patrick Beard0caa3942012-04-19 00:25:12 +0000590 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000591 ValueType = Context.getWideCharType();
Patrick Beard0caa3942012-04-19 00:25:12 +0000592 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000593
Patrick Beard0caa3942012-04-19 00:25:12 +0000594 case CharacterLiteral::UTF16:
595 ValueType = Context.Char16Ty;
596 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000597
Patrick Beard0caa3942012-04-19 00:25:12 +0000598 case CharacterLiteral::UTF32:
599 ValueType = Context.Char32Ty;
600 break;
601 }
602 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000603 // FIXME: Do I need to do anything special with BoolTy expressions?
Fangrui Song6907ce22018-07-30 19:24:48 +0000604
Patrick Beard0caa3942012-04-19 00:25:12 +0000605 // Look for the appropriate method within NSNumber.
Alex Denisovb7d85632015-07-24 05:09:40 +0000606 BoxingMethod = getNSNumberFactoryMethod(*this, Loc, ValueType);
Patrick Beard0caa3942012-04-19 00:25:12 +0000607 BoxedType = NSNumberPointer;
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000608 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
609 if (!ET->getDecl()->isComplete()) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000610 Diag(Loc, diag::err_objc_incomplete_boxed_expression_type)
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000611 << ValueType << ValueExpr->getSourceRange();
612 return ExprError();
613 }
614
Alex Denisovb7d85632015-07-24 05:09:40 +0000615 BoxingMethod = getNSNumberFactoryMethod(*this, Loc,
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000616 ET->getDecl()->getIntegerType());
617 BoxedType = NSNumberPointer;
Alex Denisovfde64952015-06-26 05:28:36 +0000618 } else if (ValueType->isObjCBoxableRecordType()) {
619 // Support for structure types, that marked as objc_boxable
620 // struct __attribute__((objc_boxable)) s { ... };
Fangrui Song6907ce22018-07-30 19:24:48 +0000621
Alex Denisovfde64952015-06-26 05:28:36 +0000622 // Look up the NSValue class, if we haven't done so already. It's cached
623 // in the Sema instance.
624 if (!NSValueDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000625 NSValueDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
626 Sema::LK_Boxed);
Alex Denisovfde64952015-06-26 05:28:36 +0000627 if (!NSValueDecl) {
Alex Denisovfde64952015-06-26 05:28:36 +0000628 return ExprError();
629 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000630
Alex Denisovfde64952015-06-26 05:28:36 +0000631 // generate the pointer to NSValue type.
632 QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
633 NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
634 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000635
Alex Denisovfde64952015-06-26 05:28:36 +0000636 if (!ValueWithBytesObjCTypeMethod) {
637 IdentifierInfo *II[] = {
638 &Context.Idents.get("valueWithBytes"),
639 &Context.Idents.get("objCType")
640 };
641 Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
Fangrui Song6907ce22018-07-30 19:24:48 +0000642
Alex Denisovfde64952015-06-26 05:28:36 +0000643 // Look for the appropriate method within NSValue.
644 BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
645 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
646 // Debugger needs to work even if NSValue hasn't been defined.
647 TypeSourceInfo *ReturnTInfo = nullptr;
648 ObjCMethodDecl *M = ObjCMethodDecl::Create(
649 Context,
650 SourceLocation(),
651 SourceLocation(),
652 ValueWithBytesObjCType,
653 NSValuePointer,
654 ReturnTInfo,
655 NSValueDecl,
656 /*isInstance=*/false,
657 /*isVariadic=*/false,
658 /*isPropertyAccessor=*/false,
659 /*isImplicitlyDeclared=*/true,
660 /*isDefined=*/false,
661 ObjCMethodDecl::Required,
662 /*HasRelatedResultType=*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +0000663
Alex Denisovfde64952015-06-26 05:28:36 +0000664 SmallVector<ParmVarDecl *, 2> Params;
Fangrui Song6907ce22018-07-30 19:24:48 +0000665
Alex Denisovfde64952015-06-26 05:28:36 +0000666 ParmVarDecl *bytes =
667 ParmVarDecl::Create(Context, M,
668 SourceLocation(), SourceLocation(),
669 &Context.Idents.get("bytes"),
670 Context.VoidPtrTy.withConst(),
671 /*TInfo=*/nullptr,
672 SC_None, nullptr);
673 Params.push_back(bytes);
Fangrui Song6907ce22018-07-30 19:24:48 +0000674
Alex Denisovfde64952015-06-26 05:28:36 +0000675 QualType ConstCharType = Context.CharTy.withConst();
676 ParmVarDecl *type =
677 ParmVarDecl::Create(Context, M,
678 SourceLocation(), SourceLocation(),
679 &Context.Idents.get("type"),
680 Context.getPointerType(ConstCharType),
681 /*TInfo=*/nullptr,
682 SC_None, nullptr);
683 Params.push_back(type);
Fangrui Song6907ce22018-07-30 19:24:48 +0000684
Alex Denisovfde64952015-06-26 05:28:36 +0000685 M->setMethodParams(Context, Params, None);
686 BoxingMethod = M;
687 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000688
Alex Denisovb7d85632015-07-24 05:09:40 +0000689 if (!validateBoxingMethod(*this, Loc, NSValueDecl,
Alex Denisovfde64952015-06-26 05:28:36 +0000690 ValueWithBytesObjCType, BoxingMethod))
691 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +0000692
Alex Denisovfde64952015-06-26 05:28:36 +0000693 ValueWithBytesObjCTypeMethod = BoxingMethod;
694 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000695
Alex Denisovfde64952015-06-26 05:28:36 +0000696 if (!ValueType.isTriviallyCopyableType(Context)) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000697 Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type)
Alex Denisovfde64952015-06-26 05:28:36 +0000698 << ValueType << ValueExpr->getSourceRange();
699 return ExprError();
700 }
701
702 BoxingMethod = ValueWithBytesObjCTypeMethod;
703 BoxedType = NSValuePointer;
Patrick Beard0caa3942012-04-19 00:25:12 +0000704 }
705
706 if (!BoxingMethod) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000707 Diag(Loc, diag::err_objc_illegal_boxed_expression_type)
Patrick Beard0caa3942012-04-19 00:25:12 +0000708 << ValueType << ValueExpr->getSourceRange();
709 return ExprError();
710 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000711
Alex Denisovb7d85632015-07-24 05:09:40 +0000712 DiagnoseUseOfDecl(BoxingMethod, Loc);
Alex Denisovfde64952015-06-26 05:28:36 +0000713
714 ExprResult ConvertedValueExpr;
715 if (ValueType->isObjCBoxableRecordType()) {
716 InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
Fangrui Song6907ce22018-07-30 19:24:48 +0000717 ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
Alex Denisovfde64952015-06-26 05:28:36 +0000718 ValueExpr);
719 } else {
720 // Convert the expression to the type that the parameter requires.
721 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
722 InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
723 ParamDecl);
724 ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
725 ValueExpr);
726 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000727
Patrick Beard0caa3942012-04-19 00:25:12 +0000728 if (ConvertedValueExpr.isInvalid())
729 return ExprError();
730 ValueExpr = ConvertedValueExpr.get();
Fangrui Song6907ce22018-07-30 19:24:48 +0000731
732 ObjCBoxedExpr *BoxedExpr =
Patrick Beard0caa3942012-04-19 00:25:12 +0000733 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
734 BoxingMethod, SR);
735 return MaybeBindToTemporary(BoxedExpr);
736}
737
John McCallf2538342012-07-31 05:14:30 +0000738/// Build an ObjC subscript pseudo-object expression, given that
739/// that's supported by the runtime.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000740ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
741 Expr *IndexExpr,
742 ObjCMethodDecl *getterMethod,
743 ObjCMethodDecl *setterMethod) {
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +0000744 assert(!LangOpts.isSubscriptPointerArithmetic());
John McCall5fb5df92012-06-20 06:18:46 +0000745
John McCallf2538342012-07-31 05:14:30 +0000746 // We can't get dependent types here; our callers should have
747 // filtered them out.
748 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
749 "base or index cannot have dependent type here");
750
751 // Filter out placeholders in the index. In theory, overloads could
752 // be preserved here, although that might not actually work correctly.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000753 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
754 if (Result.isInvalid())
755 return ExprError();
756 IndexExpr = Result.get();
Fangrui Song6907ce22018-07-30 19:24:48 +0000757
John McCallf2538342012-07-31 05:14:30 +0000758 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000759 Result = DefaultLvalueConversion(BaseExpr);
760 if (Result.isInvalid())
761 return ExprError();
762 BaseExpr = Result.get();
John McCallf2538342012-07-31 05:14:30 +0000763
764 // Build the pseudo-object expression.
James Y Knight6c2f06b2015-12-31 04:43:19 +0000765 return new (Context) ObjCSubscriptRefExpr(
766 BaseExpr, IndexExpr, Context.PseudoObjectTy, VK_LValue, OK_ObjCSubscript,
767 getterMethod, setterMethod, RB);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000768}
769
770ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000771 SourceLocation Loc = SR.getBegin();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000772
Alex Denisovb7d85632015-07-24 05:09:40 +0000773 if (!NSArrayDecl) {
774 NSArrayDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
775 Sema::LK_Array);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000776 if (!NSArrayDecl) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000777 return ExprError();
778 }
779 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000780
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000781 // Find the arrayWithObjects:count: method, if we haven't done so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000782 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000783 if (!ArrayWithObjectsMethod) {
784 Selector
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000785 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
786 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000787 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000788 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000789 Method = ObjCMethodDecl::Create(
790 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000791 Context.getTranslationUnitDecl(), false /*Instance*/,
Alp Toker314cc812014-01-25 16:55:45 +0000792 false /*isVariadic*/,
793 /*isPropertyAccessor=*/false,
794 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
795 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000796 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000797 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000798 SourceLocation(),
799 SourceLocation(),
800 &Context.Idents.get("objects"),
801 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000802 /*TInfo=*/nullptr,
803 SC_None, nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000804 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000805 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000806 SourceLocation(),
807 SourceLocation(),
808 &Context.Idents.get("cnt"),
809 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000810 /*TInfo=*/nullptr, SC_None,
811 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000812 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000813 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000814 }
815
Alex Denisovb7d85632015-07-24 05:09:40 +0000816 if (!validateBoxingMethod(*this, Loc, NSArrayDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000817 return ExprError();
Jordy Rose08e500c2012-05-12 17:32:44 +0000818
Jordy Rose4af44872012-05-12 17:32:56 +0000819 // Dig out the type that all elements should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000820 QualType T = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000821 const PointerType *PtrT = T->getAs<PointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +0000822 if (!PtrT ||
Jordy Rose4af44872012-05-12 17:32:56 +0000823 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
824 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
825 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000826 Diag(Method->parameters()[0]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000827 diag::note_objc_literal_method_param)
Fangrui Song6907ce22018-07-30 19:24:48 +0000828 << 0 << T
Jordy Rose4af44872012-05-12 17:32:56 +0000829 << Context.getPointerType(IdT.withConst());
830 return ExprError();
831 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000832
Jordy Rose4af44872012-05-12 17:32:56 +0000833 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000834 if (!Method->parameters()[1]->getType()->isIntegerType()) {
Jordy Rose4af44872012-05-12 17:32:56 +0000835 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
836 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000837 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000838 diag::note_objc_literal_method_param)
Fangrui Song6907ce22018-07-30 19:24:48 +0000839 << 1
Alp Toker03376dc2014-07-07 09:02:20 +0000840 << Method->parameters()[1]->getType()
Jordy Rose4af44872012-05-12 17:32:56 +0000841 << "integral";
842 return ExprError();
843 }
844
845 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rose08e500c2012-05-12 17:32:44 +0000846 ArrayWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000847 }
848
Alp Toker03376dc2014-07-07 09:02:20 +0000849 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000850 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000851
852 // Check that each of the elements provided is valid in a collection literal,
853 // performing conversions as necessary.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000854 Expr **ElementsBuffer = Elements.data();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000855 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
856 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
857 ElementsBuffer[I],
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000858 RequiredType, true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000859 if (Converted.isInvalid())
860 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +0000861
Ted Kremeneke65b0862012-03-06 20:05:56 +0000862 ElementsBuffer[I] = Converted.get();
863 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000864
865 QualType Ty
Ted Kremeneke65b0862012-03-06 20:05:56 +0000866 = Context.getObjCObjectPointerType(
867 Context.getObjCInterfaceType(NSArrayDecl));
868
869 return MaybeBindToTemporary(
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000870 ObjCArrayLiteral::Create(Context, Elements, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000871 ArrayWithObjectsMethod, SR));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000872}
873
Craig Topperd4336e02015-12-24 23:58:15 +0000874ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
875 MutableArrayRef<ObjCDictionaryElement> Elements) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000876 SourceLocation Loc = SR.getBegin();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000877
Alex Denisovb7d85632015-07-24 05:09:40 +0000878 if (!NSDictionaryDecl) {
879 NSDictionaryDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
880 Sema::LK_Dictionary);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000881 if (!NSDictionaryDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000882 return ExprError();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000883 }
884 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000885
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000886 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
887 // so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000888 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000889 if (!DictionaryWithObjectsMethod) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000890 Selector Sel = NSAPIObj->getNSDictionarySelector(
891 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
892 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000893 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000894 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000895 SourceLocation(), SourceLocation(), Sel,
896 IdT,
Craig Topperc3ec1492014-05-26 06:22:03 +0000897 nullptr /*TypeSourceInfo */,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000898 Context.getTranslationUnitDecl(),
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000899 false /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000900 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000901 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
902 ObjCMethodDecl::Required,
903 false);
904 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000905 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000906 SourceLocation(),
907 SourceLocation(),
908 &Context.Idents.get("objects"),
909 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000910 /*TInfo=*/nullptr, SC_None,
911 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000912 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000913 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000914 SourceLocation(),
915 SourceLocation(),
916 &Context.Idents.get("keys"),
917 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000918 /*TInfo=*/nullptr, SC_None,
919 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000920 Params.push_back(keys);
Jordy Rose08e500c2012-05-12 17:32:44 +0000921 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000922 SourceLocation(),
923 SourceLocation(),
924 &Context.Idents.get("cnt"),
925 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000926 /*TInfo=*/nullptr, SC_None,
927 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000928 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000929 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000930 }
931
Jordy Rose08e500c2012-05-12 17:32:44 +0000932 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
933 Method))
934 return ExprError();
935
Jordy Rose4af44872012-05-12 17:32:56 +0000936 // Dig out the type that all values should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000937 QualType ValueT = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000938 const PointerType *PtrValue = ValueT->getAs<PointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +0000939 if (!PtrValue ||
Jordy Rose4af44872012-05-12 17:32:56 +0000940 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000941 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000942 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000943 Diag(Method->parameters()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000944 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000945 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000946 << Context.getPointerType(IdT.withConst());
947 return ExprError();
948 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000949
Jordy Rose4af44872012-05-12 17:32:56 +0000950 // Dig out the type that all keys should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000951 QualType KeyT = Method->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000952 const PointerType *PtrKey = KeyT->getAs<PointerType>();
Fangrui Song6907ce22018-07-30 19:24:48 +0000953 if (!PtrKey ||
Jordy Rose4af44872012-05-12 17:32:56 +0000954 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
955 IdT)) {
956 bool err = true;
957 if (PtrKey) {
958 if (QIDNSCopying.isNull()) {
959 // key argument of selector is id<NSCopying>?
960 if (ObjCProtocolDecl *NSCopyingPDecl =
961 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
962 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
Fangrui Song6907ce22018-07-30 19:24:48 +0000963 QIDNSCopying =
Douglas Gregore9d95f12015-07-07 03:57:35 +0000964 Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { },
965 llvm::makeArrayRef(
966 (ObjCProtocolDecl**) PQ,
Douglas Gregorab209d82015-07-07 03:58:42 +0000967 1),
968 false);
Jordy Rose4af44872012-05-12 17:32:56 +0000969 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
970 }
971 }
972 if (!QIDNSCopying.isNull())
973 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
974 QIDNSCopying);
975 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000976
Jordy Rose4af44872012-05-12 17:32:56 +0000977 if (err) {
978 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
979 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000980 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000981 diag::note_objc_literal_method_param)
982 << 1 << KeyT
983 << Context.getPointerType(IdT.withConst());
984 return ExprError();
985 }
986 }
987
988 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000989 QualType CountType = Method->parameters()[2]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000990 if (!CountType->isIntegerType()) {
991 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
992 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000993 Diag(Method->parameters()[2]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000994 diag::note_objc_literal_method_param)
995 << 2 << CountType
996 << "integral";
997 return ExprError();
998 }
999
1000 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
1001 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001002 }
1003
Alp Toker03376dc2014-07-07 09:02:20 +00001004 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +00001005 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
Alp Toker03376dc2014-07-07 09:02:20 +00001006 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +00001007 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
1008
Fangrui Song6907ce22018-07-30 19:24:48 +00001009 // Check that each of the keys and values provided is valid in a collection
Ted Kremeneke65b0862012-03-06 20:05:56 +00001010 // literal, performing conversions as necessary.
1011 bool HasPackExpansions = false;
Craig Topperd4336e02015-12-24 23:58:15 +00001012 for (ObjCDictionaryElement &Element : Elements) {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001013 // Check the key.
Craig Topperd4336e02015-12-24 23:58:15 +00001014 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Element.Key,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001015 KeyT);
1016 if (Key.isInvalid())
1017 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +00001018
Ted Kremeneke65b0862012-03-06 20:05:56 +00001019 // Check the value.
1020 ExprResult Value
Craig Topperd4336e02015-12-24 23:58:15 +00001021 = CheckObjCCollectionLiteralElement(*this, Element.Value, ValueT);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001022 if (Value.isInvalid())
1023 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +00001024
Craig Topperd4336e02015-12-24 23:58:15 +00001025 Element.Key = Key.get();
1026 Element.Value = Value.get();
Fangrui Song6907ce22018-07-30 19:24:48 +00001027
Craig Topperd4336e02015-12-24 23:58:15 +00001028 if (Element.EllipsisLoc.isInvalid())
Ted Kremeneke65b0862012-03-06 20:05:56 +00001029 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00001030
Craig Topperd4336e02015-12-24 23:58:15 +00001031 if (!Element.Key->containsUnexpandedParameterPack() &&
1032 !Element.Value->containsUnexpandedParameterPack()) {
1033 Diag(Element.EllipsisLoc,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001034 diag::err_pack_expansion_without_parameter_packs)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001035 << SourceRange(Element.Key->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001036 Element.Value->getEndLoc());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001037 return ExprError();
1038 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001039
Ted Kremeneke65b0862012-03-06 20:05:56 +00001040 HasPackExpansions = true;
1041 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001042
Ted Kremeneke65b0862012-03-06 20:05:56 +00001043 QualType Ty
1044 = Context.getObjCObjectPointerType(
Robert Wilhelm88e02492013-08-19 07:57:02 +00001045 Context.getObjCInterfaceType(NSDictionaryDecl));
1046 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
Craig Topperd4336e02015-12-24 23:58:15 +00001047 Context, Elements, HasPackExpansions, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +00001048 DictionaryWithObjectsMethod, SR));
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001049}
1050
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001051ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregorabd9e962010-04-20 15:39:42 +00001052 TypeSourceInfo *EncodedTypeInfo,
Anders Carlsson315d2292009-06-07 18:45:35 +00001053 SourceLocation RParenLoc) {
Douglas Gregorabd9e962010-04-20 15:39:42 +00001054 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlsson315d2292009-06-07 18:45:35 +00001055 QualType StrTy;
Mike Stump11289f42009-09-09 15:08:12 +00001056 if (EncodedType->isDependentType())
Anders Carlsson315d2292009-06-07 18:45:35 +00001057 StrTy = Context.DependentTy;
1058 else {
Fariborz Jahaniand9bc6c32011-06-16 22:34:44 +00001059 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
1060 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001061 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001062 diag::err_incomplete_type_objc_at_encode,
1063 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001064 return ExprError();
1065
Anders Carlsson315d2292009-06-07 18:45:35 +00001066 std::string Str;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00001067 QualType NotEncodedT;
1068 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
1069 if (!NotEncodedT.isNull())
1070 Diag(AtLoc, diag::warn_incomplete_encoded_type)
1071 << EncodedType << NotEncodedT;
Anders Carlsson315d2292009-06-07 18:45:35 +00001072
1073 // The type of @encode is the same as the type of the corresponding string,
1074 // which is an array type.
1075 StrTy = Context.CharTy;
1076 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001077 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlsson315d2292009-06-07 18:45:35 +00001078 StrTy.addConst();
1079 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
1080 ArrayType::Normal, 0);
1081 }
Mike Stump11289f42009-09-09 15:08:12 +00001082
Douglas Gregorabd9e962010-04-20 15:39:42 +00001083 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlsson315d2292009-06-07 18:45:35 +00001084}
1085
John McCallfaf5fb42010-08-26 23:41:50 +00001086ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1087 SourceLocation EncodeLoc,
1088 SourceLocation LParenLoc,
1089 ParsedType ty,
1090 SourceLocation RParenLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001091 // FIXME: Preserve type source info ?
Douglas Gregorabd9e962010-04-20 15:39:42 +00001092 TypeSourceInfo *TInfo;
1093 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1094 if (!TInfo)
1095 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
Craig Topper07fa1762015-11-15 02:31:46 +00001096 getLocForEndOfToken(LParenLoc));
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001097
Douglas Gregorabd9e962010-04-20 15:39:42 +00001098 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001099}
1100
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001101static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1102 SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001103 SourceLocation LParenLoc,
1104 SourceLocation RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001105 ObjCMethodDecl *Method,
1106 ObjCMethodList &MethList) {
1107 ObjCMethodList *M = &MethList;
1108 bool Warned = false;
1109 for (M = M->getNext(); M; M=M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00001110 ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001111 if (MatchingMethodDecl == Method ||
1112 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1113 MatchingMethodDecl->getSelector() != Method->getSelector())
1114 continue;
1115 if (!S.MatchTwoMethodDeclarations(Method,
1116 MatchingMethodDecl, Sema::MMS_loose)) {
1117 if (!Warned) {
1118 Warned = true;
Richard Smith01d96982016-12-02 23:00:28 +00001119 S.Diag(AtLoc, diag::warn_multiple_selectors)
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001120 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1121 << FixItHint::CreateInsertion(RParenLoc, ")");
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001122 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1123 << Method->getDeclName();
1124 }
1125 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1126 << MatchingMethodDecl->getDeclName();
1127 }
1128 }
1129 return Warned;
1130}
1131
1132static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001133 ObjCMethodDecl *Method,
1134 SourceLocation LParenLoc,
1135 SourceLocation RParenLoc,
1136 bool WarnMultipleSelectors) {
1137 if (!WarnMultipleSelectors ||
Richard Smith01d96982016-12-02 23:00:28 +00001138 S.Diags.isIgnored(diag::warn_multiple_selectors, SourceLocation()))
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001139 return;
1140 bool Warned = false;
1141 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1142 e = S.MethodPool.end(); b != e; b++) {
1143 // first, instance methods
1144 ObjCMethodList &InstMethList = b->second.first;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001145 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001146 Method, InstMethList))
1147 Warned = true;
Fangrui Song6907ce22018-07-30 19:24:48 +00001148
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001149 // second, class methods
1150 ObjCMethodList &ClsMethList = b->second.second;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001151 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1152 Method, ClsMethList) || Warned)
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001153 return;
1154 }
1155}
1156
John McCallfaf5fb42010-08-26 23:41:50 +00001157ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1158 SourceLocation AtLoc,
1159 SourceLocation SelLoc,
1160 SourceLocation LParenLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001161 SourceLocation RParenLoc,
1162 bool WarnMultipleSelectors) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001163 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00001164 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001165 if (!Method)
1166 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian0571d9b2009-06-16 16:25:00 +00001167 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00001168 if (!Method) {
1169 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1170 Selector MatchedSel = OM->getSelector();
1171 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1172 RParenLoc.getLocWithOffset(-1));
1173 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1174 << Sel << MatchedSel
1175 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
Fangrui Song6907ce22018-07-30 19:24:48 +00001176
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00001177 } else
1178 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001179 } else
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001180 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1181 WarnMultipleSelectors);
Chandler Carruth12c8f652015-03-27 00:55:05 +00001182
Fariborz Jahanian65a78b52014-05-09 19:51:39 +00001183 if (Method &&
1184 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
Chandler Carruth12c8f652015-03-27 00:55:05 +00001185 !getSourceManager().isInSystemHeader(Method->getLocation()))
1186 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001187
Fangrui Song6907ce22018-07-30 19:24:48 +00001188 // In ARC, forbid the user from using @selector for
John McCall31168b02011-06-15 23:02:42 +00001189 // retain/release/autorelease/dealloc/retainCount.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001190 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001191 switch (Sel.getMethodFamily()) {
1192 case OMF_retain:
1193 case OMF_release:
1194 case OMF_autorelease:
1195 case OMF_retainCount:
1196 case OMF_dealloc:
Fangrui Song6907ce22018-07-30 19:24:48 +00001197 Diag(AtLoc, diag::err_arc_illegal_selector) <<
John McCall31168b02011-06-15 23:02:42 +00001198 Sel << SourceRange(LParenLoc, RParenLoc);
1199 break;
1200
1201 case OMF_None:
1202 case OMF_alloc:
1203 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00001204 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00001205 case OMF_init:
1206 case OMF_mutableCopy:
1207 case OMF_new:
1208 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00001209 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001210 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001211 break;
1212 }
1213 }
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001214 QualType Ty = Context.getObjCSelType();
Daniel Dunbar45858d22010-02-03 20:11:42 +00001215 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001216}
1217
John McCallfaf5fb42010-08-26 23:41:50 +00001218ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1219 SourceLocation AtLoc,
1220 SourceLocation ProtoLoc,
1221 SourceLocation LParenLoc,
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001222 SourceLocation ProtoIdLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00001223 SourceLocation RParenLoc) {
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001224 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001225 if (!PDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001226 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001227 return true;
1228 }
Alex Lorenzb111da12018-08-17 22:18:08 +00001229 if (!PDecl->hasDefinition()) {
1230 Diag(ProtoLoc, diag::err_atprotocol_protocol) << PDecl;
1231 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
1232 } else {
Fariborz Jahaniana57d91c22014-07-25 19:45:01 +00001233 PDecl = PDecl->getDefinition();
Alex Lorenzb111da12018-08-17 22:18:08 +00001234 }
Mike Stump11289f42009-09-09 15:08:12 +00001235
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001236 QualType Ty = Context.getObjCProtoType();
1237 if (Ty.isNull())
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001238 return true;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001239 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001240 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001241}
1242
John McCall5f2d5562011-02-03 09:00:02 +00001243/// Try to capture an implicit reference to 'self'.
Eli Friedman24af8502012-02-03 22:47:37 +00001244ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1245 DeclContext *DC = getFunctionLevelDeclContext();
John McCall5f2d5562011-02-03 09:00:02 +00001246
1247 // If we're not in an ObjC method, error out. Note that, unlike the
1248 // C++ case, we don't require an instance method --- class methods
1249 // still have a 'self', and we really do still need to capture it!
1250 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1251 if (!method)
Craig Topperc3ec1492014-05-26 06:22:03 +00001252 return nullptr;
John McCall5f2d5562011-02-03 09:00:02 +00001253
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001254 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall5f2d5562011-02-03 09:00:02 +00001255
1256 return method;
1257}
1258
Douglas Gregor64910ca2011-09-09 20:05:21 +00001259static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
Douglas Gregor813a0662015-06-19 18:14:38 +00001260 QualType origType = T;
1261 if (auto nullability = AttributedType::stripOuterNullability(T)) {
1262 if (T == Context.getObjCInstanceType()) {
1263 return Context.getAttributedType(
1264 AttributedType::getNullabilityAttrKind(*nullability),
1265 Context.getObjCIdType(),
1266 Context.getObjCIdType());
1267 }
1268
1269 return origType;
1270 }
1271
Douglas Gregor64910ca2011-09-09 20:05:21 +00001272 if (T == Context.getObjCInstanceType())
1273 return Context.getObjCIdType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001274
Douglas Gregor813a0662015-06-19 18:14:38 +00001275 return origType;
Douglas Gregor64910ca2011-09-09 20:05:21 +00001276}
1277
Douglas Gregor813a0662015-06-19 18:14:38 +00001278/// Determine the result type of a message send based on the receiver type,
1279/// method, and the kind of message send.
1280///
1281/// This is the "base" result type, which will still need to be adjusted
1282/// to account for nullability.
1283static QualType getBaseMessageSendResultType(Sema &S,
1284 QualType ReceiverType,
1285 ObjCMethodDecl *Method,
1286 bool isClassMessage,
1287 bool isSuperMessage) {
Douglas Gregor33823722011-06-11 01:09:30 +00001288 assert(Method && "Must have a method");
1289 if (!Method->hasRelatedResultType())
Douglas Gregore83b9562015-07-07 03:57:53 +00001290 return Method->getSendResultType(ReceiverType);
Douglas Gregor813a0662015-06-19 18:14:38 +00001291
1292 ASTContext &Context = S.Context;
1293
1294 // Local function that transfers the nullability of the method's
1295 // result type to the returned result.
1296 auto transferNullability = [&](QualType type) -> QualType {
1297 // If the method's result type has nullability, extract it.
Douglas Gregore83b9562015-07-07 03:57:53 +00001298 if (auto nullability = Method->getSendResultType(ReceiverType)
1299 ->getNullability(Context)){
Douglas Gregor813a0662015-06-19 18:14:38 +00001300 // Strip off any outer nullability sugar from the provided type.
1301 (void)AttributedType::stripOuterNullability(type);
1302
1303 // Form a new attributed type using the method result type's nullability.
1304 return Context.getAttributedType(
1305 AttributedType::getNullabilityAttrKind(*nullability),
1306 type,
1307 type);
1308 }
1309
1310 return type;
1311 };
1312
Douglas Gregor33823722011-06-11 01:09:30 +00001313 // If a method has a related return type:
1314 // - if the method found is an instance method, but the message send
1315 // was a class message send, T is the declared return type of the method
1316 // found
1317 if (Method->isInstanceMethod() && isClassMessage)
Fangrui Song6907ce22018-07-30 19:24:48 +00001318 return stripObjCInstanceType(Context,
Douglas Gregore83b9562015-07-07 03:57:53 +00001319 Method->getSendResultType(ReceiverType));
Douglas Gregor813a0662015-06-19 18:14:38 +00001320
1321 // - if the receiver is super, T is a pointer to the class of the
Douglas Gregor33823722011-06-11 01:09:30 +00001322 // enclosing method definition
1323 if (isSuperMessage) {
Douglas Gregor813a0662015-06-19 18:14:38 +00001324 if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
1325 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1326 return transferNullability(
1327 Context.getObjCObjectPointerType(
1328 Context.getObjCInterfaceType(Class)));
1329 }
Douglas Gregor33823722011-06-11 01:09:30 +00001330 }
Douglas Gregor813a0662015-06-19 18:14:38 +00001331
Douglas Gregor33823722011-06-11 01:09:30 +00001332 // - if the receiver is the name of a class U, T is a pointer to U
Douglas Gregore83b9562015-07-07 03:57:53 +00001333 if (ReceiverType->getAsObjCInterfaceType())
Douglas Gregor813a0662015-06-19 18:14:38 +00001334 return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
1335 // - if the receiver is of type Class or qualified Class type,
Douglas Gregor33823722011-06-11 01:09:30 +00001336 // T is the declared return type of the method.
1337 if (ReceiverType->isObjCClassType() ||
1338 ReceiverType->isObjCQualifiedClassType())
Fangrui Song6907ce22018-07-30 19:24:48 +00001339 return stripObjCInstanceType(Context,
Douglas Gregore83b9562015-07-07 03:57:53 +00001340 Method->getSendResultType(ReceiverType));
Douglas Gregor813a0662015-06-19 18:14:38 +00001341
Douglas Gregor33823722011-06-11 01:09:30 +00001342 // - if the receiver is id, qualified id, Class, or qualified Class, T
1343 // is the receiver type, otherwise
1344 // - T is the type of the receiver expression.
Douglas Gregor813a0662015-06-19 18:14:38 +00001345 return transferNullability(ReceiverType);
1346}
1347
Alex Lorenzf50d1ac2018-12-20 22:11:11 +00001348QualType Sema::getMessageSendResultType(const Expr *Receiver,
1349 QualType ReceiverType,
Douglas Gregor813a0662015-06-19 18:14:38 +00001350 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.
Alex Lorenzf50d1ac2018-12-20 22:11:11 +00001360 if (isClassMessage) {
1361 // In a class method, class messages to 'self' that return instancetype can
1362 // be typed as the current class. We can safely do this in ARC because self
1363 // can't be reassigned, and we do it unsafely outside of ARC because in
1364 // practice people never reassign self in class methods and there's some
1365 // virtue in not being aggressively pedantic.
1366 if (Receiver && Receiver->isObjCSelfExpr()) {
1367 assert(ReceiverType->isObjCClassType() && "expected a Class self");
1368 QualType T = Method->getSendResultType(ReceiverType);
1369 AttributedType::stripOuterNullability(T);
1370 if (T == Context.getObjCInstanceType()) {
1371 const ObjCMethodDecl *MD = cast<ObjCMethodDecl>(
1372 cast<ImplicitParamDecl>(
1373 cast<DeclRefExpr>(Receiver->IgnoreParenImpCasts())->getDecl())
1374 ->getDeclContext());
1375 assert(MD->isClassMethod() && "expected a class method");
1376 QualType NewResultType = Context.getObjCObjectPointerType(
1377 Context.getObjCInterfaceType(MD->getClassInterface()));
1378 if (auto Nullability = resultType->getNullability(Context))
1379 NewResultType = Context.getAttributedType(
1380 AttributedType::getNullabilityAttrKind(*Nullability),
1381 NewResultType, NewResultType);
1382 return NewResultType;
1383 }
1384 }
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001385 return resultType;
Alex Lorenzf50d1ac2018-12-20 22:11:11 +00001386 }
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001387
Akira Hatanaka66d405d2018-07-26 17:51:13 +00001388 // There is nothing left to do if the result type cannot have a nullability
1389 // specifier.
1390 if (!resultType->canHaveNullability())
1391 return resultType;
1392
Douglas Gregor813a0662015-06-19 18:14:38 +00001393 // Map the nullability of the result into a table index.
1394 unsigned receiverNullabilityIdx = 0;
1395 if (auto nullability = ReceiverType->getNullability(Context))
1396 receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1397
1398 unsigned resultNullabilityIdx = 0;
1399 if (auto nullability = resultType->getNullability(Context))
1400 resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1401
1402 // The table of nullability mappings, indexed by the receiver's nullability
1403 // and then the result type's nullability.
1404 static const uint8_t None = 0;
1405 static const uint8_t NonNull = 1;
1406 static const uint8_t Nullable = 2;
1407 static const uint8_t Unspecified = 3;
1408 static const uint8_t nullabilityMap[4][4] = {
1409 // None NonNull Nullable Unspecified
1410 /* None */ { None, None, Nullable, None },
1411 /* NonNull */ { None, NonNull, Nullable, Unspecified },
1412 /* Nullable */ { Nullable, Nullable, Nullable, Nullable },
1413 /* Unspecified */ { None, Unspecified, Nullable, Unspecified }
1414 };
1415
1416 unsigned newResultNullabilityIdx
1417 = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
1418 if (newResultNullabilityIdx == resultNullabilityIdx)
1419 return resultType;
1420
1421 // Strip off the existing nullability. This removes as little type sugar as
1422 // possible.
1423 do {
1424 if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
1425 resultType = attributed->getModifiedType();
1426 } else {
1427 resultType = resultType.getDesugaredType(Context);
1428 }
1429 } while (resultType->getNullability(Context));
1430
1431 // Add nullability back if needed.
1432 if (newResultNullabilityIdx > 0) {
1433 auto newNullability
1434 = static_cast<NullabilityKind>(newResultNullabilityIdx-1);
1435 return Context.getAttributedType(
1436 AttributedType::getNullabilityAttrKind(newNullability),
1437 resultType, resultType);
1438 }
1439
1440 return resultType;
Douglas Gregor33823722011-06-11 01:09:30 +00001441}
John McCall5f2d5562011-02-03 09:00:02 +00001442
John McCall5ec7e7d2013-03-19 07:04:25 +00001443/// Look for an ObjC method whose result type exactly matches the given type.
1444static const ObjCMethodDecl *
1445findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1446 QualType instancetype) {
Alp Toker314cc812014-01-25 16:55:45 +00001447 if (MD->getReturnType() == instancetype)
1448 return MD;
John McCall5ec7e7d2013-03-19 07:04:25 +00001449
1450 // For these purposes, a method in an @implementation overrides a
1451 // declaration in the @interface.
1452 if (const ObjCImplDecl *impl =
1453 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1454 const ObjCContainerDecl *iface;
Fangrui Song6907ce22018-07-30 19:24:48 +00001455 if (const ObjCCategoryImplDecl *catImpl =
John McCall5ec7e7d2013-03-19 07:04:25 +00001456 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1457 iface = catImpl->getCategoryDecl();
1458 } else {
1459 iface = impl->getClassInterface();
1460 }
1461
Fangrui Song6907ce22018-07-30 19:24:48 +00001462 const ObjCMethodDecl *ifaceMD =
John McCall5ec7e7d2013-03-19 07:04:25 +00001463 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1464 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1465 }
1466
1467 SmallVector<const ObjCMethodDecl *, 4> overrides;
1468 MD->getOverriddenMethods(overrides);
1469 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1470 if (const ObjCMethodDecl *result =
1471 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1472 return result;
1473 }
1474
Craig Topperc3ec1492014-05-26 06:22:03 +00001475 return nullptr;
John McCall5ec7e7d2013-03-19 07:04:25 +00001476}
1477
1478void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1479 // Only complain if we're in an ObjC method and the required return
1480 // type doesn't match the method's declared return type.
1481 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1482 if (!MD || !MD->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +00001483 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
John McCall5ec7e7d2013-03-19 07:04:25 +00001484 return;
1485
1486 // Look for a method overridden by this method which explicitly uses
1487 // 'instancetype'.
1488 if (const ObjCMethodDecl *overridden =
1489 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +00001490 SourceRange range = overridden->getReturnTypeSourceRange();
1491 SourceLocation loc = range.getBegin();
John McCall5ec7e7d2013-03-19 07:04:25 +00001492 if (loc.isInvalid())
1493 loc = overridden->getLocation();
1494 Diag(loc, diag::note_related_result_type_explicit)
1495 << /*current method*/ 1 << range;
1496 return;
1497 }
1498
1499 // Otherwise, if we have an interesting method family, note that.
1500 // This should always trigger if the above didn't.
1501 if (ObjCMethodFamily family = MD->getMethodFamily())
1502 Diag(MD->getLocation(), diag::note_related_result_type_family)
1503 << /*current method*/ 1
1504 << family;
1505}
1506
Douglas Gregor33823722011-06-11 01:09:30 +00001507void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1508 E = E->IgnoreParenImpCasts();
1509 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1510 if (!MsgSend)
1511 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001512
Douglas Gregor33823722011-06-11 01:09:30 +00001513 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1514 if (!Method)
1515 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001516
Douglas Gregor33823722011-06-11 01:09:30 +00001517 if (!Method->hasRelatedResultType())
1518 return;
Alp Toker314cc812014-01-25 16:55:45 +00001519
1520 if (Context.hasSameUnqualifiedType(
1521 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
Douglas Gregor33823722011-06-11 01:09:30 +00001522 return;
Alp Toker314cc812014-01-25 16:55:45 +00001523
1524 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
Douglas Gregorbab8a962011-09-08 01:46:34 +00001525 Context.getObjCInstanceType()))
1526 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001527
Douglas Gregor33823722011-06-11 01:09:30 +00001528 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1529 << Method->isInstanceMethod() << Method->getSelector()
1530 << MsgSend->getType();
1531}
1532
Alex Lorenzf50d1ac2018-12-20 22:11:11 +00001533bool Sema::CheckMessageArgumentTypes(
1534 const Expr *Receiver, QualType ReceiverType, MultiExprArg Args,
1535 Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method,
1536 bool isClassMessage, bool isSuperMessage, SourceLocation lbrac,
1537 SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType,
1538 ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001539 SourceLocation SelLoc;
1540 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1541 SelLoc = SelectorLocs.front();
1542 else
1543 SelLoc = lbrac;
1544
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001545 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001546 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001547 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001548 if (Args[i]->isTypeDependent())
1549 continue;
1550
John McCallcc5788c2013-03-04 07:34:02 +00001551 ExprResult result;
1552 if (getLangOpts().DebuggerSupport) {
1553 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001554 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001555 } else {
1556 result = DefaultArgumentPromotion(Args[i]);
1557 }
1558 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001559 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001560 Args[i] = result.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001561 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001562
John McCall31168b02011-06-15 23:02:42 +00001563 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001564 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001565 DiagID = diag::err_arc_method_not_found;
1566 else
1567 DiagID = isClassMessage ? diag::warn_class_method_not_found
1568 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001569 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001570 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahanian06499232013-06-18 17:10:58 +00001571 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001572 if (getLangOpts().ObjCAutoRefCount)
Richard Smithf8812672016-12-02 22:38:31 +00001573 DiagID = diag::err_method_not_found_with_typo;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001574 else
1575 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1576 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001577 Selector MatchedSel = OMD->getSelector();
1578 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian5ab87502014-08-12 22:16:41 +00001579 if (MatchedSel.isUnarySelector())
1580 Diag(SelLoc, DiagID)
1581 << Sel<< isClassMessage << MatchedSel
1582 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1583 else
1584 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001585 }
1586 else
1587 Diag(SelLoc, DiagID)
Fangrui Song6907ce22018-07-30 19:24:48 +00001588 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001589 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001590 // Find the class to which we are sending this message.
1591 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001592 if (ObjCInterfaceDecl *ThisClass =
1593 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
1594 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1595 if (!RecRange.isInvalid())
1596 if (ThisClass->lookupClassMethod(Sel))
1597 Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
1598 << FixItHint::CreateReplacement(RecRange,
1599 ThisClass->getNameAsString());
1600 }
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001601 }
1602 }
John McCall3f4138c2011-07-13 17:56:40 +00001603
1604 // In debuggers, we want to use __unknown_anytype for these
1605 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001606 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001607 ReturnType = Context.UnknownAnyTy;
1608 } else {
1609 ReturnType = Context.getObjCIdType();
1610 }
John McCall7decc9e2010-11-18 06:31:45 +00001611 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001612 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001613 }
Mike Stump11289f42009-09-09 15:08:12 +00001614
Alex Lorenzf50d1ac2018-12-20 22:11:11 +00001615 ReturnType = getMessageSendResultType(Receiver, ReceiverType, Method,
1616 isClassMessage, isSuperMessage);
Alp Toker314cc812014-01-25 16:55:45 +00001617 VK = Expr::getValueKindForType(Method->getReturnType());
Mike Stump11289f42009-09-09 15:08:12 +00001618
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001619 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001620 // Method might have more arguments than selector indicates. This is due
1621 // to addition of c-style arguments in method.
1622 if (Method->param_size() > Sel.getNumArgs())
1623 NumNamedArgs = Method->param_size();
1624 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001625 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001626 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001627 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001628 return false;
1629 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001630
Douglas Gregore83b9562015-07-07 03:57:53 +00001631 // Compute the set of type arguments to be substituted into each parameter
1632 // type.
1633 Optional<ArrayRef<QualType>> typeArgs
1634 = ReceiverType->getObjCSubstitutions(Method->getDeclContext());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001635 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001636 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001637 // We can't do any type-checking on a type-dependent argument.
1638 if (Args[i]->isTypeDependent())
1639 continue;
1640
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001641 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001642
Alp Toker03376dc2014-07-07 09:02:20 +00001643 ParmVarDecl *param = Method->parameters()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001644 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001645
Akira Hatanaka627586b2018-03-02 01:53:15 +00001646 if (param->hasAttr<NoEscapeAttr>())
1647 if (auto *BE = dyn_cast<BlockExpr>(
1648 argExpr->IgnoreParenNoopCasts(Context)))
1649 BE->getBlockDecl()->setDoesNotEscape();
1650
John McCall4124c492011-10-17 18:40:02 +00001651 // Strip the unbridged-cast placeholder expression off unless it's
1652 // a consumed argument.
1653 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1654 !param->hasAttr<CFConsumedAttr>())
1655 argExpr = stripARCUnbridgedCast(argExpr);
1656
John McCallea0a39e2012-11-14 00:49:39 +00001657 // If the parameter is __unknown_anytype, infer its type
1658 // from the argument.
1659 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001660 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001661 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001662 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001663 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001664 } else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001665 Args[i] = argE.get();
John McCallea0a39e2012-11-14 00:49:39 +00001666
John McCallcc5788c2013-03-04 07:34:02 +00001667 // Update the parameter type in-place.
1668 param->setType(paramType);
1669 }
1670 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001671 }
1672
Douglas Gregore83b9562015-07-07 03:57:53 +00001673 QualType origParamType = param->getType();
1674 QualType paramType = param->getType();
1675 if (typeArgs)
1676 paramType = paramType.substObjCTypeArgs(
1677 Context,
1678 *typeArgs,
1679 ObjCSubstitutionContext::Parameter);
1680
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001681 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
Douglas Gregore83b9562015-07-07 03:57:53 +00001682 paramType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001683 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001684 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001685
Douglas Gregore83b9562015-07-07 03:57:53 +00001686 InitializedEntity Entity
1687 = InitializedEntity::InitializeParameter(Context, param, paramType);
Fariborz Jahaniana1db7df2014-07-31 17:39:50 +00001688 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001689 if (ArgE.isInvalid())
1690 IsError = true;
Douglas Gregore83b9562015-07-07 03:57:53 +00001691 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001692 Args[i] = ArgE.getAs<Expr>();
Douglas Gregore83b9562015-07-07 03:57:53 +00001693
1694 // If we are type-erasing a block to a block-compatible
1695 // Objective-C pointer type, we may need to extend the lifetime
1696 // of the block object.
1697 if (typeArgs && Args[i]->isRValue() && paramType->isBlockPointerType() &&
Bob Wilson7e9fd562015-10-02 01:05:29 +00001698 Args[i]->getType()->isBlockPointerType() &&
1699 origParamType->isObjCObjectPointerType()) {
Douglas Gregore83b9562015-07-07 03:57:53 +00001700 ExprResult arg = Args[i];
1701 maybeExtendBlockObject(arg);
1702 Args[i] = arg.get();
1703 }
1704 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001705 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001706
1707 // Promote additional arguments to variadic methods.
1708 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001709 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001710 if (Args[i]->isTypeDependent())
1711 continue;
1712
Jordy Roseaca01f92012-05-12 17:32:52 +00001713 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
Craig Topperc3ec1492014-05-26 06:22:03 +00001714 nullptr);
John Wiegley01296292011-04-08 18:41:53 +00001715 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001716 Args[i] = Arg.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001717 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001718 } else {
1719 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001720 if (Args.size() != NumNamedArgs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001721 Diag(Args[NumNamedArgs]->getBeginLoc(),
Chris Lattner3b054132008-11-19 05:08:23 +00001722 diag::err_typecheck_call_too_many_args)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001723 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
1724 << Method->getSourceRange()
1725 << SourceRange(Args[NumNamedArgs]->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001726 Args.back()->getEndLoc());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001727 }
1728 }
1729
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001730 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001731
1732 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001733 IsError |= CheckObjCMethodCall(
Craig Topper8c2a2a02014-08-30 16:55:39 +00001734 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001735
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001736 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001737}
1738
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001739bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001740 // 'self' is objc 'self' in an objc method only.
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001741 ObjCMethodDecl *Method =
1742 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1743 return isSelfExpr(RExpr, Method);
1744}
1745
1746bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
John McCallfe96e0b2011-11-06 09:01:30 +00001747 if (!method) return false;
1748
John McCall31168b02011-06-15 23:02:42 +00001749 receiver = receiver->IgnoreParenLValueCasts();
1750 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001751 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001752 return true;
1753 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001754}
1755
John McCall526ab472011-10-25 17:37:35 +00001756/// LookupMethodInType - Look up a method in an ObjCObjectType.
1757ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1758 bool isInstance) {
1759 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1760 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1761 // Look it up in the main interface (and categories, etc.)
1762 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1763 return method;
1764
1765 // Okay, look for "private" methods declared in any
1766 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001767 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1768 return method;
John McCall526ab472011-10-25 17:37:35 +00001769 }
1770
1771 // Check qualifiers.
Aaron Ballman1683f7b2014-03-17 15:55:30 +00001772 for (const auto *I : objType->quals())
1773 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
John McCall526ab472011-10-25 17:37:35 +00001774 return method;
1775
Craig Topperc3ec1492014-05-26 06:22:03 +00001776 return nullptr;
John McCall526ab472011-10-25 17:37:35 +00001777}
1778
Fangrui Song6907ce22018-07-30 19:24:48 +00001779/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001780/// list of a qualified objective pointer type.
1781ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1782 const ObjCObjectPointerType *OPT,
1783 bool Instance)
1784{
Craig Topperc3ec1492014-05-26 06:22:03 +00001785 ObjCMethodDecl *MD = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +00001786 for (const auto *PROTO : OPT->quals()) {
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001787 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1788 return MD;
1789 }
1790 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001791 return nullptr;
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001792}
1793
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001794/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1795/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001796ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001797HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001798 Expr *BaseExpr, SourceLocation OpLoc,
1799 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001800 SourceLocation MemberLoc,
1801 SourceLocation SuperLoc, QualType SuperType,
1802 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001803 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1804 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001805
Benjamin Kramer365082d2012-05-19 16:34:46 +00001806 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001807 Diag(MemberLoc, diag::err_invalid_property_name)
1808 << MemberName << QualType(OPT, 0);
1809 return ExprError();
1810 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001811
1812 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Fangrui Song6907ce22018-07-30 19:24:48 +00001813
Douglas Gregor4123a862011-11-14 22:10:01 +00001814 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1815 : BaseExpr->getSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +00001816 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001817 diag::err_property_not_found_forward_class,
1818 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001819 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +00001820
Manman Ren5b786402016-01-28 18:49:28 +00001821 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(
1822 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001823 // Check whether we can reference this property.
1824 if (DiagnoseUseOfDecl(PD, MemberLoc))
1825 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001826 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001827 return new (Context)
1828 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1829 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001830 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001831 return new (Context)
1832 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1833 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001834 }
1835 // Check protocols on qualified interfaces.
Aaron Ballman83731462014-03-17 16:14:00 +00001836 for (const auto *I : OPT->quals())
Manman Ren5b786402016-01-28 18:49:28 +00001837 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
1838 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001839 // Check whether we can reference this property.
1840 if (DiagnoseUseOfDecl(PD, MemberLoc))
1841 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001842
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001843 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001844 return new (Context) ObjCPropertyRefExpr(
1845 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1846 SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001847 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001848 return new (Context)
1849 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1850 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001851 }
1852 // If that failed, look for an "implicit" property by seeing if the nullary
1853 // selector is implemented.
1854
1855 // FIXME: The logic for looking up nullary and unary selectors should be
1856 // shared with the code in ActOnInstanceMessage.
1857
1858 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1859 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fangrui Song6907ce22018-07-30 19:24:48 +00001860
Manman Ren2b2b1a92016-06-28 23:01:49 +00001861 // May be found in property's qualified list.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001862 if (!Getter)
1863 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001864
1865 // If this reference is in an @implementation, check for 'private' methods.
1866 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001867 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001868
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001869 if (Getter) {
1870 // Check if we can reference this property.
1871 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1872 return ExprError();
1873 }
1874 // If we found a getter then this may be a valid dot-reference, we
1875 // will look for the matching setter, in case it is needed.
1876 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001877 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1878 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001879 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fangrui Song6907ce22018-07-30 19:24:48 +00001880
Manman Ren2b2b1a92016-06-28 23:01:49 +00001881 // May be found in property's qualified list.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001882 if (!Setter)
1883 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00001884
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001885 if (!Setter) {
1886 // If this reference is in an @implementation, also check for 'private'
1887 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001888 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001889 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001890
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001891 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1892 return ExprError();
1893
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001894 // Special warning if member name used in a property-dot for a setter accessor
1895 // does not use a property with same name; e.g. obj.X = ... for a property with
1896 // name 'x'.
Manman Ren5b786402016-01-28 18:49:28 +00001897 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor() &&
1898 !IFace->FindPropertyDeclaration(
1899 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001900 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
1901 // Do not warn if user is using property-dot syntax to make call to
1902 // user named setter.
1903 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001904 Diag(MemberLoc,
1905 diag::warn_property_access_suggest)
1906 << MemberName << QualType(OPT, 0) << PDecl->getName()
1907 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001908 }
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001909 }
1910
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001911 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001912 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001913 return new (Context)
1914 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1915 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001916 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001917 return new (Context)
1918 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1919 OK_ObjCProperty, MemberLoc, BaseExpr);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001920
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001921 }
1922
1923 // Attempt to correct for typos in property names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001924 if (TypoCorrection Corrected =
1925 CorrectTypo(DeclarationNameInfo(MemberName, MemberLoc),
1926 LookupOrdinaryName, nullptr, nullptr,
1927 llvm::make_unique<DeclFilterCCC<ObjCPropertyDecl>>(),
1928 CTK_ErrorRecovery, IFace, false, OPT)) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001929 DeclarationName TypoResult = Corrected.getCorrection();
Manman Ren2b2b1a92016-06-28 23:01:49 +00001930 if (TypoResult.isIdentifier() &&
1931 TypoResult.getAsIdentifierInfo() == Member) {
1932 // There is no need to try the correction if it is the same.
1933 NamedDecl *ChosenDecl =
1934 Corrected.isKeyword() ? nullptr : Corrected.getFoundDecl();
1935 if (ChosenDecl && isa<ObjCPropertyDecl>(ChosenDecl))
1936 if (cast<ObjCPropertyDecl>(ChosenDecl)->isClassProperty()) {
1937 // This is a class property, we should not use the instance to
1938 // access it.
1939 Diag(MemberLoc, diag::err_class_property_found) << MemberName
1940 << OPT->getInterfaceDecl()->getName()
1941 << FixItHint::CreateReplacement(BaseExpr->getSourceRange(),
1942 OPT->getInterfaceDecl()->getName());
1943 return ExprError();
1944 }
1945 } else {
1946 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1947 << MemberName << QualType(OPT, 0));
1948 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1949 TypoResult, MemberLoc,
1950 SuperLoc, SuperType, Super);
1951 }
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001952 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001953 ObjCInterfaceDecl *ClassDeclared;
Fangrui Song6907ce22018-07-30 19:24:48 +00001954 if (ObjCIvarDecl *Ivar =
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001955 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1956 QualType T = Ivar->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001957 if (const ObjCObjectPointerType * OBJPT =
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001958 T->getAsObjCInterfacePointerType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001959 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001960 diag::err_property_not_as_forward_class,
1961 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001962 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001963 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001964 Diag(MemberLoc,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001965 diag::err_ivar_access_using_property_syntax_suggest)
1966 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1967 << FixItHint::CreateReplacement(OpLoc, "->");
1968 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001969 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001970
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001971 Diag(MemberLoc, diag::err_property_not_found)
1972 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001973 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001974 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001975 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001976 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001977}
1978
John McCalldadc5752010-08-24 06:29:42 +00001979ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001980ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1981 IdentifierInfo &propertyName,
1982 SourceLocation receiverNameLoc,
1983 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001984
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001985 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001986 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1987 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001988
Douglas Gregore83b9562015-07-07 03:57:53 +00001989 QualType SuperType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001990 if (!IFace) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001991 // If the "receiver" is 'super' in a method, handle it as an expression-like
1992 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001993 if (receiverNamePtr->isStr("super")) {
Eli Friedman24af8502012-02-03 22:47:37 +00001994 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Douglas Gregore83b9562015-07-07 03:57:53 +00001995 if (auto classDecl = CurMethod->getClassInterface()) {
1996 SuperType = QualType(classDecl->getSuperClassType(), 0);
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001997 if (CurMethod->isInstanceMethod()) {
Douglas Gregore83b9562015-07-07 03:57:53 +00001998 if (SuperType.isNull()) {
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001999 // The current class does not have a superclass.
Richard Smithf8812672016-12-02 22:38:31 +00002000 Diag(receiverNameLoc, diag::err_root_class_cannot_use_super)
Douglas Gregore83b9562015-07-07 03:57:53 +00002001 << CurMethod->getClassInterface()->getIdentifier();
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00002002 return ExprError();
2003 }
Douglas Gregore83b9562015-07-07 03:57:53 +00002004 QualType T = Context.getObjCObjectPointerType(SuperType);
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00002005
Douglas Gregore83b9562015-07-07 03:57:53 +00002006 return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(),
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00002007 /*BaseExpr*/nullptr,
2008 SourceLocation()/*OpLoc*/,
2009 &propertyName,
2010 propertyNameLoc,
2011 receiverNameLoc, T, true);
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00002012 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002013
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00002014 // Otherwise, if this is a class method, try dispatching to our
2015 // superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00002016 IFace = CurMethod->getClassInterface()->getSuperClass();
Chris Lattnera36ec422010-04-11 08:28:14 +00002017 }
Chris Lattnera36ec422010-04-11 08:28:14 +00002018 }
John McCall5f2d5562011-02-03 09:00:02 +00002019 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002020
2021 if (!IFace) {
Alp Tokerec543272013-12-24 09:48:30 +00002022 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
2023 << tok::l_paren;
Chris Lattnera36ec422010-04-11 08:28:14 +00002024 return ExprError();
2025 }
2026 }
2027
Saleem Abdulrasoolb3a2d042017-02-20 23:45:49 +00002028 Selector GetterSel;
2029 Selector SetterSel;
2030 if (auto PD = IFace->FindPropertyDeclaration(
2031 &propertyName, ObjCPropertyQueryKind::OBJC_PR_query_class)) {
2032 GetterSel = PD->getGetterName();
2033 SetterSel = PD->getSetterName();
2034 } else {
2035 GetterSel = PP.getSelectorTable().getNullarySelector(&propertyName);
2036 SetterSel = SelectorTable::constructSetterSelector(
2037 PP.getIdentifierTable(), PP.getSelectorTable(), &propertyName);
2038 }
2039
Chris Lattnera36ec422010-04-11 08:28:14 +00002040 // Search for a declared property first.
Saleem Abdulrasoolb3a2d042017-02-20 23:45:49 +00002041 ObjCMethodDecl *Getter = IFace->lookupClassMethod(GetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002042
2043 // If this reference is in an @implementation, check for 'private' methods.
2044 if (!Getter)
Saleem Abdulrasoolb3a2d042017-02-20 23:45:49 +00002045 Getter = IFace->lookupPrivateClassMethod(GetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002046
2047 if (Getter) {
2048 // FIXME: refactor/share with ActOnMemberReference().
2049 // Check if we can reference this property.
2050 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
2051 return ExprError();
2052 }
Mike Stump11289f42009-09-09 15:08:12 +00002053
Steve Naroff9527bbf2009-03-09 21:12:44 +00002054 // Look for the matching setter, in case it is needed.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002055 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002056 if (!Setter) {
2057 // If this reference is in an @implementation, also check for 'private'
2058 // methods.
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00002059 Setter = IFace->lookupPrivateClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002060 }
2061 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002062 if (!Setter)
2063 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002064
2065 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
2066 return ExprError();
2067
2068 if (Getter || Setter) {
Douglas Gregore83b9562015-07-07 03:57:53 +00002069 if (!SuperType.isNull())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002070 return new (Context)
2071 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2072 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
Douglas Gregore83b9562015-07-07 03:57:53 +00002073 SuperType);
Douglas Gregor33823722011-06-11 01:09:30 +00002074
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002075 return new (Context) ObjCPropertyRefExpr(
2076 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
2077 propertyNameLoc, receiverNameLoc, IFace);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002078 }
2079 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
2080 << &propertyName << Context.getObjCInterfaceType(IFace));
2081}
2082
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002083namespace {
2084
2085class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
2086 public:
2087 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
2088 // Determine whether "super" is acceptable in the current context.
2089 if (Method && Method->getClassInterface())
2090 WantObjCSuper = Method->getClassInterface()->getSuperClass();
2091 }
2092
Craig Toppere14c0f82014-03-12 04:55:44 +00002093 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002094 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
2095 candidate.isKeyword("super");
2096 }
2097};
2098
Eugene Zelenko1ced5092016-02-12 22:53:10 +00002099} // end anonymous namespace
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002100
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002101Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00002102 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002103 SourceLocation NameLoc,
2104 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00002105 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00002106 ParsedType &ReceiverType) {
David Blaikieefdccaa2016-01-15 23:43:34 +00002107 ReceiverType = nullptr;
Douglas Gregore5798dc2010-04-21 20:38:13 +00002108
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002109 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00002110 // messaging super. If the identifier is "super" and there is a
2111 // trailing dot, it's an instance message.
2112 if (IsSuper && S->isInObjcMethodScope())
2113 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Fangrui Song6907ce22018-07-30 19:24:48 +00002114
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002115 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
2116 LookupName(Result, S);
Fangrui Song6907ce22018-07-30 19:24:48 +00002117
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002118 switch (Result.getResultKind()) {
2119 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00002120 // Normal name lookup didn't find anything. If we're in an
2121 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00002122 // FIXME: This is a hack. Ivar lookup should be part of normal
2123 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00002124 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00002125 if (!Method->getClassInterface()) {
2126 // Fall back: let the parser try to parse it as an instance message.
2127 return ObjCInstanceMessage;
2128 }
2129
Douglas Gregorca7136b2010-04-19 20:09:36 +00002130 ObjCInterfaceDecl *ClassDeclared;
Fangrui Song6907ce22018-07-30 19:24:48 +00002131 if (Method->getClassInterface()->lookupInstanceVariable(Name,
Douglas Gregorca7136b2010-04-19 20:09:36 +00002132 ClassDeclared))
2133 return ObjCInstanceMessage;
2134 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002135
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002136 // Break out; we'll perform typo correction below.
2137 break;
2138
2139 case LookupResult::NotFoundInCurrentInstantiation:
2140 case LookupResult::FoundOverloaded:
2141 case LookupResult::FoundUnresolvedValue:
2142 case LookupResult::Ambiguous:
2143 Result.suppressDiagnostics();
2144 return ObjCInstanceMessage;
2145
2146 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00002147 // If the identifier is a class or not, and there is a trailing dot,
2148 // it's an instance message.
2149 if (HasTrailingDot)
2150 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002151 // We found something. If it's a type, then we have a class
2152 // message. Otherwise, it's an instance message.
2153 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00002154 QualType T;
2155 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
2156 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00002157 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00002158 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00002159 DiagnoseUseOfDecl(Type, NameLoc);
2160 }
2161 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00002162 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002163
Douglas Gregore5798dc2010-04-21 20:38:13 +00002164 // We have a class message, and T is the type we're
2165 // messaging. Build source-location information for it.
2166 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00002167 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00002168 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002169 }
2170 }
2171
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002172 if (TypoCorrection Corrected = CorrectTypo(
2173 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr,
2174 llvm::make_unique<ObjCInterfaceOrSuperCCC>(getCurMethodDecl()),
2175 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002176 if (Corrected.isKeyword()) {
2177 // If we've found the keyword "super" (the only keyword that would be
2178 // returned by CorrectTypo), this is a send to super.
Richard Smithf9b15102013-08-17 00:46:16 +00002179 diagnoseTypo(Corrected,
2180 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002181 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002182 } else if (ObjCInterfaceDecl *Class =
Richard Smithf9b15102013-08-17 00:46:16 +00002183 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002184 // If we found a declaration, correct when it refers to an Objective-C
2185 // class.
Richard Smithf9b15102013-08-17 00:46:16 +00002186 diagnoseTypo(Corrected,
2187 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002188 QualType T = Context.getObjCInterfaceType(Class);
2189 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2190 ReceiverType = CreateParsedType(T, TSInfo);
2191 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002192 }
2193 }
Richard Smithf9b15102013-08-17 00:46:16 +00002194
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002195 // Fall back: let the parser try to parse it as an instance message.
2196 return ObjCInstanceMessage;
2197}
Steve Naroff9527bbf2009-03-09 21:12:44 +00002198
Fangrui Song6907ce22018-07-30 19:24:48 +00002199ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002200 SourceLocation SuperLoc,
2201 Selector Sel,
2202 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002203 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002204 SourceLocation RBracLoc,
2205 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002206 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00002207 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00002208 if (!Method) {
2209 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
2210 return ExprError();
2211 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002212
Douglas Gregor4fdba132010-04-21 20:01:04 +00002213 ObjCInterfaceDecl *Class = Method->getClassInterface();
2214 if (!Class) {
Richard Smithf8812672016-12-02 22:38:31 +00002215 Diag(SuperLoc, diag::err_no_super_class_message)
Douglas Gregor4fdba132010-04-21 20:01:04 +00002216 << Method->getDeclName();
2217 return ExprError();
2218 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002219
Douglas Gregore83b9562015-07-07 03:57:53 +00002220 QualType SuperTy(Class->getSuperClassType(), 0);
2221 if (SuperTy.isNull()) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002222 // The current class does not have a superclass.
Richard Smithf8812672016-12-02 22:38:31 +00002223 Diag(SuperLoc, diag::err_root_class_cannot_use_super)
Ted Kremenek499897b2011-01-23 17:21:34 +00002224 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002225 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002226 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002227
Douglas Gregor4fdba132010-04-21 20:01:04 +00002228 // We are in a method whose class has a superclass, so 'super'
2229 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00002230 if (Method->getSelector() == Sel)
2231 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00002232
Jordan Rose2afd6612012-10-19 16:05:26 +00002233 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00002234 // Since we are in an instance method, this is an instance
2235 // message to the superclass instance.
Douglas Gregor4fdba132010-04-21 20:01:04 +00002236 SuperTy = Context.getObjCObjectPointerType(SuperTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00002237 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2238 Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002239 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002240 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002241
Douglas Gregor4fdba132010-04-21 20:01:04 +00002242 // Since we are in a class method, this is a class message to
2243 // the superclass.
Craig Topperc3ec1492014-05-26 06:22:03 +00002244 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
Douglas Gregore83b9562015-07-07 03:57:53 +00002245 SuperTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00002246 SuperLoc, Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002247 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002248}
2249
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002250ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2251 bool isSuperReceiver,
2252 SourceLocation Loc,
2253 Selector Sel,
2254 ObjCMethodDecl *Method,
2255 MultiExprArg Args) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002256 TypeSourceInfo *receiverTypeInfo = nullptr;
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002257 if (!ReceiverType.isNull())
2258 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2259
2260 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2261 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2262 Sel, Method, Loc, Loc, Loc, Args,
2263 /*isImplicit=*/true);
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002264}
2265
Ted Kremeneke65b0862012-03-06 20:05:56 +00002266static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2267 unsigned DiagID,
2268 bool (*refactor)(const ObjCMessageExpr *,
2269 const NSAPI &, edit::Commit &)) {
2270 SourceLocation MsgLoc = Msg->getExprLoc();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002271 if (S.Diags.isIgnored(DiagID, MsgLoc))
Ted Kremeneke65b0862012-03-06 20:05:56 +00002272 return;
2273
2274 SourceManager &SM = S.SourceMgr;
2275 edit::Commit ECommit(SM, S.LangOpts);
2276 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2277 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2278 << Msg->getSelector() << Msg->getSourceRange();
2279 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2280 if (!ECommit.isCommitable())
2281 return;
2282 for (edit::Commit::edit_iterator
2283 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2284 const edit::Commit::Edit &Edit = *I;
2285 switch (Edit.Kind) {
2286 case edit::Commit::Act_Insert:
2287 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2288 Edit.Text,
2289 Edit.BeforePrev));
2290 break;
2291 case edit::Commit::Act_InsertFromRange:
2292 Builder.AddFixItHint(
2293 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2294 Edit.getInsertFromRange(SM),
2295 Edit.BeforePrev));
2296 break;
2297 case edit::Commit::Act_Remove:
2298 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2299 break;
2300 }
2301 }
2302 }
2303}
2304
2305static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2306 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2307 edit::rewriteObjCRedundantCallWithLiteral);
2308}
2309
Alex Lorenz0e23c612017-03-06 15:58:34 +00002310static void checkFoundationAPI(Sema &S, SourceLocation Loc,
2311 const ObjCMethodDecl *Method,
2312 ArrayRef<Expr *> Args, QualType ReceiverType,
2313 bool IsClassObjectCall) {
2314 // Check if this is a performSelector method that uses a selector that returns
2315 // a record or a vector type.
Alex Lorenz5ffe4e12017-03-23 10:46:05 +00002316 if (Method->getSelector().getMethodFamily() != OMF_performSelector ||
2317 Args.empty())
Alex Lorenz0e23c612017-03-06 15:58:34 +00002318 return;
2319 const auto *SE = dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens());
2320 if (!SE)
2321 return;
2322 ObjCMethodDecl *ImpliedMethod;
2323 if (!IsClassObjectCall) {
2324 const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>();
2325 if (!OPT || !OPT->getInterfaceDecl())
2326 return;
2327 ImpliedMethod =
2328 OPT->getInterfaceDecl()->lookupInstanceMethod(SE->getSelector());
2329 if (!ImpliedMethod)
2330 ImpliedMethod =
2331 OPT->getInterfaceDecl()->lookupPrivateMethod(SE->getSelector());
2332 } else {
2333 const auto *IT = ReceiverType->getAs<ObjCInterfaceType>();
2334 if (!IT)
2335 return;
2336 ImpliedMethod = IT->getDecl()->lookupClassMethod(SE->getSelector());
2337 if (!ImpliedMethod)
2338 ImpliedMethod =
2339 IT->getDecl()->lookupPrivateClassMethod(SE->getSelector());
2340 }
2341 if (!ImpliedMethod)
2342 return;
2343 QualType Ret = ImpliedMethod->getReturnType();
2344 if (Ret->isRecordType() || Ret->isVectorType() || Ret->isExtVectorType()) {
2345 QualType Ret = ImpliedMethod->getReturnType();
2346 S.Diag(Loc, diag::warn_objc_unsafe_perform_selector)
2347 << Method->getSelector()
2348 << (!Ret->isRecordType()
2349 ? /*Vector*/ 2
2350 : Ret->isUnionType() ? /*Union*/ 1 : /*Struct*/ 0);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002351 S.Diag(ImpliedMethod->getBeginLoc(),
Alex Lorenz0e23c612017-03-06 15:58:34 +00002352 diag::note_objc_unsafe_perform_selector_method_declared_here)
2353 << ImpliedMethod->getSelector() << Ret;
2354 }
2355}
2356
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002357/// Diagnose use of %s directive in an NSString which is being passed
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002358/// as formatting string to formatting method.
2359static void
2360DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2361 ObjCMethodDecl *Method,
2362 Selector Sel,
2363 Expr **Args, unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002364 unsigned Idx = 0;
2365 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002366 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2367 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002368 Idx = 0;
2369 Format = true;
2370 }
2371 else if (Method) {
2372 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2373 if (S.GetFormatNSStringIdx(I, Idx)) {
2374 Format = true;
2375 break;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002376 }
2377 }
2378 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002379 if (!Format || NumArgs <= Idx)
2380 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002381
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002382 Expr *FormatExpr = Args[Idx];
2383 if (ObjCStringLiteral *OSL =
2384 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2385 StringLiteral *FormatString = OSL->getString();
2386 if (S.FormatStringHasSArg(FormatString)) {
2387 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2388 << "%s" << 0 << 0;
2389 if (Method)
2390 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2391 << Method->getDeclName();
2392 }
2393 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002394}
2395
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002396/// Build an Objective-C class message expression.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002397///
2398/// This routine takes care of both normal class messages and
2399/// class messages to the superclass.
2400///
2401/// \param ReceiverTypeInfo Type source information that describes the
2402/// receiver of this message. This may be NULL, in which case we are
2403/// sending to the superclass and \p SuperLoc must be a valid source
2404/// location.
2405
2406/// \param ReceiverType The type of the object receiving the
2407/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2408/// type as that refers to. For a superclass send, this is the type of
2409/// the superclass.
2410///
2411/// \param SuperLoc The location of the "super" keyword in a
2412/// superclass message.
2413///
2414/// \param Sel The selector to which the message is being sent.
2415///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002416/// \param Method The method that this class message is invoking, if
2417/// already known.
2418///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002419/// \param LBracLoc The location of the opening square bracket ']'.
2420///
James Dennettffad8b72012-06-22 08:10:18 +00002421/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002422///
James Dennettffad8b72012-06-22 08:10:18 +00002423/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002424ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002425 QualType ReceiverType,
2426 SourceLocation SuperLoc,
2427 Selector Sel,
2428 ObjCMethodDecl *Method,
Fangrui Song6907ce22018-07-30 19:24:48 +00002429 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002430 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002431 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002432 MultiExprArg ArgsIn,
2433 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002434 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002435 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002436 if (LBracLoc.isInvalid()) {
2437 Diag(Loc, diag::err_missing_open_square_message_send)
2438 << FixItHint::CreateInsertion(Loc, "[");
2439 LBracLoc = Loc;
2440 }
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002441 ArrayRef<SourceLocation> SelectorSlotLocs;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002442 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002443 SelectorSlotLocs = SelectorLocs;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002444 else
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002445 SelectorSlotLocs = Loc;
2446 SourceLocation SelLoc = SelectorSlotLocs.front();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002447
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002448 if (ReceiverType->isDependentType()) {
2449 // If the receiver type is dependent, we can't type-check anything
2450 // at this point. Build a dependent expression.
2451 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002452 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002453 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002454 return ObjCMessageExpr::Create(
2455 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2456 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2457 isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002458 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002459
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002460 // Find the class to which we are sending this message.
Craig Topperc3ec1492014-05-26 06:22:03 +00002461 ObjCInterfaceDecl *Class = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00002462 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2463 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002464 Diag(Loc, diag::err_invalid_receiver_class_message)
2465 << ReceiverType;
2466 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002467 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002468 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002469 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002470 if (!getLangOpts().CPlusPlus)
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002471 (void)DiagnoseUseOfDecl(Class, SelectorSlotLocs);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002472 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002473 if (!Method) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002474 SourceRange TypeRange
Douglas Gregor4123a862011-11-14 22:10:01 +00002475 = SuperLoc.isValid()? SourceRange(SuperLoc)
2476 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002477 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002478 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002479 ? diag::err_arc_receiver_forward_class
2480 : diag::warn_receiver_forward_class),
2481 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002482 // A forward class used in messaging is treated as a 'Class'
Fangrui Song6907ce22018-07-30 19:24:48 +00002483 Method = LookupFactoryMethodInGlobalPool(Sel,
Douglas Gregorb5186b12010-04-22 17:01:48 +00002484 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002485 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002486 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2487 << Method->getDeclName();
2488 }
2489 if (!Method)
2490 Method = Class->lookupClassMethod(Sel);
2491
2492 // If we have an implementation in scope, check "private" methods.
2493 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002494 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002495
Erik Pilkington42578572018-09-10 22:20:09 +00002496 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs,
2497 nullptr, false, false, Class))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002498 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002499 }
Mike Stump11289f42009-09-09 15:08:12 +00002500
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002501 // Check the argument types and determine the result type.
2502 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002503 ExprValueKind VK = VK_RValue;
2504
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002505 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002506 Expr **Args = ArgsIn.data();
Alex Lorenzf50d1ac2018-12-20 22:11:11 +00002507 if (CheckMessageArgumentTypes(/*Receiver=*/nullptr, ReceiverType,
2508 MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
2509 Method, true, SuperLoc.isValid(), LBracLoc,
2510 RBracLoc, SourceRange(), ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002511 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002512
Alp Toker314cc812014-01-25 16:55:45 +00002513 if (Method && !Method->getReturnType()->isVoidType() &&
2514 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002515 diag::err_illegal_message_expr_incomplete_type))
2516 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +00002517
Fariborz Jahaniane8b45502014-08-22 19:52:49 +00002518 // Warn about explicit call of +initialize on its own class. But not on 'super'.
Fariborz Jahanian42292282014-08-25 21:27:38 +00002519 if (Method && Method->getMethodFamily() == OMF_initialize) {
2520 if (!SuperLoc.isValid()) {
2521 const ObjCInterfaceDecl *ID =
2522 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2523 if (ID == Class) {
2524 Diag(Loc, diag::warn_direct_initialize_call);
2525 Diag(Method->getLocation(), diag::note_method_declared_at)
2526 << Method->getDeclName();
2527 }
2528 }
2529 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2530 // [super initialize] is allowed only within an +initialize implementation
2531 if (CurMeth->getMethodFamily() != OMF_initialize) {
2532 Diag(Loc, diag::warn_direct_super_initialize_call);
2533 Diag(Method->getLocation(), diag::note_method_declared_at)
2534 << Method->getDeclName();
2535 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2536 << CurMeth->getDeclName();
2537 }
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002538 }
2539 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002540
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002541 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
Fangrui Song6907ce22018-07-30 19:24:48 +00002542
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002543 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002544 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002545 if (SuperLoc.isValid())
Fangrui Song6907ce22018-07-30 19:24:48 +00002546 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2547 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002548 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002549 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002550 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002551 else {
Fangrui Song6907ce22018-07-30 19:24:48 +00002552 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002553 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002554 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002555 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002556 if (!isImplicit)
2557 checkCocoaAPI(*this, Result);
2558 }
Alex Lorenz0e23c612017-03-06 15:58:34 +00002559 if (Method)
2560 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
2561 ReceiverType, /*IsClassObjectCall=*/true);
Douglas Gregoraae38d62010-05-22 05:17:18 +00002562 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002563}
2564
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002565// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002566// ArgExprs is optional - if it is present, the number of expressions
2567// is obtained from Sel.getNumArgs().
Fangrui Song6907ce22018-07-30 19:24:48 +00002568ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002569 ParsedType Receiver,
2570 Selector Sel,
2571 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002572 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002573 SourceLocation RBracLoc,
2574 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002575 TypeSourceInfo *ReceiverTypeInfo;
2576 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2577 if (ReceiverType.isNull())
2578 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002579
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002580 if (!ReceiverTypeInfo)
2581 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2582
Fangrui Song6907ce22018-07-30 19:24:48 +00002583 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002584 /*SuperLoc=*/SourceLocation(), Sel,
2585 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2586 Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002587}
2588
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002589ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2590 QualType ReceiverType,
2591 SourceLocation Loc,
2592 Selector Sel,
2593 ObjCMethodDecl *Method,
2594 MultiExprArg Args) {
2595 return BuildInstanceMessage(Receiver, ReceiverType,
2596 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2597 Sel, Method, Loc, Loc, Loc, Args,
2598 /*isImplicit=*/true);
2599}
2600
Alex Lorenz5e895cf2017-03-15 17:16:41 +00002601static bool isMethodDeclaredInRootProtocol(Sema &S, const ObjCMethodDecl *M) {
2602 if (!S.NSAPIObj)
2603 return false;
2604 const auto *Protocol = dyn_cast<ObjCProtocolDecl>(M->getDeclContext());
2605 if (!Protocol)
2606 return false;
2607 const IdentifierInfo *II = S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
2608 if (const auto *RootClass = dyn_cast_or_null<ObjCInterfaceDecl>(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002609 S.LookupSingleName(S.TUScope, II, Protocol->getBeginLoc(),
Alex Lorenz5e895cf2017-03-15 17:16:41 +00002610 Sema::LookupOrdinaryName))) {
2611 for (const ObjCProtocolDecl *P : RootClass->all_referenced_protocols()) {
2612 if (P->getCanonicalDecl() == Protocol->getCanonicalDecl())
2613 return true;
2614 }
2615 }
2616 return false;
2617}
2618
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002619/// Build an Objective-C instance message expression.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002620///
2621/// This routine takes care of both normal instance messages and
2622/// instance messages to the superclass instance.
2623///
2624/// \param Receiver The expression that computes the object that will
2625/// receive this message. This may be empty, in which case we are
2626/// sending to the superclass instance and \p SuperLoc must be a valid
2627/// source location.
2628///
2629/// \param ReceiverType The (static) type of the object receiving the
2630/// message. When a \p Receiver expression is provided, this is the
2631/// same type as that expression. For a superclass instance send, this
2632/// is a pointer to the type of the superclass.
2633///
2634/// \param SuperLoc The location of the "super" keyword in a
2635/// superclass instance message.
2636///
2637/// \param Sel The selector to which the message is being sent.
2638///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002639/// \param Method The method that this instance message is invoking, if
2640/// already known.
2641///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002642/// \param LBracLoc The location of the opening square bracket ']'.
2643///
James Dennettffad8b72012-06-22 08:10:18 +00002644/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002645///
James Dennettffad8b72012-06-22 08:10:18 +00002646/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002647ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002648 QualType ReceiverType,
2649 SourceLocation SuperLoc,
2650 Selector Sel,
2651 ObjCMethodDecl *Method,
Fangrui Song6907ce22018-07-30 19:24:48 +00002652 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002653 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002654 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002655 MultiExprArg ArgsIn,
2656 bool isImplicit) {
Chandler Carruth3d402842016-11-04 06:11:54 +00002657 assert((Receiver || SuperLoc.isValid()) && "If the Receiver is null, the "
2658 "SuperLoc must be valid so we can "
2659 "use it instead.");
2660
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002661 // The location of the receiver.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002662 SourceLocation Loc = SuperLoc.isValid() ? SuperLoc : Receiver->getBeginLoc();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002663 SourceRange RecRange =
2664 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002665 ArrayRef<SourceLocation> SelectorSlotLocs;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002666 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002667 SelectorSlotLocs = SelectorLocs;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002668 else
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002669 SelectorSlotLocs = Loc;
2670 SourceLocation SelLoc = SelectorSlotLocs.front();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002671
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002672 if (LBracLoc.isInvalid()) {
2673 Diag(Loc, diag::err_missing_open_square_message_send)
2674 << FixItHint::CreateInsertion(Loc, "[");
2675 LBracLoc = Loc;
2676 }
2677
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002678 // If we have a receiver expression, perform appropriate promotions
2679 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002680 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002681 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002682 ExprResult Result;
2683 if (Receiver->getType() == Context.UnknownAnyTy)
2684 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2685 else
2686 Result = CheckPlaceholderExpr(Receiver);
2687 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002688 Receiver = Result.get();
John McCall4124c492011-10-17 18:40:02 +00002689 }
2690
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002691 if (Receiver->isTypeDependent()) {
2692 // If the receiver is type-dependent, we can't type-check anything
2693 // at this point. Build a dependent expression.
2694 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002695 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002696 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002697 return ObjCMessageExpr::Create(
2698 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2699 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2700 RBracLoc, isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002701 }
2702
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002703 // If necessary, apply function/array conversion to the receiver.
2704 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002705 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2706 if (Result.isInvalid())
2707 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002708 Receiver = Result.get();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002709 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002710
2711 // If the receiver is an ObjC pointer, a block pointer, or an
2712 // __attribute__((NSObject)) pointer, we don't need to do any
2713 // special conversion in order to look up a receiver.
2714 if (ReceiverType->isObjCRetainableType()) {
2715 // do nothing
2716 } else if (!getLangOpts().ObjCAutoRefCount &&
2717 !Context.getObjCIdType().isNull() &&
Fangrui Song6907ce22018-07-30 19:24:48 +00002718 (ReceiverType->isPointerType() ||
John McCall80c93a02013-03-01 09:20:14 +00002719 ReceiverType->isIntegerType())) {
2720 // Implicitly convert integers and pointers to 'id' but emit a warning.
2721 // But not in ARC.
2722 Diag(Loc, diag::warn_bad_receiver_type)
Fangrui Song6907ce22018-07-30 19:24:48 +00002723 << ReceiverType
John McCall80c93a02013-03-01 09:20:14 +00002724 << Receiver->getSourceRange();
2725 if (ReceiverType->isPointerType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002726 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002727 CK_CPointerToObjCPointerCast).get();
John McCall80c93a02013-03-01 09:20:14 +00002728 } else {
2729 // TODO: specialized warning on null receivers?
2730 bool IsNull = Receiver->isNullPointerConstant(Context,
2731 Expr::NPC_ValueDependentIsNull);
2732 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2733 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002734 Kind).get();
John McCall80c93a02013-03-01 09:20:14 +00002735 }
2736 ReceiverType = Receiver->getType();
2737 } else if (getLangOpts().CPlusPlus) {
Douglas Gregor4b60a152013-11-07 22:34:54 +00002738 // The receiver must be a complete type.
2739 if (RequireCompleteType(Loc, Receiver->getType(),
2740 diag::err_incomplete_receiver_type))
2741 return ExprError();
2742
John McCall80c93a02013-03-01 09:20:14 +00002743 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2744 if (result.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002745 Receiver = result.get();
John McCall80c93a02013-03-01 09:20:14 +00002746 ReceiverType = Receiver->getType();
2747 }
2748 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002749 }
2750
Alex Lorenzd9f12842017-08-25 16:12:17 +00002751 if (ReceiverType->isObjCIdType() && !isImplicit)
2752 Diag(Receiver->getExprLoc(), diag::warn_messaging_unqualified_id);
2753
John McCall80c93a02013-03-01 09:20:14 +00002754 // There's a somewhat weird interaction here where we assume that we
2755 // won't actually have a method unless we also don't need to do some
2756 // of the more detailed type-checking on the receiver.
2757
Douglas Gregorb5186b12010-04-22 17:01:48 +00002758 if (!Method) {
Douglas Gregorab209d82015-07-07 03:58:42 +00002759 // Handle messages to id and __kindof types (where we use the
2760 // global method pool).
Douglas Gregorab209d82015-07-07 03:58:42 +00002761 const ObjCObjectType *typeBound = nullptr;
2762 bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
2763 typeBound);
2764 if (receiverIsIdLike || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002765 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
Manman Rend2a3cd72016-04-07 19:30:20 +00002766 SmallVector<ObjCMethodDecl*, 4> Methods;
Manman Ren7ed4f982016-04-07 19:32:24 +00002767 // If we have a type bound, further filter the methods.
Manman Rend2a3cd72016-04-07 19:30:20 +00002768 CollectMultipleMethodsInGlobalPool(Sel, Methods, true/*InstanceFirst*/,
Manman Ren7ed4f982016-04-07 19:32:24 +00002769 true/*CheckTheOther*/, typeBound);
Manman Rend2a3cd72016-04-07 19:30:20 +00002770 if (!Methods.empty()) {
George Burgess IV52d07de2016-09-01 01:26:58 +00002771 // We choose the first method as the initial candidate, then try to
Manman Rend2a3cd72016-04-07 19:30:20 +00002772 // select a better one.
2773 Method = Methods[0];
2774
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002775 if (ObjCMethodDecl *BestMethod =
Manman Rend2a3cd72016-04-07 19:30:20 +00002776 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(), Methods))
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002777 Method = BestMethod;
Manman Rend2a3cd72016-04-07 19:30:20 +00002778
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002779 if (!AreMultipleMethodsInGlobalPool(Sel, Method,
2780 SourceRange(LBracLoc, RBracLoc),
Manman Rend2a3cd72016-04-07 19:30:20 +00002781 receiverIsIdLike, Methods))
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002782 DiagnoseUseOfDecl(Method, SelectorSlotLocs);
Fariborz Jahanian05e77f82014-11-07 23:51:15 +00002783 }
Douglas Gregorab209d82015-07-07 03:58:42 +00002784 } else if (ReceiverType->isObjCClassOrClassKindOfType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002785 ReceiverType->isObjCQualifiedClassType()) {
2786 // Handle messages to Class.
Nico Weber2e0c8f72014-12-27 03:58:08 +00002787 // We allow sending a message to a qualified Class ("Class<foo>"), which
2788 // is ok as long as one of the protocols implements the selector (if not,
2789 // warn).
Douglas Gregorab209d82015-07-07 03:58:42 +00002790 if (!ReceiverType->isObjCClassOrClassKindOfType()) {
2791 const ObjCObjectPointerType *QClassTy
2792 = ReceiverType->getAsObjCQualifiedClassType();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002793 // Search protocols for class methods.
2794 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2795 if (!Method) {
2796 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2797 // warn if instance method found for a Class message.
Alex Lorenz5e895cf2017-03-15 17:16:41 +00002798 if (Method && !isMethodDeclaredInRootProtocol(*this, Method)) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002799 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002800 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002801 Diag(Method->getLocation(), diag::note_method_declared_at)
2802 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002803 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002804 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002805 } else {
2806 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2807 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
Erik Pilkington42578572018-09-10 22:20:09 +00002808 // FIXME: Is this correct? Why are we assuming that a message to
2809 // Class will call a method in the current interface?
2810
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002811 // First check the public methods in the class interface.
2812 Method = ClassDecl->lookupClassMethod(Sel);
2813
2814 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002815 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Erik Pilkington42578572018-09-10 22:20:09 +00002816
2817 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs, nullptr,
2818 false, false, ClassDecl))
2819 return ExprError();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002820 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002821 }
2822 if (!Method) {
2823 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002824 if (!Receiver || !isSelfExpr(Receiver)) {
Manman Rend2a3cd72016-04-07 19:30:20 +00002825 // If no class (factory) method was found, check if an _instance_
2826 // method of the same name exists in the root class only.
2827 SmallVector<ObjCMethodDecl*, 4> Methods;
2828 CollectMultipleMethodsInGlobalPool(Sel, Methods,
2829 false/*InstanceFirst*/,
2830 true/*CheckTheOther*/);
2831 if (!Methods.empty()) {
George Burgess IV52d07de2016-09-01 01:26:58 +00002832 // We choose the first method as the initial candidate, then try
Manman Rend2a3cd72016-04-07 19:30:20 +00002833 // to select a better one.
2834 Method = Methods[0];
2835
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002836 // If we find an instance method, emit warning.
Manman Rend2a3cd72016-04-07 19:30:20 +00002837 if (Method->isInstanceMethod()) {
2838 if (const ObjCInterfaceDecl *ID =
2839 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2840 if (ID->getSuperClass())
2841 Diag(SelLoc, diag::warn_root_inst_method_not_found)
2842 << Sel << SourceRange(LBracLoc, RBracLoc);
2843 }
2844 }
2845
2846 if (ObjCMethodDecl *BestMethod =
2847 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2848 Methods))
2849 Method = BestMethod;
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002850 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002851 }
2852 }
2853 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002854 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002855 ObjCInterfaceDecl *ClassDecl = nullptr;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002856
2857 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2858 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002859 // And as long as message is not deprecated/unavailable (warn if it is).
Fangrui Song6907ce22018-07-30 19:24:48 +00002860 if (const ObjCObjectPointerType *QIdTy
Douglas Gregorb5186b12010-04-22 17:01:48 +00002861 = ReceiverType->getAsObjCQualifiedIdType()) {
2862 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002863 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2864 if (!Method)
2865 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002866 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002867 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002868 } else if (const ObjCObjectPointerType *OCIType
2869 = ReceiverType->getAsObjCInterfacePointerType()) {
2870 // We allow sending a message to a pointer to an interface (an object).
2871 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002872
Douglas Gregor4123a862011-11-14 22:10:01 +00002873 // Try to complete the type. Under ARC, this is a hard error from which
2874 // we don't try to recover.
Richard Smithdb0ac552015-12-18 22:40:25 +00002875 // FIXME: In the non-ARC case, this will still be a hard error if the
2876 // definition is found in a module that's not visible.
Craig Topperc3ec1492014-05-26 06:22:03 +00002877 const ObjCInterfaceDecl *forwardClass = nullptr;
Douglas Gregor4123a862011-11-14 22:10:01 +00002878 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002879 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002880 ? diag::err_arc_receiver_forward_instance
2881 : diag::warn_receiver_forward_instance,
2882 Receiver? Receiver->getSourceRange()
2883 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002884 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002885 return ExprError();
Fangrui Song6907ce22018-07-30 19:24:48 +00002886
Douglas Gregor4123a862011-11-14 22:10:01 +00002887 forwardClass = OCIType->getInterfaceDecl();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002888 Diag(Receiver ? Receiver->getBeginLoc() : SuperLoc,
2889 diag::note_receiver_is_id);
Craig Topperc3ec1492014-05-26 06:22:03 +00002890 Method = nullptr;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002891 } else {
2892 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002893 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002894
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002895 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002896 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002897 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00002898
Douglas Gregorb5186b12010-04-22 17:01:48 +00002899 if (!Method) {
2900 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002901 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002902
David Blaikiebbafb8a2012-03-11 07:00:24 +00002903 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002904 Diag(SelLoc, diag::err_arc_may_not_respond)
2905 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002906 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002907 return ExprError();
2908 }
2909
Douglas Gregor486b74e2011-09-27 16:10:05 +00002910 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002911 // If we still haven't found a method, look in the global pool. This
2912 // behavior isn't very desirable, however we need it for GCC
2913 // compatibility. FIXME: should we deviate??
2914 if (OCIType->qual_empty()) {
Manman Rend2a3cd72016-04-07 19:30:20 +00002915 SmallVector<ObjCMethodDecl*, 4> Methods;
2916 CollectMultipleMethodsInGlobalPool(Sel, Methods,
2917 true/*InstanceFirst*/,
2918 false/*CheckTheOther*/);
2919 if (!Methods.empty()) {
George Burgess IV52d07de2016-09-01 01:26:58 +00002920 // We choose the first method as the initial candidate, then try
Manman Rend2a3cd72016-04-07 19:30:20 +00002921 // to select a better one.
2922 Method = Methods[0];
2923
2924 if (ObjCMethodDecl *BestMethod =
2925 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2926 Methods))
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002927 Method = BestMethod;
Manman Rend2a3cd72016-04-07 19:30:20 +00002928
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002929 AreMultipleMethodsInGlobalPool(Sel, Method,
2930 SourceRange(LBracLoc, RBracLoc),
Manman Rend2a3cd72016-04-07 19:30:20 +00002931 true/*receiverIdOrClass*/,
2932 Methods);
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002933 }
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002934 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002935 Diag(SelLoc, diag::warn_maynot_respond)
2936 << OCIType->getInterfaceDecl()->getIdentifier()
2937 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002938 }
2939 }
2940 }
Volodymyr Sapsai7d89ce92018-03-29 17:34:09 +00002941 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002942 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002943 } else {
John McCall80c93a02013-03-01 09:20:14 +00002944 // Reject other random receiver types (e.g. structs).
2945 Diag(Loc, diag::err_bad_receiver_type)
2946 << ReceiverType << Receiver->getSourceRange();
2947 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002948 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002949 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002950 }
Mike Stump11289f42009-09-09 15:08:12 +00002951
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002952 FunctionScopeInfo *DIFunctionScopeInfo =
2953 (Method && Method->getMethodFamily() == OMF_init)
Craig Topperc3ec1492014-05-26 06:22:03 +00002954 ? getEnclosingFunction() : nullptr;
2955
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002956 if (DIFunctionScopeInfo &&
2957 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002958 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2959 bool isDesignatedInitChain = false;
2960 if (SuperLoc.isValid()) {
2961 if (const ObjCObjectPointerType *
2962 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2963 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
Argyrios Kyrtzidisd664a342013-12-13 03:48:17 +00002964 // Either we know this is a designated initializer or we
2965 // conservatively assume it because we don't know for sure.
2966 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2967 ID->isDesignatedInitializer(Sel)) {
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002968 isDesignatedInitChain = true;
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002969 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002970 }
2971 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002972 }
2973 }
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002974 if (!isDesignatedInitChain) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002975 const ObjCMethodDecl *InitMethod = nullptr;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002976 bool isDesignated =
2977 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2978 assert(isDesignated && InitMethod);
2979 (void)isDesignated;
2980 Diag(SelLoc, SuperLoc.isValid() ?
2981 diag::warn_objc_designated_init_non_designated_init_call :
2982 diag::warn_objc_designated_init_non_super_designated_init_call);
2983 Diag(InitMethod->getLocation(),
2984 diag::note_objc_designated_init_marked_here);
2985 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002986 }
2987
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002988 if (DIFunctionScopeInfo &&
2989 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002990 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2991 if (SuperLoc.isValid()) {
2992 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2993 } else {
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002994 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002995 }
2996 }
2997
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002998 // Check the message arguments.
2999 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003000 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003001 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00003002 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00003003 bool ClassMessage = (ReceiverType->isObjCClassType() ||
3004 ReceiverType->isObjCQualifiedClassType());
Alex Lorenzf50d1ac2018-12-20 22:11:11 +00003005 if (CheckMessageArgumentTypes(Receiver, ReceiverType,
3006 MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
3007 Method, ClassMessage, SuperLoc.isValid(),
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00003008 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003009 return ExprError();
Alp Toker314cc812014-01-25 16:55:45 +00003010
3011 if (Method && !Method->getReturnType()->isVoidType() &&
3012 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00003013 diag::err_illegal_message_expr_incomplete_type))
3014 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00003015
Fangrui Song6907ce22018-07-30 19:24:48 +00003016 // In ARC, forbid the user from sending messages to
John McCall31168b02011-06-15 23:02:42 +00003017 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003018 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00003019 ObjCMethodFamily family =
3020 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
3021 switch (family) {
3022 case OMF_init:
3023 if (Method)
3024 checkInitMethod(Method, ReceiverType);
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00003025 break;
John McCall31168b02011-06-15 23:02:42 +00003026
3027 case OMF_None:
3028 case OMF_alloc:
3029 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00003030 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00003031 case OMF_mutableCopy:
3032 case OMF_new:
3033 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00003034 case OMF_initialize:
John McCall31168b02011-06-15 23:02:42 +00003035 break;
3036
3037 case OMF_dealloc:
3038 case OMF_retain:
3039 case OMF_release:
3040 case OMF_autorelease:
3041 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00003042 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
3043 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00003044 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00003045
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003046 case OMF_performSelector:
3047 if (Method && NumArgs >= 1) {
Alex Lorenz51c01282017-02-20 17:55:15 +00003048 if (const auto *SelExp =
3049 dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens())) {
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003050 Selector ArgSel = SelExp->getSelector();
Fangrui Song6907ce22018-07-30 19:24:48 +00003051 ObjCMethodDecl *SelMethod =
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003052 LookupInstanceMethodInGlobalPool(ArgSel,
3053 SelExp->getSourceRange());
3054 if (!SelMethod)
3055 SelMethod =
3056 LookupFactoryMethodInGlobalPool(ArgSel,
3057 SelExp->getSourceRange());
3058 if (SelMethod) {
3059 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
3060 switch (SelFamily) {
3061 case OMF_alloc:
3062 case OMF_copy:
3063 case OMF_mutableCopy:
3064 case OMF_new:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003065 case OMF_init:
3066 // Issue error, unless ns_returns_not_retained.
3067 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00003068 // selector names a +1 method
3069 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003070 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00003071 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3072 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003073 }
3074 break;
3075 default:
3076 // +0 call. OK. unless ns_returns_retained.
3077 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
3078 // selector names a +1 method
Fangrui Song6907ce22018-07-30 19:24:48 +00003079 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003080 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00003081 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3082 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003083 }
3084 break;
3085 }
3086 }
3087 } else {
3088 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00003089 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003090 Diag(Args[0]->getExprLoc(), diag::note_used_here);
3091 }
3092 }
3093 break;
John McCall31168b02011-06-15 23:02:42 +00003094 }
3095 }
3096
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00003097 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
Fangrui Song6907ce22018-07-30 19:24:48 +00003098
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003099 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00003100 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003101 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00003102 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00003103 SuperLoc, /*IsInstanceSuper=*/true,
Fangrui Song6907ce22018-07-30 19:24:48 +00003104 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00003105 makeArrayRef(Args, NumArgs), RBracLoc,
3106 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00003107 else {
John McCall7decc9e2010-11-18 06:31:45 +00003108 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00003109 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00003110 makeArrayRef(Args, NumArgs), RBracLoc,
3111 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00003112 if (!isImplicit)
3113 checkCocoaAPI(*this, Result);
3114 }
Alex Lorenz0e23c612017-03-06 15:58:34 +00003115 if (Method) {
3116 bool IsClassObjectCall = ClassMessage;
3117 // 'self' message receivers in class methods should be treated as message
3118 // sends to the class object in order for the semantic checks to be
3119 // performed correctly. Messages to 'super' already count as class messages,
3120 // so they don't need to be handled here.
3121 if (Receiver && isSelfExpr(Receiver)) {
3122 if (const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>()) {
3123 if (OPT->getObjectType()->isObjCClass()) {
3124 if (const auto *CurMeth = getCurMethodDecl()) {
3125 IsClassObjectCall = true;
3126 ReceiverType =
3127 Context.getObjCInterfaceType(CurMeth->getClassInterface());
3128 }
3129 }
3130 }
3131 }
3132 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
3133 ReceiverType, IsClassObjectCall);
3134 }
John McCall31168b02011-06-15 23:02:42 +00003135
David Blaikiebbafb8a2012-03-11 07:00:24 +00003136 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00003137 // In ARC, annotate delegate init calls.
3138 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00003139 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00003140 // Only consider init calls *directly* in init implementations,
3141 // not within blocks.
3142 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
3143 if (method && method->getMethodFamily() == OMF_init) {
3144 // The implicit assignment to self means we also don't want to
3145 // consume the result.
3146 Result->setDelegateInitCall(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003147 return Result;
John McCall31168b02011-06-15 23:02:42 +00003148 }
3149 }
3150
3151 // In ARC, check for message sends which are likely to introduce
3152 // retain cycles.
3153 checkRetainCycles(Result);
Brian Kelleycafd9122017-03-29 17:55:11 +00003154 }
Jordan Rose22487652012-10-11 16:06:21 +00003155
Brian Kelleycafd9122017-03-29 17:55:11 +00003156 if (getLangOpts().ObjCWeak) {
Jordan Rose22487652012-10-11 16:06:21 +00003157 if (!isImplicit && Method) {
3158 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
3159 bool IsWeak =
3160 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
3161 if (!IsWeak && Sel.isUnarySelector())
3162 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
Akira Hatanaka0a848562019-01-10 20:12:16 +00003163 if (IsWeak && !isUnevaluatedContext() &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003164 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
3165 getCurFunction()->recordUseOfWeak(Result, Prop);
Jordan Rose22487652012-10-11 16:06:21 +00003166 }
3167 }
John McCall31168b02011-06-15 23:02:42 +00003168 }
Alex Denisove1d882c2015-03-04 17:55:52 +00003169
3170 CheckObjCCircularContainer(Result);
3171
Douglas Gregoraae38d62010-05-22 05:17:18 +00003172 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003173}
3174
Fariborz Jahanian02447d82013-01-22 18:35:43 +00003175static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
3176 if (ObjCSelectorExpr *OSE =
3177 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
3178 Selector Sel = OSE->getSelector();
3179 SourceLocation Loc = OSE->getAtLoc();
Chandler Carruth12c8f652015-03-27 00:55:05 +00003180 auto Pos = S.ReferencedSelectors.find(Sel);
Fariborz Jahanian02447d82013-01-22 18:35:43 +00003181 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
3182 S.ReferencedSelectors.erase(Pos);
3183 }
3184}
3185
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003186// ActOnInstanceMessage - used for both unary and keyword messages.
3187// ArgExprs is optional - if it is present, the number of expressions
3188// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00003189ExprResult Sema::ActOnInstanceMessage(Scope *S,
Fangrui Song6907ce22018-07-30 19:24:48 +00003190 Expr *Receiver,
John McCalldadc5752010-08-24 06:29:42 +00003191 Selector Sel,
3192 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00003193 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00003194 SourceLocation RBracLoc,
3195 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003196 if (!Receiver)
3197 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00003198
3199 // A ParenListExpr can show up while doing error recovery with invalid code.
3200 if (isa<ParenListExpr>(Receiver)) {
3201 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
3202 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003203 Receiver = Result.get();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00003204 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003205
Fariborz Jahanian17748062013-01-22 19:05:17 +00003206 if (RespondsToSelectorSel.isNull()) {
3207 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
3208 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
3209 }
3210 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00003211 RemoveSelectorFromWarningCache(*this, Args[0]);
Craig Topperc3ec1492014-05-26 06:22:03 +00003212
John McCallb268a282010-08-23 23:25:46 +00003213 return BuildInstanceMessage(Receiver, Receiver->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003214 /*SuperLoc=*/SourceLocation(), Sel,
3215 /*Method=*/nullptr, LBracLoc, SelectorLocs,
3216 RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00003217}
Chris Lattner2a3569b2008-04-07 05:30:13 +00003218
John McCall31168b02011-06-15 23:02:42 +00003219enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00003220 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00003221 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00003222
3223 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00003224 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00003225
3226 /// id*, id***, void (^*)(),
3227 ACTC_indirectRetainable,
3228
3229 /// void* might be a normal C type, or it might a CF type.
3230 ACTC_voidPtr,
3231
3232 /// struct A*
3233 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00003234};
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003235
John McCalle4fe2452011-10-01 01:01:08 +00003236static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
3237 return (ACTC == ACTC_retainable ||
3238 ACTC == ACTC_coreFoundation ||
3239 ACTC == ACTC_voidPtr);
3240}
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003241
John McCalle4fe2452011-10-01 01:01:08 +00003242static bool isAnyCLike(ARCConversionTypeClass ACTC) {
3243 return ACTC == ACTC_none ||
3244 ACTC == ACTC_voidPtr ||
3245 ACTC == ACTC_coreFoundation;
3246}
3247
John McCall31168b02011-06-15 23:02:42 +00003248static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00003249 bool isIndirect = false;
Fangrui Song6907ce22018-07-30 19:24:48 +00003250
John McCall31168b02011-06-15 23:02:42 +00003251 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00003252 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00003253 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00003254 isIndirect = true;
3255 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003256
John McCall31168b02011-06-15 23:02:42 +00003257 // Drill through pointers and arrays recursively.
3258 while (true) {
3259 if (const PointerType *ptr = type->getAs<PointerType>()) {
3260 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00003261
3262 // The first level of pointer may be the innermost pointer on a CF type.
3263 if (!isIndirect) {
3264 if (type->isVoidType()) return ACTC_voidPtr;
3265 if (type->isRecordType()) return ACTC_coreFoundation;
3266 }
John McCall31168b02011-06-15 23:02:42 +00003267 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
3268 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
3269 } else {
3270 break;
3271 }
John McCalle4fe2452011-10-01 01:01:08 +00003272 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00003273 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003274
John McCalle4fe2452011-10-01 01:01:08 +00003275 if (isIndirect) {
3276 if (type->isObjCARCBridgableType())
3277 return ACTC_indirectRetainable;
3278 return ACTC_none;
3279 }
3280
3281 if (type->isObjCARCBridgableType())
3282 return ACTC_retainable;
3283
3284 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00003285}
3286
3287namespace {
John McCalle4fe2452011-10-01 01:01:08 +00003288 /// A result from the cast checker.
3289 enum ACCResult {
3290 /// Cannot be casted.
3291 ACC_invalid,
3292
3293 /// Can be safely retained or not retained.
3294 ACC_bottom,
3295
3296 /// Can be casted at +0.
3297 ACC_plusZero,
3298
3299 /// Can be casted at +1.
3300 ACC_plusOne
3301 };
3302 ACCResult merge(ACCResult left, ACCResult right) {
3303 if (left == right) return left;
3304 if (left == ACC_bottom) return right;
3305 if (right == ACC_bottom) return left;
3306 return ACC_invalid;
3307 }
3308
3309 /// A checker which white-lists certain expressions whose conversion
3310 /// to or from retainable type would otherwise be forbidden in ARC.
3311 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
3312 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
3313
John McCall31168b02011-06-15 23:02:42 +00003314 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00003315 ARCConversionTypeClass SourceClass;
3316 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003317 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00003318
3319 static bool isCFType(QualType type) {
3320 // Someday this can use ns_bridged. For now, it has to do this.
3321 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00003322 }
John McCalle4fe2452011-10-01 01:01:08 +00003323
3324 public:
3325 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003326 ARCConversionTypeClass target, bool diagnose)
3327 : Context(Context), SourceClass(source), TargetClass(target),
3328 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00003329
3330 using super::Visit;
3331 ACCResult Visit(Expr *e) {
3332 return super::Visit(e->IgnoreParens());
3333 }
3334
3335 ACCResult VisitStmt(Stmt *s) {
3336 return ACC_invalid;
3337 }
3338
3339 /// Null pointer constants can be casted however you please.
3340 ACCResult VisitExpr(Expr *e) {
3341 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
3342 return ACC_bottom;
3343 return ACC_invalid;
3344 }
3345
3346 /// Objective-C string literals can be safely casted.
3347 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3348 // If we're casting to any retainable type, go ahead. Global
3349 // strings are immune to retains, so this is bottom.
3350 if (isAnyRetainable(TargetClass)) return ACC_bottom;
3351
3352 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00003353 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003354
John McCalle4fe2452011-10-01 01:01:08 +00003355 /// Look through certain implicit and explicit casts.
3356 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003357 switch (e->getCastKind()) {
3358 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00003359 return ACC_bottom;
3360
John McCall31168b02011-06-15 23:02:42 +00003361 case CK_NoOp:
3362 case CK_LValueToRValue:
3363 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00003364 case CK_CPointerToObjCPointerCast:
3365 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00003366 case CK_AnyPointerToBlockPointerCast:
3367 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00003368
John McCall31168b02011-06-15 23:02:42 +00003369 default:
John McCalle4fe2452011-10-01 01:01:08 +00003370 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00003371 }
3372 }
John McCalle4fe2452011-10-01 01:01:08 +00003373
3374 /// Look through unary extension.
3375 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003376 return Visit(e->getSubExpr());
3377 }
John McCalle4fe2452011-10-01 01:01:08 +00003378
3379 /// Ignore the LHS of a comma operator.
3380 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003381 return Visit(e->getRHS());
3382 }
John McCalle4fe2452011-10-01 01:01:08 +00003383
3384 /// Conditional operators are okay if both sides are okay.
3385 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3386 ACCResult left = Visit(e->getTrueExpr());
3387 if (left == ACC_invalid) return ACC_invalid;
3388 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00003389 }
John McCalle4fe2452011-10-01 01:01:08 +00003390
John McCallfe96e0b2011-11-06 09:01:30 +00003391 /// Look through pseudo-objects.
3392 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3393 // If we're getting here, we should always have a result.
3394 return Visit(e->getResultExpr());
3395 }
3396
John McCalle4fe2452011-10-01 01:01:08 +00003397 /// Statement expressions are okay if their result expression is okay.
3398 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003399 return Visit(e->getSubStmt()->body_back());
3400 }
John McCall31168b02011-06-15 23:02:42 +00003401
John McCalle4fe2452011-10-01 01:01:08 +00003402 /// Some declaration references are okay.
3403 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
John McCalle4fe2452011-10-01 01:01:08 +00003404 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
Ben Langmuir443aa4b2015-02-25 20:09:06 +00003405 // References to global constants are okay.
John McCalle4fe2452011-10-01 01:01:08 +00003406 if (isAnyRetainable(TargetClass) &&
3407 isAnyRetainable(SourceClass) &&
3408 var &&
Akira Hatanakaad515392017-04-11 22:01:33 +00003409 !var->hasDefinition(Context) &&
Ben Langmuir443aa4b2015-02-25 20:09:06 +00003410 var->getType().isConstQualified()) {
3411
3412 // In system headers, they can also be assumed to be immune to retains.
3413 // These are things like 'kCFStringTransformToLatin'.
3414 if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
3415 return ACC_bottom;
3416
3417 return ACC_plusZero;
John McCalle4fe2452011-10-01 01:01:08 +00003418 }
3419
3420 // Nothing else.
3421 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00003422 }
John McCalle4fe2452011-10-01 01:01:08 +00003423
3424 /// Some calls are okay.
3425 ACCResult VisitCallExpr(CallExpr *e) {
3426 if (FunctionDecl *fn = e->getDirectCallee())
3427 if (ACCResult result = checkCallToFunction(fn))
3428 return result;
3429
3430 return super::VisitCallExpr(e);
3431 }
3432
3433 ACCResult checkCallToFunction(FunctionDecl *fn) {
3434 // Require a CF*Ref return type.
Alp Toker314cc812014-01-25 16:55:45 +00003435 if (!isCFType(fn->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003436 return ACC_invalid;
3437
3438 if (!isAnyRetainable(TargetClass))
3439 return ACC_invalid;
3440
3441 // Honor an explicit 'not retained' attribute.
3442 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3443 return ACC_plusZero;
3444
3445 // Honor an explicit 'retained' attribute, except that for
3446 // now we're not going to permit implicit handling of +1 results,
3447 // because it's a bit frightening.
3448 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003449 return Diagnose ? ACC_plusOne
3450 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003451
3452 // Recognize this specific builtin function, which is used by CFSTR.
3453 unsigned builtinID = fn->getBuiltinID();
3454 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3455 return ACC_bottom;
3456
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003457 // Otherwise, don't do anything implicit with an unaudited function.
3458 if (!fn->hasAttr<CFAuditedTransferAttr>())
3459 return ACC_invalid;
Fangrui Song6907ce22018-07-30 19:24:48 +00003460
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003461 // Otherwise, it's +0 unless it follows the create convention.
3462 if (ento::coreFoundation::followsCreateRule(fn))
Fangrui Song6907ce22018-07-30 19:24:48 +00003463 return Diagnose ? ACC_plusOne
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003464 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003465
John McCalle4fe2452011-10-01 01:01:08 +00003466 return ACC_plusZero;
3467 }
3468
3469 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3470 return checkCallToMethod(e->getMethodDecl());
3471 }
3472
3473 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3474 ObjCMethodDecl *method;
3475 if (e->isExplicitProperty())
3476 method = e->getExplicitProperty()->getGetterMethodDecl();
3477 else
3478 method = e->getImplicitPropertyGetter();
3479 return checkCallToMethod(method);
3480 }
3481
3482 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3483 if (!method) return ACC_invalid;
3484
3485 // Check for message sends to functions returning CF types. We
3486 // just obey the Cocoa conventions with these, even though the
3487 // return type is CF.
Alp Toker314cc812014-01-25 16:55:45 +00003488 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003489 return ACC_invalid;
Fangrui Song6907ce22018-07-30 19:24:48 +00003490
John McCalle4fe2452011-10-01 01:01:08 +00003491 // If the method is explicitly marked not-retained, it's +0.
3492 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3493 return ACC_plusZero;
3494
3495 // If the method is explicitly marked as returning retained, or its
3496 // selector follows a +1 Cocoa convention, treat it as +1.
3497 if (method->hasAttr<CFReturnsRetainedAttr>())
3498 return ACC_plusOne;
3499
3500 switch (method->getSelector().getMethodFamily()) {
3501 case OMF_alloc:
3502 case OMF_copy:
3503 case OMF_mutableCopy:
3504 case OMF_new:
3505 return ACC_plusOne;
3506
3507 default:
3508 // Otherwise, treat it as +0.
3509 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00003510 }
3511 }
John McCalle4fe2452011-10-01 01:01:08 +00003512 };
Eugene Zelenko1ced5092016-02-12 22:53:10 +00003513} // end anonymous namespace
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00003514
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003515bool Sema::isKnownName(StringRef name) {
3516 if (name.empty())
3517 return false;
3518 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003519 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003520 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003521}
3522
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003523static void addFixitForObjCARCConversion(Sema &S,
3524 DiagnosticBuilder &DiagB,
3525 Sema::CheckedConversionKind CCK,
3526 SourceLocation afterLParen,
3527 QualType castType,
3528 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003529 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003530 const char *bridgeKeyword,
3531 const char *CFBridgeName) {
3532 // We handle C-style and implicit casts here.
3533 switch (CCK) {
3534 case Sema::CCK_ImplicitConversion:
Richard Smith1ef75542018-06-27 20:30:34 +00003535 case Sema::CCK_ForBuiltinOverloadedOp:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003536 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003537 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003538 break;
3539 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003540 return;
3541 }
3542
3543 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003544 if (CCK == Sema::CCK_OtherCast) {
3545 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3546 SourceRange range(NCE->getOperatorLoc(),
3547 NCE->getAngleBrackets().getEnd());
3548 SmallString<32> BridgeCall;
Fangrui Song6907ce22018-07-30 19:24:48 +00003549
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003550 SourceManager &SM = S.getSourceManager();
3551 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3552 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3553 BridgeCall += ' ';
Fangrui Song6907ce22018-07-30 19:24:48 +00003554
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003555 BridgeCall += CFBridgeName;
3556 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3557 }
3558 return;
3559 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003560 Expr *castedE = castExpr;
3561 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3562 castedE = CCE->getSubExpr();
3563 castedE = castedE->IgnoreImpCasts();
3564 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00003565
3566 SmallString<32> BridgeCall;
3567
3568 SourceManager &SM = S.getSourceManager();
3569 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3570 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3571 BridgeCall += ' ';
3572
3573 BridgeCall += CFBridgeName;
3574
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003575 if (isa<ParenExpr>(castedE)) {
3576 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003577 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003578 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00003579 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003580 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003581 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003582 DiagB.AddFixItHint(FixItHint::CreateInsertion(
Craig Topper07fa1762015-11-15 02:31:46 +00003583 S.getLocForEndOfToken(range.getEnd()),
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003584 ")"));
3585 }
3586 return;
3587 }
3588
3589 if (CCK == Sema::CCK_CStyleCast) {
3590 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003591 } else if (CCK == Sema::CCK_OtherCast) {
3592 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3593 std::string castCode = "(";
3594 castCode += bridgeKeyword;
3595 castCode += castType.getAsString();
3596 castCode += ")";
3597 SourceRange Range(NCE->getOperatorLoc(),
3598 NCE->getAngleBrackets().getEnd());
3599 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3600 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003601 } else {
3602 std::string castCode = "(";
3603 castCode += bridgeKeyword;
3604 castCode += castType.getAsString();
3605 castCode += ")";
3606 Expr *castedE = castExpr->IgnoreImpCasts();
3607 SourceRange range = castedE->getSourceRange();
3608 if (isa<ParenExpr>(castedE)) {
3609 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3610 castCode));
3611 } else {
3612 castCode += "(";
3613 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3614 castCode));
3615 DiagB.AddFixItHint(FixItHint::CreateInsertion(
Craig Topper07fa1762015-11-15 02:31:46 +00003616 S.getLocForEndOfToken(range.getEnd()),
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003617 ")"));
3618 }
3619 }
3620}
3621
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003622template <typename T>
3623static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3624 TypedefNameDecl *TDNDecl = TD->getDecl();
3625 QualType QT = TDNDecl->getUnderlyingType();
3626 if (QT->isPointerType()) {
3627 QT = QT->getPointeeType();
3628 if (const RecordType *RT = QT->getAs<RecordType>())
Fariborz Jahanian9af6a782014-06-11 19:10:46 +00003629 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
Aaron Ballman2084f8f2013-12-19 13:20:36 +00003630 return RD->getAttr<T>();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003631 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003632 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003633}
3634
3635static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3636 TypedefNameDecl *&TDNDecl) {
3637 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3638 TDNDecl = TD->getDecl();
3639 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3640 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3641 return ObjCBAttr;
3642 T = TDNDecl->getUnderlyingType();
3643 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003644 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003645}
3646
John McCall4124c492011-10-17 18:40:02 +00003647static void
3648diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3649 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003650 Expr *castExpr, Expr *realCast,
3651 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003652 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003653 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003654 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
Fangrui Song6907ce22018-07-30 19:24:48 +00003655
John McCall4124c492011-10-17 18:40:02 +00003656 if (S.makeUnavailableInSystemHeader(loc,
John McCallc6af8c62015-10-28 05:03:19 +00003657 UnavailableAttr::IR_ARCForbiddenConversion))
John McCall31168b02011-06-15 23:02:42 +00003658 return;
John McCall4124c492011-10-17 18:40:02 +00003659
3660 QualType castExprType = castExpr->getType();
Bob Wilsonf5c53b82016-02-13 01:41:41 +00003661 // Defer emitting a diagnostic for bridge-related casts; that will be
3662 // handled by CheckObjCBridgeRelatedConversions.
Craig Topperc3ec1492014-05-26 06:22:03 +00003663 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003664 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3665 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3666 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
Fariborz Jahanian1ad83a32014-06-18 23:22:38 +00003667 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003668 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00003669
John McCall640767f2011-06-17 06:50:50 +00003670 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003671 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003672 case ACTC_none:
3673 case ACTC_coreFoundation:
3674 case ACTC_voidPtr:
3675 srcKind = (castExprType->isPointerType() ? 1 : 0);
3676 break;
3677 case ACTC_retainable:
3678 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3679 break;
3680 case ACTC_indirectRetainable:
3681 srcKind = 4;
3682 break;
John McCall31168b02011-06-15 23:02:42 +00003683 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003684
John McCall4124c492011-10-17 18:40:02 +00003685 // Check whether this could be fixed with a bridge cast.
Craig Topper07fa1762015-11-15 02:31:46 +00003686 SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin());
John McCall4124c492011-10-17 18:40:02 +00003687 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003688
Richard Smith1ef75542018-06-27 20:30:34 +00003689 unsigned convKindForDiag = Sema::isCast(CCK) ? 0 : 1;
3690
John McCall4124c492011-10-17 18:40:02 +00003691 // Bridge from an ARC type to a CF type.
3692 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003693
John McCall4124c492011-10-17 18:40:02 +00003694 S.Diag(loc, diag::err_arc_cast_requires_bridge)
Richard Smith1ef75542018-06-27 20:30:34 +00003695 << convKindForDiag
John McCall4124c492011-10-17 18:40:02 +00003696 << 2 // of C pointer type
3697 << castExprType
3698 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3699 << castType
3700 << castRange
3701 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003702 bool br = S.isKnownName("CFBridgingRelease");
Fangrui Song6907ce22018-07-30 19:24:48 +00003703 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003704 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003705 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003706 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003707 {
Fangrui Song6907ce22018-07-30 19:24:48 +00003708 DiagnosticBuilder DiagB =
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003709 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3710 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Craig Topperc3ec1492014-05-26 06:22:03 +00003711
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003712 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003713 castType, castExpr, realCast, "__bridge ",
3714 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003715 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003716 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003717 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003718 DiagnosticBuilder DiagB =
3719 (CCK == Sema::CCK_OtherCast && !br) ?
3720 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3721 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3722 diag::note_arc_bridge_transfer)
3723 << castExprType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003724
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003725 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003726 castType, castExpr, realCast, "__bridge_transfer ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003727 br ? "CFBridgingRelease" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003728 }
John McCall4124c492011-10-17 18:40:02 +00003729
3730 return;
3731 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003732
John McCall4124c492011-10-17 18:40:02 +00003733 // Bridge from a CF type to an ARC type.
3734 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003735 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003736 S.Diag(loc, diag::err_arc_cast_requires_bridge)
Richard Smith1ef75542018-06-27 20:30:34 +00003737 << convKindForDiag
John McCall4124c492011-10-17 18:40:02 +00003738 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3739 << castExprType
3740 << 2 // to C pointer type
3741 << castType
3742 << castRange
3743 << castExpr->getSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +00003744 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003745 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003746 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003747 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003748 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003749 DiagnosticBuilder DiagB =
3750 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3751 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003752 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003753 castType, castExpr, realCast, "__bridge ",
3754 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003755 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003756 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003757 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003758 DiagnosticBuilder DiagB =
3759 (CCK == Sema::CCK_OtherCast && !br) ?
3760 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3761 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3762 diag::note_arc_bridge_retained)
3763 << castType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003764
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003765 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003766 castType, castExpr, realCast, "__bridge_retained ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003767 br ? "CFBridgingRetain" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003768 }
John McCall4124c492011-10-17 18:40:02 +00003769
3770 return;
John McCall31168b02011-06-15 23:02:42 +00003771 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003772
John McCall4124c492011-10-17 18:40:02 +00003773 S.Diag(loc, diag::err_arc_mismatched_cast)
Richard Smith1ef75542018-06-27 20:30:34 +00003774 << !convKindForDiag
John McCall4124c492011-10-17 18:40:02 +00003775 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003776 << castRange << castExpr->getSourceRange();
3777}
3778
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003779template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003780static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3781 bool &HadTheAttribute, bool warn) {
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003782 QualType T = castExpr->getType();
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003783 HadTheAttribute = false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003784 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3785 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003786 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003787 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003788 HadTheAttribute = true;
Fariborz Jahanianc9e266b2014-12-11 22:56:26 +00003789 if (Parm->isStr("id"))
3790 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +00003791
Craig Topperc3ec1492014-05-26 06:22:03 +00003792 NamedDecl *Target = nullptr;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003793 // Check for an existing type with this name.
3794 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3795 Sema::LookupOrdinaryName);
3796 if (S.LookupName(R, S.TUScope)) {
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003797 Target = R.getFoundDecl();
3798 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3799 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3800 if (const ObjCObjectPointerType *InterfacePointerType =
3801 castType->getAsObjCInterfacePointerType()) {
3802 ObjCInterfaceDecl *CastClass
3803 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003804 if ((CastClass == ExprClass) ||
Fariborz Jahanian27aa9b42015-04-10 22:07:47 +00003805 (CastClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003806 return true;
3807 if (warn)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003808 S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
3809 << T << Target->getName() << castType->getPointeeType();
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003810 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003811 } else if (castType->isObjCIdType() ||
3812 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3813 castType, ExprClass)))
3814 // ok to cast to 'id'.
3815 // casting to id<p-list> is ok if bridge type adopts all of
3816 // p-list protocols.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003817 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003818 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003819 if (warn) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003820 S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
3821 << T << Target->getName() << castType;
3822 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
3823 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003824 }
3825 return false;
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003826 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003827 }
Fariborz Jahanian696c8872015-04-09 23:39:53 +00003828 } else if (!castType->isObjCIdType()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003829 S.Diag(castExpr->getBeginLoc(),
3830 diag::err_objc_cf_bridged_not_interface)
3831 << castExpr->getType() << Parm;
3832 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
Fariborz Jahanian696c8872015-04-09 23:39:53 +00003833 if (Target)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003834 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003835 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003836 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003837 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003838 return false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003839 }
3840 T = TDNDecl->getUnderlyingType();
3841 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003842 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003843}
3844
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003845template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003846static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3847 bool &HadTheAttribute, bool warn) {
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003848 QualType T = castType;
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003849 HadTheAttribute = false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003850 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3851 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003852 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003853 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003854 HadTheAttribute = true;
John McCallaf6b3f82015-03-10 18:41:23 +00003855 if (Parm->isStr("id"))
3856 return true;
3857
Craig Topperc3ec1492014-05-26 06:22:03 +00003858 NamedDecl *Target = nullptr;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003859 // Check for an existing type with this name.
3860 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3861 Sema::LookupOrdinaryName);
3862 if (S.LookupName(R, S.TUScope)) {
3863 Target = R.getFoundDecl();
3864 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3865 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3866 if (const ObjCObjectPointerType *InterfacePointerType =
3867 castExpr->getType()->getAsObjCInterfacePointerType()) {
3868 ObjCInterfaceDecl *ExprClass
3869 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003870 if ((CastClass == ExprClass) ||
3871 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003872 return true;
3873 if (warn) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003874 S.Diag(castExpr->getBeginLoc(),
3875 diag::warn_objc_invalid_bridge_to_cf)
3876 << castExpr->getType()->getPointeeType() << T;
3877 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003878 }
3879 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003880 } else if (castExpr->getType()->isObjCIdType() ||
3881 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3882 castExpr->getType(), CastClass)))
3883 // ok to cast an 'id' expression to a CFtype.
3884 // ok to cast an 'id<plist>' expression to CFtype provided plist
3885 // adopts all of CFtype's ObjetiveC's class plist.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003886 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003887 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003888 if (warn) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003889 S.Diag(castExpr->getBeginLoc(),
3890 diag::warn_objc_invalid_bridge_to_cf)
3891 << castExpr->getType() << castType;
3892 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
3893 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003894 }
3895 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003896 }
3897 }
3898 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003899 S.Diag(castExpr->getBeginLoc(),
3900 diag::err_objc_ns_bridged_invalid_cfobject)
3901 << castExpr->getType() << castType;
3902 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003903 if (Target)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003904 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003905 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003906 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003907 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003908 }
3909 T = TDNDecl->getUnderlyingType();
3910 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003911 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003912}
3913
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003914void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003915 if (!getLangOpts().ObjC)
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003916 return;
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003917 // warn in presence of __bridge casting to or from a toll free bridge cast.
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003918 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3919 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003920 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003921 bool HasObjCBridgeAttr;
3922 bool ObjCBridgeAttrWillNotWarn =
3923 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3924 false);
3925 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3926 return;
3927 bool HasObjCBridgeMutableAttr;
3928 bool ObjCBridgeMutableAttrWillNotWarn =
3929 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3930 HasObjCBridgeMutableAttr, false);
3931 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3932 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00003933
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003934 if (HasObjCBridgeAttr)
3935 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3936 true);
3937 else if (HasObjCBridgeMutableAttr)
3938 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3939 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003940 }
3941 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003942 bool HasObjCBridgeAttr;
3943 bool ObjCBridgeAttrWillNotWarn =
3944 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3945 false);
3946 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3947 return;
3948 bool HasObjCBridgeMutableAttr;
3949 bool ObjCBridgeMutableAttrWillNotWarn =
3950 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3951 HasObjCBridgeMutableAttr, false);
3952 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3953 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00003954
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003955 if (HasObjCBridgeAttr)
3956 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3957 true);
3958 else if (HasObjCBridgeMutableAttr)
3959 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3960 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003961 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003962}
3963
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003964void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3965 QualType SrcType = castExpr->getType();
3966 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3967 if (PRE->isExplicitProperty()) {
3968 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3969 SrcType = PDecl->getType();
3970 }
3971 else if (PRE->isImplicitProperty()) {
3972 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3973 SrcType = Getter->getReturnType();
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003974 }
3975 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003976
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003977 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3978 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3979 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3980 return;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003981 CheckObjCBridgeRelatedConversions(castExpr->getBeginLoc(), castType, SrcType,
3982 castExpr);
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003983}
3984
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00003985bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3986 CastKind &Kind) {
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003987 if (!getLangOpts().ObjC)
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00003988 return false;
3989 ARCConversionTypeClass exprACTC =
3990 classifyTypeForARCConversion(castExpr->getType());
3991 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3992 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3993 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3994 CheckTollFreeBridgeCast(castType, castExpr);
3995 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3996 : CK_CPointerToObjCPointerCast;
3997 return true;
3998 }
3999 return false;
4000}
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004001
4002bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
4003 QualType DestType, QualType SrcType,
4004 ObjCInterfaceDecl *&RelatedClass,
4005 ObjCMethodDecl *&ClassMethod,
4006 ObjCMethodDecl *&InstanceMethod,
4007 TypedefNameDecl *&TDNDecl,
George Burgess IV60bc9722016-01-13 23:36:34 +00004008 bool CfToNs, bool Diagnose) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004009 QualType T = CfToNs ? SrcType : DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004010 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
4011 if (!ObjCBAttr)
4012 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004013
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004014 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
4015 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
4016 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
4017 if (!RCId)
4018 return false;
Craig Topperc3ec1492014-05-26 06:22:03 +00004019 NamedDecl *Target = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004020 // Check for an existing type with this name.
4021 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
4022 Sema::LookupOrdinaryName);
4023 if (!LookupName(R, TUScope)) {
George Burgess IV60bc9722016-01-13 23:36:34 +00004024 if (Diagnose) {
4025 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
4026 << SrcType << DestType;
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;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004030 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004031 Target = R.getFoundDecl();
4032 if (Target && isa<ObjCInterfaceDecl>(Target))
4033 RelatedClass = cast<ObjCInterfaceDecl>(Target);
4034 else {
George Burgess IV60bc9722016-01-13 23:36:34 +00004035 if (Diagnose) {
4036 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
4037 << SrcType << DestType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004038 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
George Burgess IV60bc9722016-01-13 23:36:34 +00004039 if (Target)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004040 Diag(Target->getBeginLoc(), diag::note_declared_at);
George Burgess IV60bc9722016-01-13 23:36:34 +00004041 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004042 return false;
4043 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004044
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004045 // Check for an existing class method with the given selector name.
4046 if (CfToNs && CMId) {
4047 Selector Sel = Context.Selectors.getUnarySelector(CMId);
4048 ClassMethod = RelatedClass->lookupMethod(Sel, false);
4049 if (!ClassMethod) {
George Burgess IV60bc9722016-01-13 23:36:34 +00004050 if (Diagnose) {
4051 Diag(Loc, diag::err_objc_bridged_related_known_method)
4052 << SrcType << DestType << Sel << false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004053 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
George Burgess IV60bc9722016-01-13 23:36:34 +00004054 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004055 return false;
4056 }
4057 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004058
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004059 // Check for an existing instance method with the given selector name.
4060 if (!CfToNs && IMId) {
4061 Selector Sel = Context.Selectors.getNullarySelector(IMId);
4062 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
4063 if (!InstanceMethod) {
George Burgess IV60bc9722016-01-13 23:36:34 +00004064 if (Diagnose) {
4065 Diag(Loc, diag::err_objc_bridged_related_known_method)
4066 << SrcType << DestType << Sel << true;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004067 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
George Burgess IV60bc9722016-01-13 23:36:34 +00004068 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00004069 return false;
4070 }
4071 }
4072 return true;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004073}
4074
4075bool
4076Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
Fariborz Jahaniandb765772013-12-10 17:08:13 +00004077 QualType DestType, QualType SrcType,
George Burgess IV60bc9722016-01-13 23:36:34 +00004078 Expr *&SrcExpr, bool Diagnose) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004079 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
4080 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
4081 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
4082 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
4083 if (!CfToNs && !NsToCf)
4084 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004085
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004086 ObjCInterfaceDecl *RelatedClass;
Craig Topperc3ec1492014-05-26 06:22:03 +00004087 ObjCMethodDecl *ClassMethod = nullptr;
4088 ObjCMethodDecl *InstanceMethod = nullptr;
4089 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004090 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
George Burgess IV60bc9722016-01-13 23:36:34 +00004091 ClassMethod, InstanceMethod, TDNDecl,
4092 CfToNs, Diagnose))
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004093 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004094
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004095 if (CfToNs) {
4096 // Implicit conversion from CF to ObjC object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00004097 if (ClassMethod) {
George Burgess IV60bc9722016-01-13 23:36:34 +00004098 if (Diagnose) {
4099 std::string ExpressionString = "[";
4100 ExpressionString += RelatedClass->getNameAsString();
4101 ExpressionString += " ";
4102 ExpressionString += ClassMethod->getSelector().getAsString();
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004103 SourceLocation SrcExprEndLoc =
4104 getLocForEndOfToken(SrcExpr->getEndLoc());
George Burgess IV60bc9722016-01-13 23:36:34 +00004105 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
4106 Diag(Loc, diag::err_objc_bridged_related_known_method)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004107 << SrcType << DestType << ClassMethod->getSelector() << false
4108 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(),
4109 ExpressionString)
4110 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
4111 Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
4112 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
Fangrui Song6907ce22018-07-30 19:24:48 +00004113
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004114 QualType receiverType = Context.getObjCInterfaceType(RelatedClass);
4115 // Argument.
4116 Expr *args[] = { SrcExpr };
4117 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
Fariborz Jahanian381edf52013-12-16 22:54:37 +00004118 ClassMethod->getLocation(),
4119 ClassMethod->getSelector(), ClassMethod,
4120 MultiExprArg(args, 1));
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004121 SrcExpr = msg.get();
4122 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00004123 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00004124 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004125 }
4126 else {
4127 // Implicit conversion from ObjC type to CF object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00004128 if (InstanceMethod) {
George Burgess IV60bc9722016-01-13 23:36:34 +00004129 if (Diagnose) {
4130 std::string ExpressionString;
4131 SourceLocation SrcExprEndLoc =
Stephen Kelly1c301dc2018-08-09 21:09:38 +00004132 getLocForEndOfToken(SrcExpr->getEndLoc());
George Burgess IV60bc9722016-01-13 23:36:34 +00004133 if (InstanceMethod->isPropertyAccessor())
4134 if (const ObjCPropertyDecl *PDecl =
4135 InstanceMethod->findPropertyDecl()) {
4136 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
4137 ExpressionString = ".";
4138 ExpressionString += PDecl->getNameAsString();
4139 Diag(Loc, diag::err_objc_bridged_related_known_method)
4140 << SrcType << DestType << InstanceMethod->getSelector() << true
4141 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4142 }
4143 if (ExpressionString.empty()) {
4144 // Provide a fixit: [ObjectExpr InstanceMethod]
4145 ExpressionString = " ";
4146 ExpressionString += InstanceMethod->getSelector().getAsString();
4147 ExpressionString += "]";
4148
Fariborz Jahanian88b68982013-12-10 23:18:06 +00004149 Diag(Loc, diag::err_objc_bridged_related_known_method)
George Burgess IV60bc9722016-01-13 23:36:34 +00004150 << SrcType << DestType << InstanceMethod->getSelector() << true
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004151 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "[")
George Burgess IV60bc9722016-01-13 23:36:34 +00004152 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
Fariborz Jahanian88b68982013-12-10 23:18:06 +00004153 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004154 Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
4155 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
Fangrui Song6907ce22018-07-30 19:24:48 +00004156
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004157 ExprResult msg =
4158 BuildInstanceMessageImplicit(SrcExpr, SrcType,
4159 InstanceMethod->getLocation(),
4160 InstanceMethod->getSelector(),
4161 InstanceMethod, None);
4162 SrcExpr = msg.get();
4163 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00004164 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00004165 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004166 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00004167 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00004168}
4169
John McCall4124c492011-10-17 18:40:02 +00004170Sema::ARCConversionResult
Brian Kelley11352a82017-03-29 18:09:02 +00004171Sema::CheckObjCConversion(SourceRange castRange, QualType castType,
4172 Expr *&castExpr, CheckedConversionKind CCK,
4173 bool Diagnose, bool DiagnoseCFAudited,
4174 BinaryOperatorKind Opc) {
John McCall4124c492011-10-17 18:40:02 +00004175 QualType castExprType = castExpr->getType();
4176
4177 // For the purposes of the classification, we assume reference types
4178 // will bind to temporaries.
4179 QualType effCastType = castType;
4180 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
4181 effCastType = ref->getPointeeType();
Fangrui Song6907ce22018-07-30 19:24:48 +00004182
John McCall4124c492011-10-17 18:40:02 +00004183 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
4184 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004185 if (exprACTC == castACTC) {
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004186 // Check for viability and report error if casting an rvalue to a
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004187 // life-time qualifier.
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004188 if (castACTC == ACTC_retainable &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004189 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
George Burgess IV60bc9722016-01-13 23:36:34 +00004190 castType != castExprType) {
Fariborz Jahanian244b1872011-10-29 00:06:10 +00004191 const Type *DT = castType.getTypePtr();
4192 QualType QDT = castType;
4193 // We desugar some types but not others. We ignore those
4194 // that cannot happen in a cast; i.e. auto, and those which
4195 // should not be de-sugared; i.e typedef.
4196 if (const ParenType *PT = dyn_cast<ParenType>(DT))
4197 QDT = PT->desugar();
4198 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
4199 QDT = TP->desugar();
4200 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
4201 QDT = AT->desugar();
4202 if (QDT != castType &&
4203 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004204 if (Diagnose) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004205 SourceLocation loc = (castRange.isValid() ? castRange.getBegin()
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004206 : castExpr->getExprLoc());
4207 Diag(loc, diag::err_arc_nolifetime_behavior);
4208 }
4209 return ACR_error;
Fariborz Jahanian244b1872011-10-29 00:06:10 +00004210 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004211 }
4212 return ACR_okay;
4213 }
Brian Kelley11352a82017-03-29 18:09:02 +00004214
4215 // The life-time qualifier cast check above is all we need for ObjCWeak.
4216 // ObjCAutoRefCount has more restrictions on what is legal.
4217 if (!getLangOpts().ObjCAutoRefCount)
4218 return ACR_okay;
4219
John McCall4124c492011-10-17 18:40:02 +00004220 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
4221
4222 // Allow all of these types to be cast to integer types (but not
4223 // vice-versa).
4224 if (castACTC == ACTC_none && castType->isIntegralType(Context))
4225 return ACR_okay;
Fangrui Song6907ce22018-07-30 19:24:48 +00004226
John McCall4124c492011-10-17 18:40:02 +00004227 // Allow casts between pointers to lifetime types (e.g., __strong id*)
4228 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
4229 // must be explicit.
4230 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
4231 return ACR_okay;
4232 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
Richard Smith1ef75542018-06-27 20:30:34 +00004233 isCast(CCK))
John McCall4124c492011-10-17 18:40:02 +00004234 return ACR_okay;
4235
Fariborz Jahanian36986c62012-07-27 22:37:07 +00004236 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00004237 // For invalid casts, fall through.
4238 case ACC_invalid:
4239 break;
4240
4241 // Do nothing for both bottom and +0.
4242 case ACC_bottom:
4243 case ACC_plusZero:
4244 return ACR_okay;
4245
4246 // If the result is +1, consume it here.
4247 case ACC_plusOne:
4248 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
4249 CK_ARCConsumeObject, castExpr,
Craig Topperc3ec1492014-05-26 06:22:03 +00004250 nullptr, VK_RValue);
Tim Shen4a05bb82016-06-21 20:29:17 +00004251 Cleanup.setExprNeedsCleanups(true);
John McCall4124c492011-10-17 18:40:02 +00004252 return ACR_okay;
4253 }
4254
4255 // If this is a non-implicit cast from id or block type to a
4256 // CoreFoundation type, delay complaining in case the cast is used
4257 // in an acceptable context.
Richard Smith1ef75542018-06-27 20:30:34 +00004258 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) && isCast(CCK))
John McCall4124c492011-10-17 18:40:02 +00004259 return ACR_unbridged;
4260
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004261 // Issue a diagnostic about a missing @-sign when implicit casting a cstring
4262 // to 'NSString *', instead of falling through to report a "bridge cast"
4263 // diagnostic.
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004264 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
George Burgess IV60bc9722016-01-13 23:36:34 +00004265 ConversionToObjCStringLiteralCheck(castType, castExpr, Diagnose))
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004266 return ACR_error;
Fangrui Song6907ce22018-07-30 19:24:48 +00004267
Fariborz Jahanian25eef192013-07-31 21:40:51 +00004268 // Do not issue "bridge cast" diagnostic when implicit casting
4269 // a retainable object to a CF type parameter belonging to an audited
4270 // CF API function. Let caller issue a normal type mismatched diagnostic
4271 // instead.
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004272 if ((!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
4273 castACTC != ACTC_coreFoundation) &&
4274 !(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
4275 (Opc == BO_NE || Opc == BO_EQ))) {
4276 if (Diagnose)
George Burgess IV60bc9722016-01-13 23:36:34 +00004277 diagnoseObjCARCConversion(*this, castRange, castType, castACTC, castExpr,
4278 castExpr, exprACTC, CCK);
Bob Wilsonf5c53b82016-02-13 01:41:41 +00004279 return ACR_error;
4280 }
John McCall4124c492011-10-17 18:40:02 +00004281 return ACR_okay;
4282}
4283
4284/// Given that we saw an expression with the ARCUnbridgedCastTy
4285/// placeholder type, complain bitterly.
4286void Sema::diagnoseARCUnbridgedCast(Expr *e) {
4287 // We expect the spurious ImplicitCastExpr to already have been stripped.
4288 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4289 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
4290
4291 SourceRange castRange;
4292 QualType castType;
4293 CheckedConversionKind CCK;
4294
4295 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
4296 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
4297 castType = cast->getTypeAsWritten();
4298 CCK = CCK_CStyleCast;
4299 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
4300 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
4301 castType = cast->getTypeAsWritten();
4302 CCK = CCK_OtherCast;
4303 } else {
Akira Hatanaka2cd7e862017-05-09 01:54:51 +00004304 llvm_unreachable("Unexpected ImplicitCastExpr");
John McCall4124c492011-10-17 18:40:02 +00004305 }
4306
4307 ARCConversionTypeClass castACTC =
4308 classifyTypeForARCConversion(castType.getNonReferenceType());
4309
4310 Expr *castExpr = realCast->getSubExpr();
4311 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
4312
4313 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00004314 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00004315}
4316
4317/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
4318/// type, remove the placeholder cast.
4319Expr *Sema::stripARCUnbridgedCast(Expr *e) {
4320 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4321
4322 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
4323 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
4324 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
4325 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
4326 assert(uo->getOpcode() == UO_Extension);
4327 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
Aaron Ballmana5038552018-01-09 13:07:03 +00004328 return new (Context)
4329 UnaryOperator(sub, UO_Extension, sub->getType(), sub->getValueKind(),
4330 sub->getObjectKind(), uo->getOperatorLoc(), false);
John McCall4124c492011-10-17 18:40:02 +00004331 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
4332 assert(!gse->isResultDependent());
4333
4334 unsigned n = gse->getNumAssocs();
4335 SmallVector<Expr*, 4> subExprs(n);
4336 SmallVector<TypeSourceInfo*, 4> subTypes(n);
4337 for (unsigned i = 0; i != n; ++i) {
4338 subTypes[i] = gse->getAssocTypeSourceInfo(i);
4339 Expr *sub = gse->getAssocExpr(i);
4340 if (i == gse->getResultIndex())
4341 sub = stripARCUnbridgedCast(sub);
4342 subExprs[i] = sub;
4343 }
4344
Bruno Riccidb076832019-01-26 14:15:10 +00004345 return GenericSelectionExpr::Create(
4346 Context, gse->getGenericLoc(), gse->getControllingExpr(), subTypes,
4347 subExprs, gse->getDefaultLoc(), gse->getRParenLoc(),
4348 gse->containsUnexpandedParameterPack(), gse->getResultIndex());
John McCall4124c492011-10-17 18:40:02 +00004349 } else {
4350 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
4351 return cast<ImplicitCastExpr>(e)->getSubExpr();
4352 }
4353}
4354
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004355bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
4356 QualType exprType) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004357 QualType canCastType =
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004358 Context.getCanonicalType(castType).getUnqualifiedType();
Fangrui Song6907ce22018-07-30 19:24:48 +00004359 QualType canExprType =
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004360 Context.getCanonicalType(exprType).getUnqualifiedType();
4361 if (isa<ObjCObjectPointerType>(canCastType) &&
4362 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
4363 canExprType->isObjCObjectPointerType()) {
4364 if (const ObjCObjectPointerType *ObjT =
4365 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00004366 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4367 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004368 }
4369 return true;
4370}
4371
John McCall4db5c3c2011-07-07 06:58:02 +00004372/// Look for an ObjCReclaimReturnedObject cast and destroy it.
4373static Expr *maybeUndoReclaimObject(Expr *e) {
Akira Hatanakacc7171a2017-10-10 01:24:33 +00004374 Expr *curExpr = e, *prevExpr = nullptr;
4375
4376 // Walk down the expression until we hit an implicit cast of kind
4377 // ARCReclaimReturnedObject or an Expr that is neither a Paren nor a Cast.
4378 while (true) {
4379 if (auto *pe = dyn_cast<ParenExpr>(curExpr)) {
4380 prevExpr = curExpr;
4381 curExpr = pe->getSubExpr();
4382 continue;
4383 }
4384
4385 if (auto *ce = dyn_cast<CastExpr>(curExpr)) {
4386 if (auto *ice = dyn_cast<ImplicitCastExpr>(ce))
4387 if (ice->getCastKind() == CK_ARCReclaimReturnedObject) {
4388 if (!prevExpr)
4389 return ice->getSubExpr();
4390 if (auto *pe = dyn_cast<ParenExpr>(prevExpr))
4391 pe->setSubExpr(ice->getSubExpr());
4392 else
4393 cast<CastExpr>(prevExpr)->setSubExpr(ice->getSubExpr());
4394 return e;
4395 }
4396
4397 prevExpr = curExpr;
4398 curExpr = ce->getSubExpr();
4399 continue;
4400 }
4401
4402 // Break out of the loop if curExpr is neither a Paren nor a Cast.
4403 break;
4404 }
John McCall4db5c3c2011-07-07 06:58:02 +00004405
4406 return e;
4407}
4408
John McCall31168b02011-06-15 23:02:42 +00004409ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
4410 ObjCBridgeCastKind Kind,
4411 SourceLocation BridgeKeywordLoc,
4412 TypeSourceInfo *TSInfo,
4413 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00004414 ExprResult SubResult = UsualUnaryConversions(SubExpr);
4415 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004416 SubExpr = SubResult.get();
John McCalleb075542011-08-26 00:48:42 +00004417
John McCall31168b02011-06-15 23:02:42 +00004418 QualType T = TSInfo->getType();
4419 QualType FromType = SubExpr->getType();
4420
John McCall9320b872011-09-09 05:25:32 +00004421 CastKind CK;
4422
John McCall31168b02011-06-15 23:02:42 +00004423 bool MustConsume = false;
4424 if (T->isDependentType() || SubExpr->isTypeDependent()) {
4425 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00004426 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00004427 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
4428 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00004429 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4430 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00004431 switch (Kind) {
4432 case OBC_Bridge:
4433 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004434
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004435 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004436 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00004437 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4438 << 2
4439 << FromType
4440 << (T->isBlockPointerType()? 1 : 0)
4441 << T
4442 << SubExpr->getSourceRange()
4443 << Kind;
4444 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4445 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4446 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004447 << FromType << br
Fangrui Song6907ce22018-07-30 19:24:48 +00004448 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4449 br ? "CFBridgingRelease "
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004450 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00004451
4452 Kind = OBC_Bridge;
4453 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004454 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004455
John McCall31168b02011-06-15 23:02:42 +00004456 case OBC_BridgeTransfer:
4457 // We must consume the Objective-C object produced by the cast.
4458 MustConsume = true;
4459 break;
4460 }
4461 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4462 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00004463 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00004464 switch (Kind) {
Fariborz Jahanian214567c2014-10-28 17:26:21 +00004465 case OBC_Bridge:
4466 // Reclaiming a value that's going to be __bridge-casted to CF
4467 // is very dangerous, so we don't do it.
4468 SubExpr = maybeUndoReclaimObject(SubExpr);
4469 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004470
4471 case OBC_BridgeRetained:
John McCall31168b02011-06-15 23:02:42 +00004472 // Produce the object before casting it.
4473 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00004474 CK_ARCProduceObject,
Craig Topperc3ec1492014-05-26 06:22:03 +00004475 SubExpr, nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004476 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004477
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004478 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004479 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00004480 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4481 << (FromType->isBlockPointerType()? 1 : 0)
4482 << FromType
4483 << 2
4484 << T
4485 << SubExpr->getSourceRange()
4486 << Kind;
Fangrui Song6907ce22018-07-30 19:24:48 +00004487
John McCall31168b02011-06-15 23:02:42 +00004488 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4489 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4490 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004491 << T << br
Fangrui Song6907ce22018-07-30 19:24:48 +00004492 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004493 br ? "CFBridgingRetain " : "__bridge_retained");
Fangrui Song6907ce22018-07-30 19:24:48 +00004494
John McCall31168b02011-06-15 23:02:42 +00004495 Kind = OBC_Bridge;
4496 break;
4497 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004498 }
John McCall31168b02011-06-15 23:02:42 +00004499 } else {
4500 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4501 << FromType << T << Kind
4502 << SubExpr->getSourceRange()
4503 << TSInfo->getTypeLoc().getSourceRange();
4504 return ExprError();
4505 }
4506
John McCall9320b872011-09-09 05:25:32 +00004507 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00004508 BridgeKeywordLoc,
4509 TSInfo, SubExpr);
Fangrui Song6907ce22018-07-30 19:24:48 +00004510
John McCall31168b02011-06-15 23:02:42 +00004511 if (MustConsume) {
Tim Shen4a05bb82016-06-21 20:29:17 +00004512 Cleanup.setExprNeedsCleanups(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00004513 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
Craig Topperc3ec1492014-05-26 06:22:03 +00004514 nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004515 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004516
John McCall31168b02011-06-15 23:02:42 +00004517 return Result;
4518}
4519
4520ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4521 SourceLocation LParenLoc,
4522 ObjCBridgeCastKind Kind,
4523 SourceLocation BridgeKeywordLoc,
4524 ParsedType Type,
4525 SourceLocation RParenLoc,
4526 Expr *SubExpr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004527 TypeSourceInfo *TSInfo = nullptr;
John McCall31168b02011-06-15 23:02:42 +00004528 QualType T = GetTypeFromParser(Type, &TSInfo);
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00004529 if (Kind == OBC_Bridge)
4530 CheckTollFreeBridgeCast(T, SubExpr);
John McCall31168b02011-06-15 23:02:42 +00004531 if (!TSInfo)
4532 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
Fangrui Song6907ce22018-07-30 19:24:48 +00004533 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
John McCall31168b02011-06-15 23:02:42 +00004534 SubExpr);
4535}