blob: 65f10816924f01597616c5cba2abf43eeec18c4d [file] [log] [blame]
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for Objective-C expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnera3fc41d2008-01-04 22:32:30 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
Steve Naroff021ca182008-05-29 21:12:08 +000017#include "clang/AST/ExprObjC.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor0c78ad92010-04-21 19:57:20 +000019#include "clang/AST/TypeLoc.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
21#include "clang/Edit/Commit.h"
22#include "clang/Edit/Rewriters.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000023#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/Initialization.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/Scope.h"
27#include "clang/Sema/ScopeInfo.h"
28#include "llvm/ADT/SmallString.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000029
Chris Lattnera3fc41d2008-01-04 22:32:30 +000030using namespace clang;
John McCall5f2d5562011-02-03 09:00:02 +000031using namespace sema;
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +000032using llvm::makeArrayRef;
Chris Lattnera3fc41d2008-01-04 22:32:30 +000033
John McCallfaf5fb42010-08-26 23:41:50 +000034ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
Craig Topper883dd332015-12-24 23:58:11 +000035 ArrayRef<Expr *> Strings) {
Chris Lattnerd7670d92009-02-18 06:13:04 +000036 // Most ObjC strings are formed out of a single piece. However, we *can*
37 // have strings formed out of multiple @ strings with multiple pptokens in
38 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
39 // StringLiteral for ObjCStringLiteral to hold onto.
Craig Topper883dd332015-12-24 23:58:11 +000040 StringLiteral *S = cast<StringLiteral>(Strings[0]);
Mike Stump11289f42009-09-09 15:08:12 +000041
Chris Lattnerd7670d92009-02-18 06:13:04 +000042 // If we have a multi-part string, merge it all together.
Craig Topper883dd332015-12-24 23:58:11 +000043 if (Strings.size() != 1) {
Chris Lattnera3fc41d2008-01-04 22:32:30 +000044 // Concatenate objc strings.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000045 SmallString<128> StrBuf;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000046 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump11289f42009-09-09 15:08:12 +000047
Craig Topper883dd332015-12-24 23:58:11 +000048 for (Expr *E : Strings) {
49 S = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +000050
Douglas Gregorfb65e592011-07-27 05:40:30 +000051 // ObjC strings can't be wide or UTF.
52 if (!S->isAscii()) {
Chris Lattnerd7670d92009-02-18 06:13:04 +000053 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
54 << S->getSourceRange();
55 return true;
56 }
Mike Stump11289f42009-09-09 15:08:12 +000057
Benjamin Kramer35b077e2010-08-17 12:54:38 +000058 // Append the string.
59 StrBuf += S->getString();
Mike Stump11289f42009-09-09 15:08:12 +000060
Chris Lattner163ffd22009-02-18 06:48:40 +000061 // Get the locations of the string tokens.
62 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000063 }
Mike Stump11289f42009-09-09 15:08:12 +000064
Chris Lattner163ffd22009-02-18 06:48:40 +000065 // Create the aggregate string with the appropriate content and location
66 // information.
Benjamin Kramercdac7612014-02-25 12:26:20 +000067 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
68 assert(CAT && "String literal not of constant array type!");
69 QualType StrTy = Context.getConstantArrayType(
70 CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1),
71 CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
72 S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
73 /*Pascal=*/false, StrTy, &StrLocs[0],
74 StrLocs.size());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000075 }
Ted Kremeneke65b0862012-03-06 20:05:56 +000076
77 return BuildObjCStringLiteral(AtLocs[0], S);
78}
Mike Stump11289f42009-09-09 15:08:12 +000079
Ted Kremeneke65b0862012-03-06 20:05:56 +000080ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
Chris Lattner6436fb62009-02-18 06:01:06 +000081 // Verify that this composite string is acceptable for ObjC strings.
82 if (CheckObjCString(S))
Chris Lattnera3fc41d2008-01-04 22:32:30 +000083 return true;
Chris Lattnerfffd6a72009-02-18 06:06:56 +000084
85 // Initialize the constant string interface lazily. This assumes
Steve Naroff54e59452009-04-07 14:18:33 +000086 // the NSString interface is seen in this translation unit. Note: We
87 // don't use NSConstantString, since the runtime team considers this
88 // interface private (even though it appears in the header files).
Chris Lattnerfffd6a72009-02-18 06:06:56 +000089 QualType Ty = Context.getObjCConstantStringInterface();
90 if (!Ty.isNull()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +000091 Ty = Context.getObjCObjectPointerType(Ty);
David Blaikiebbafb8a2012-03-11 07:00:24 +000092 } else if (getLangOpts().NoConstantCFStrings) {
Craig Topperc3ec1492014-05-26 06:22:03 +000093 IdentifierInfo *NSIdent=nullptr;
David Blaikiebbafb8a2012-03-11 07:00:24 +000094 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +000095
96 if (StringClass.empty())
97 NSIdent = &Context.Idents.get("NSConstantString");
98 else
99 NSIdent = &Context.Idents.get(StringClass);
100
Ted Kremeneke65b0862012-03-06 20:05:56 +0000101 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Fariborz Jahanian07317632010-04-23 23:19:04 +0000102 LookupOrdinaryName);
103 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
104 Context.setObjCConstantStringInterface(StrIF);
105 Ty = Context.getObjCConstantStringInterface();
106 Ty = Context.getObjCObjectPointerType(Ty);
107 } else {
108 // If there is no NSConstantString interface defined then treat this
109 // as error and recover from it.
110 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
111 << S->getSourceRange();
112 Ty = Context.getObjCIdType();
113 }
Chris Lattner091f6982008-06-21 21:44:18 +0000114 } else {
Patrick Beard0caa3942012-04-19 00:25:12 +0000115 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000116 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000117 LookupOrdinaryName);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000118 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
119 Context.setObjCConstantStringInterface(StrIF);
120 Ty = Context.getObjCConstantStringInterface();
Steve Naroff7cae42b2009-07-10 23:34:53 +0000121 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000122 } else {
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000123 // If there is no NSString interface defined, implicitly declare
124 // a @class NSString; and use that instead. This is to make sure
125 // type of an NSString literal is represented correctly, instead of
126 // being an 'id' type.
127 Ty = Context.getObjCNSStringType();
128 if (Ty.isNull()) {
129 ObjCInterfaceDecl *NSStringIDecl =
130 ObjCInterfaceDecl::Create (Context,
131 Context.getTranslationUnitDecl(),
132 SourceLocation(), NSIdent,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000133 nullptr, nullptr, SourceLocation());
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000134 Ty = Context.getObjCInterfaceType(NSStringIDecl);
135 Context.setObjCNSStringType(Ty);
136 }
137 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000138 }
Chris Lattner091f6982008-06-21 21:44:18 +0000139 }
Mike Stump11289f42009-09-09 15:08:12 +0000140
Ted Kremeneke65b0862012-03-06 20:05:56 +0000141 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
142}
143
Jordy Rose08e500c2012-05-12 17:32:44 +0000144/// \brief Emits an error if the given method does not exist, or if the return
145/// type is not an Objective-C object.
146static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
147 const ObjCInterfaceDecl *Class,
148 Selector Sel, const ObjCMethodDecl *Method) {
149 if (!Method) {
150 // FIXME: Is there a better way to avoid quotes than using getName()?
151 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
152 return false;
153 }
154
155 // Make sure the return type is reasonable.
Alp Toker314cc812014-01-25 16:55:45 +0000156 QualType ReturnType = Method->getReturnType();
Jordy Rose08e500c2012-05-12 17:32:44 +0000157 if (!ReturnType->isObjCObjectPointerType()) {
158 S.Diag(Loc, diag::err_objc_literal_method_sig)
159 << Sel;
160 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
161 << ReturnType;
162 return false;
163 }
164
165 return true;
166}
167
Alex Denisovb7d85632015-07-24 05:09:40 +0000168/// \brief Maps ObjCLiteralKind to NSClassIdKindKind
169static NSAPI::NSClassIdKindKind ClassKindFromLiteralKind(
170 Sema::ObjCLiteralKind LiteralKind) {
171 switch (LiteralKind) {
172 case Sema::LK_Array:
173 return NSAPI::ClassId_NSArray;
174 case Sema::LK_Dictionary:
175 return NSAPI::ClassId_NSDictionary;
176 case Sema::LK_Numeric:
177 return NSAPI::ClassId_NSNumber;
178 case Sema::LK_String:
179 return NSAPI::ClassId_NSString;
180 case Sema::LK_Boxed:
181 return NSAPI::ClassId_NSValue;
182
183 // there is no corresponding matching
184 // between LK_None/LK_Block and NSClassIdKindKind
185 case Sema::LK_Block:
186 case Sema::LK_None:
Aaron Ballman3e839de2015-07-24 12:47:27 +0000187 break;
Alex Denisovb7d85632015-07-24 05:09:40 +0000188 }
Aaron Ballman3e839de2015-07-24 12:47:27 +0000189 llvm_unreachable("LiteralKind can't be converted into a ClassKind");
Alex Denisovb7d85632015-07-24 05:09:40 +0000190}
191
192/// \brief Validates ObjCInterfaceDecl availability.
193/// ObjCInterfaceDecl, used to create ObjC literals, should be defined
194/// if clang not in a debugger mode.
195static bool ValidateObjCLiteralInterfaceDecl(Sema &S, ObjCInterfaceDecl *Decl,
196 SourceLocation Loc,
197 Sema::ObjCLiteralKind LiteralKind) {
198 if (!Decl) {
199 NSAPI::NSClassIdKindKind Kind = ClassKindFromLiteralKind(LiteralKind);
200 IdentifierInfo *II = S.NSAPIObj->getNSClassId(Kind);
201 S.Diag(Loc, diag::err_undeclared_objc_literal_class)
202 << II->getName() << LiteralKind;
203 return false;
204 } else if (!Decl->hasDefinition() && !S.getLangOpts().DebuggerObjCLiteral) {
205 S.Diag(Loc, diag::err_undeclared_objc_literal_class)
206 << Decl->getName() << LiteralKind;
207 S.Diag(Decl->getLocation(), diag::note_forward_class);
208 return false;
209 }
210
211 return true;
212}
213
214/// \brief Looks up ObjCInterfaceDecl of a given NSClassIdKindKind.
215/// Used to create ObjC literals, such as NSDictionary (@{}),
216/// NSArray (@[]) and Boxed Expressions (@())
217static ObjCInterfaceDecl *LookupObjCInterfaceDeclForLiteral(Sema &S,
218 SourceLocation Loc,
219 Sema::ObjCLiteralKind LiteralKind) {
220 NSAPI::NSClassIdKindKind ClassKind = ClassKindFromLiteralKind(LiteralKind);
221 IdentifierInfo *II = S.NSAPIObj->getNSClassId(ClassKind);
222 NamedDecl *IF = S.LookupSingleName(S.TUScope, II, Loc,
223 Sema::LookupOrdinaryName);
224 ObjCInterfaceDecl *ID = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
225 if (!ID && S.getLangOpts().DebuggerObjCLiteral) {
226 ASTContext &Context = S.Context;
227 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
228 ID = ObjCInterfaceDecl::Create (Context, TU, SourceLocation(), II,
229 nullptr, nullptr, SourceLocation());
230 }
231
232 if (!ValidateObjCLiteralInterfaceDecl(S, ID, Loc, LiteralKind)) {
233 ID = nullptr;
234 }
235
236 return ID;
237}
238
Ted Kremeneke65b0862012-03-06 20:05:56 +0000239/// \brief Retrieve the NSNumber factory method that should be used to create
240/// an Objective-C literal for the given type.
241static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
Patrick Beard0caa3942012-04-19 00:25:12 +0000242 QualType NumberType,
243 bool isLiteral = false,
244 SourceRange R = SourceRange()) {
David Blaikie05785d12013-02-20 22:23:23 +0000245 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
246 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
247
Ted Kremeneke65b0862012-03-06 20:05:56 +0000248 if (!Kind) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000249 if (isLiteral) {
250 S.Diag(Loc, diag::err_invalid_nsnumber_type)
251 << NumberType << R;
252 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000253 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000254 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000255
Ted Kremeneke65b0862012-03-06 20:05:56 +0000256 // If we already looked up this method, we're done.
257 if (S.NSNumberLiteralMethods[*Kind])
258 return S.NSNumberLiteralMethods[*Kind];
259
260 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
261 /*Instance=*/false);
262
Patrick Beard0caa3942012-04-19 00:25:12 +0000263 ASTContext &CX = S.Context;
264
265 // Look up the NSNumber class, if we haven't done so already. It's cached
266 // in the Sema instance.
267 if (!S.NSNumberDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000268 S.NSNumberDecl = LookupObjCInterfaceDeclForLiteral(S, Loc,
269 Sema::LK_Numeric);
Patrick Beard0caa3942012-04-19 00:25:12 +0000270 if (!S.NSNumberDecl) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000271 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000272 }
Alex Denisove36748a2015-02-16 16:17:05 +0000273 }
274
275 if (S.NSNumberPointer.isNull()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000276 // generate the pointer to NSNumber type.
Jordy Roseaca01f92012-05-12 17:32:52 +0000277 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
278 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000279 }
280
Ted Kremeneke65b0862012-03-06 20:05:56 +0000281 // Look for the appropriate method within NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000282 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000283 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000284 // create a stub definition this NSNumber factory method.
Craig Topperc3ec1492014-05-26 06:22:03 +0000285 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000286 Method =
287 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
288 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
289 /*isInstance=*/false, /*isVariadic=*/false,
290 /*isPropertyAccessor=*/false,
291 /*isImplicitlyDeclared=*/true,
292 /*isDefined=*/false, ObjCMethodDecl::Required,
293 /*HasRelatedResultType=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000294 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
295 SourceLocation(), SourceLocation(),
Patrick Beard0caa3942012-04-19 00:25:12 +0000296 &CX.Idents.get("value"),
Craig Topperc3ec1492014-05-26 06:22:03 +0000297 NumberType, /*TInfo=*/nullptr,
298 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000299 Method->setMethodParams(S.Context, value, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000300 }
301
Jordy Rose08e500c2012-05-12 17:32:44 +0000302 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
Craig Topperc3ec1492014-05-26 06:22:03 +0000303 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000304
305 // Note: if the parameter type is out-of-line, we'll catch it later in the
306 // implicit conversion.
307
308 S.NSNumberLiteralMethods[*Kind] = Method;
309 return Method;
310}
311
Patrick Beard0caa3942012-04-19 00:25:12 +0000312/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
313/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremeneke65b0862012-03-06 20:05:56 +0000314ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000315 // Determine the type of the literal.
316 QualType NumberType = Number->getType();
317 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
318 // In C, character literals have type 'int'. That's not the type we want
319 // to use to determine the Objective-c literal kind.
320 switch (Char->getKind()) {
321 case CharacterLiteral::Ascii:
322 NumberType = Context.CharTy;
323 break;
324
325 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000326 NumberType = Context.getWideCharType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000327 break;
328
329 case CharacterLiteral::UTF16:
330 NumberType = Context.Char16Ty;
331 break;
332
333 case CharacterLiteral::UTF32:
334 NumberType = Context.Char32Ty;
335 break;
336 }
337 }
338
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();
357
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
364ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
365 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 {
371 // C doesn't actually have a way to represent literal values of type
372 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
373 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
374 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
375 CK_IntegralToBoolean);
376 }
377
378 return BuildObjCNumericLiteral(AtLoc, Inner.get());
379}
380
381/// \brief Check that the given expression is a valid element of an Objective-C
382/// collection literal.
383static 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
395 // In C++, check for an implicit conversion to an Objective-C object pointer
396 // 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);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000401 InitializationKind Kind
Jordy Roseaca01f92012-05-12 17:32:52 +0000402 = InitializationKind::CreateCopy(Element->getLocStart(),
403 SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000404 InitializationSequence Seq(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000405 if (!Seq.Failed())
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000406 return Seq.Perform(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000407 }
408
409 Expr *OrigElement = Element;
410
411 // Perform lvalue-to-rvalue conversion.
412 Result = S.DefaultLvalueConversion(Element);
413 if (Result.isInvalid())
414 return ExprError();
415 Element = Result.get();
416
417 // Make sure that we have an Objective-C pointer type or block.
418 if (!Element->getType()->isObjCObjectPointerType() &&
419 !Element->getType()->isBlockPointerType()) {
420 bool Recovered = false;
421
422 // If this is potentially an Objective-C numeric literal, add the '@'.
423 if (isa<IntegerLiteral>(OrigElement) ||
424 isa<CharacterLiteral>(OrigElement) ||
425 isa<FloatingLiteral>(OrigElement) ||
426 isa<ObjCBoolLiteralExpr>(OrigElement) ||
427 isa<CXXBoolLiteralExpr>(OrigElement)) {
428 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
429 int Which = isa<CharacterLiteral>(OrigElement) ? 1
430 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
431 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
432 : 3;
433
434 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
435 << Which << OrigElement->getSourceRange()
436 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
437
438 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
439 OrigElement);
440 if (Result.isInvalid())
441 return ExprError();
442
443 Element = Result.get();
444 Recovered = true;
445 }
446 }
447 // If this is potentially an Objective-C string literal, add the '@'.
448 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
449 if (String->isAscii()) {
450 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
451 << 0 << OrigElement->getSourceRange()
452 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
453
454 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
455 if (Result.isInvalid())
456 return ExprError();
457
458 Element = Result.get();
459 Recovered = true;
460 }
461 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000462
Ted Kremeneke65b0862012-03-06 20:05:56 +0000463 if (!Recovered) {
464 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
465 << Element->getType();
466 return ExprError();
467 }
468 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000469 if (ArrayLiteral)
Ted Kremenek197fee42013-10-09 22:34:33 +0000470 if (ObjCStringLiteral *getString =
471 dyn_cast<ObjCStringLiteral>(OrigElement)) {
472 if (StringLiteral *SL = getString->getString()) {
473 unsigned numConcat = SL->getNumConcatenated();
474 if (numConcat > 1) {
475 // Only warn if the concatenated string doesn't come from a macro.
476 bool hasMacro = false;
477 for (unsigned i = 0; i < numConcat ; ++i)
478 if (SL->getStrTokenLoc(i).isMacroID()) {
479 hasMacro = true;
480 break;
481 }
482 if (!hasMacro)
483 S.Diag(Element->getLocStart(),
484 diag::warn_concatenated_nsarray_literal)
485 << Element->getType();
486 }
487 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000488 }
489
Ted Kremeneke65b0862012-03-06 20:05:56 +0000490 // Make sure that the element has the type that the container factory
491 // function expects.
492 return S.PerformCopyInitialization(
493 InitializedEntity::InitializeParameter(S.Context, T,
494 /*Consumed=*/false),
495 Element->getLocStart(), Element);
496}
497
Patrick Beard0caa3942012-04-19 00:25:12 +0000498ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
499 if (ValueExpr->isTypeDependent()) {
500 ObjCBoxedExpr *BoxedExpr =
Craig Topperc3ec1492014-05-26 06:22:03 +0000501 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000502 return BoxedExpr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000503 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000504 ObjCMethodDecl *BoxingMethod = nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000505 QualType BoxedType;
506 // Convert the expression to an RValue, so we can check for pointer types...
507 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
508 if (RValue.isInvalid()) {
509 return ExprError();
510 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000511 SourceLocation Loc = SR.getBegin();
Patrick Beard0caa3942012-04-19 00:25:12 +0000512 ValueExpr = RValue.get();
Patrick Beard2565c592012-05-01 21:47:19 +0000513 QualType ValueType(ValueExpr->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +0000514 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
515 QualType PointeeType = PT->getPointeeType();
516 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
517
518 if (!NSStringDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000519 NSStringDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
520 Sema::LK_String);
Patrick Beard0caa3942012-04-19 00:25:12 +0000521 if (!NSStringDecl) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000522 return ExprError();
523 }
Jordy Roseaca01f92012-05-12 17:32:52 +0000524 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
525 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000526 }
527
528 if (!StringWithUTF8StringMethod) {
529 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
530 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
531
532 // Look for the appropriate method within NSString.
Jordy Rose08e500c2012-05-12 17:32:44 +0000533 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
534 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000535 // Debugger needs to work even if NSString hasn't been defined.
Craig Topperc3ec1492014-05-26 06:22:03 +0000536 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000537 ObjCMethodDecl *M = ObjCMethodDecl::Create(
538 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
539 NSStringPointer, ReturnTInfo, NSStringDecl,
540 /*isInstance=*/false, /*isVariadic=*/false,
541 /*isPropertyAccessor=*/false,
542 /*isImplicitlyDeclared=*/true,
543 /*isDefined=*/false, ObjCMethodDecl::Required,
544 /*HasRelatedResultType=*/false);
Jordy Roseaca01f92012-05-12 17:32:52 +0000545 QualType ConstCharType = Context.CharTy.withConst();
Patrick Beard0caa3942012-04-19 00:25:12 +0000546 ParmVarDecl *value =
547 ParmVarDecl::Create(Context, M,
548 SourceLocation(), SourceLocation(),
549 &Context.Idents.get("value"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000550 Context.getPointerType(ConstCharType),
Craig Topperc3ec1492014-05-26 06:22:03 +0000551 /*TInfo=*/nullptr,
552 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000553 M->setMethodParams(Context, value, None);
Jordy Rose08e500c2012-05-12 17:32:44 +0000554 BoxingMethod = M;
Patrick Beard0caa3942012-04-19 00:25:12 +0000555 }
Jordy Rose890f4572012-05-12 15:53:41 +0000556
Alex Denisovb7d85632015-07-24 05:09:40 +0000557 if (!validateBoxingMethod(*this, Loc, NSStringDecl,
Jordy Rose08e500c2012-05-12 17:32:44 +0000558 stringWithUTF8String, BoxingMethod))
559 return ExprError();
560
561 StringWithUTF8StringMethod = BoxingMethod;
Patrick Beard0caa3942012-04-19 00:25:12 +0000562 }
563
564 BoxingMethod = StringWithUTF8StringMethod;
565 BoxedType = NSStringPointer;
566 }
Patrick Beard2565c592012-05-01 21:47:19 +0000567 } else if (ValueType->isBuiltinType()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000568 // The other types we support are numeric, char and BOOL/bool. We could also
569 // provide limited support for structure types, such as NSRange, NSRect, and
570 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
571 // for more details.
572
573 // Check for a top-level character literal.
574 if (const CharacterLiteral *Char =
575 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
576 // In C, character literals have type 'int'. That's not the type we want
577 // to use to determine the Objective-c literal kind.
578 switch (Char->getKind()) {
579 case CharacterLiteral::Ascii:
580 ValueType = Context.CharTy;
581 break;
582
583 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000584 ValueType = Context.getWideCharType();
Patrick Beard0caa3942012-04-19 00:25:12 +0000585 break;
586
587 case CharacterLiteral::UTF16:
588 ValueType = Context.Char16Ty;
589 break;
590
591 case CharacterLiteral::UTF32:
592 ValueType = Context.Char32Ty;
593 break;
594 }
595 }
Fariborz Jahanian5d64abb2014-06-18 20:49:02 +0000596 CheckForIntOverflow(ValueExpr);
Patrick Beard0caa3942012-04-19 00:25:12 +0000597 // FIXME: Do I need to do anything special with BoolTy expressions?
598
599 // Look for the appropriate method within NSNumber.
Alex Denisovb7d85632015-07-24 05:09:40 +0000600 BoxingMethod = getNSNumberFactoryMethod(*this, Loc, ValueType);
Patrick Beard0caa3942012-04-19 00:25:12 +0000601 BoxedType = NSNumberPointer;
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000602 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
603 if (!ET->getDecl()->isComplete()) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000604 Diag(Loc, diag::err_objc_incomplete_boxed_expression_type)
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000605 << ValueType << ValueExpr->getSourceRange();
606 return ExprError();
607 }
608
Alex Denisovb7d85632015-07-24 05:09:40 +0000609 BoxingMethod = getNSNumberFactoryMethod(*this, Loc,
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000610 ET->getDecl()->getIntegerType());
611 BoxedType = NSNumberPointer;
Alex Denisovfde64952015-06-26 05:28:36 +0000612 } else if (ValueType->isObjCBoxableRecordType()) {
613 // Support for structure types, that marked as objc_boxable
614 // struct __attribute__((objc_boxable)) s { ... };
615
616 // Look up the NSValue class, if we haven't done so already. It's cached
617 // in the Sema instance.
618 if (!NSValueDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000619 NSValueDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
620 Sema::LK_Boxed);
Alex Denisovfde64952015-06-26 05:28:36 +0000621 if (!NSValueDecl) {
Alex Denisovfde64952015-06-26 05:28:36 +0000622 return ExprError();
623 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000624
Alex Denisovfde64952015-06-26 05:28:36 +0000625 // generate the pointer to NSValue type.
626 QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
627 NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
628 }
629
630 if (!ValueWithBytesObjCTypeMethod) {
631 IdentifierInfo *II[] = {
632 &Context.Idents.get("valueWithBytes"),
633 &Context.Idents.get("objCType")
634 };
635 Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
636
637 // Look for the appropriate method within NSValue.
638 BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
639 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
640 // Debugger needs to work even if NSValue hasn't been defined.
641 TypeSourceInfo *ReturnTInfo = nullptr;
642 ObjCMethodDecl *M = ObjCMethodDecl::Create(
643 Context,
644 SourceLocation(),
645 SourceLocation(),
646 ValueWithBytesObjCType,
647 NSValuePointer,
648 ReturnTInfo,
649 NSValueDecl,
650 /*isInstance=*/false,
651 /*isVariadic=*/false,
652 /*isPropertyAccessor=*/false,
653 /*isImplicitlyDeclared=*/true,
654 /*isDefined=*/false,
655 ObjCMethodDecl::Required,
656 /*HasRelatedResultType=*/false);
657
658 SmallVector<ParmVarDecl *, 2> Params;
659
660 ParmVarDecl *bytes =
661 ParmVarDecl::Create(Context, M,
662 SourceLocation(), SourceLocation(),
663 &Context.Idents.get("bytes"),
664 Context.VoidPtrTy.withConst(),
665 /*TInfo=*/nullptr,
666 SC_None, nullptr);
667 Params.push_back(bytes);
668
669 QualType ConstCharType = Context.CharTy.withConst();
670 ParmVarDecl *type =
671 ParmVarDecl::Create(Context, M,
672 SourceLocation(), SourceLocation(),
673 &Context.Idents.get("type"),
674 Context.getPointerType(ConstCharType),
675 /*TInfo=*/nullptr,
676 SC_None, nullptr);
677 Params.push_back(type);
678
679 M->setMethodParams(Context, Params, None);
680 BoxingMethod = M;
681 }
682
Alex Denisovb7d85632015-07-24 05:09:40 +0000683 if (!validateBoxingMethod(*this, Loc, NSValueDecl,
Alex Denisovfde64952015-06-26 05:28:36 +0000684 ValueWithBytesObjCType, BoxingMethod))
685 return ExprError();
686
687 ValueWithBytesObjCTypeMethod = BoxingMethod;
688 }
689
690 if (!ValueType.isTriviallyCopyableType(Context)) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000691 Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type)
Alex Denisovfde64952015-06-26 05:28:36 +0000692 << ValueType << ValueExpr->getSourceRange();
693 return ExprError();
694 }
695
696 BoxingMethod = ValueWithBytesObjCTypeMethod;
697 BoxedType = NSValuePointer;
Patrick Beard0caa3942012-04-19 00:25:12 +0000698 }
699
700 if (!BoxingMethod) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000701 Diag(Loc, diag::err_objc_illegal_boxed_expression_type)
Patrick Beard0caa3942012-04-19 00:25:12 +0000702 << ValueType << ValueExpr->getSourceRange();
703 return ExprError();
704 }
705
Alex Denisovb7d85632015-07-24 05:09:40 +0000706 DiagnoseUseOfDecl(BoxingMethod, Loc);
Alex Denisovfde64952015-06-26 05:28:36 +0000707
708 ExprResult ConvertedValueExpr;
709 if (ValueType->isObjCBoxableRecordType()) {
710 InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
711 ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
712 ValueExpr);
713 } else {
714 // Convert the expression to the type that the parameter requires.
715 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
716 InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
717 ParamDecl);
718 ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
719 ValueExpr);
720 }
721
Patrick Beard0caa3942012-04-19 00:25:12 +0000722 if (ConvertedValueExpr.isInvalid())
723 return ExprError();
724 ValueExpr = ConvertedValueExpr.get();
725
726 ObjCBoxedExpr *BoxedExpr =
727 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
728 BoxingMethod, SR);
729 return MaybeBindToTemporary(BoxedExpr);
730}
731
John McCallf2538342012-07-31 05:14:30 +0000732/// Build an ObjC subscript pseudo-object expression, given that
733/// that's supported by the runtime.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000734ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
735 Expr *IndexExpr,
736 ObjCMethodDecl *getterMethod,
737 ObjCMethodDecl *setterMethod) {
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +0000738 assert(!LangOpts.isSubscriptPointerArithmetic());
John McCall5fb5df92012-06-20 06:18:46 +0000739
John McCallf2538342012-07-31 05:14:30 +0000740 // We can't get dependent types here; our callers should have
741 // filtered them out.
742 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
743 "base or index cannot have dependent type here");
744
745 // Filter out placeholders in the index. In theory, overloads could
746 // be preserved here, although that might not actually work correctly.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000747 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
748 if (Result.isInvalid())
749 return ExprError();
750 IndexExpr = Result.get();
751
John McCallf2538342012-07-31 05:14:30 +0000752 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000753 Result = DefaultLvalueConversion(BaseExpr);
754 if (Result.isInvalid())
755 return ExprError();
756 BaseExpr = Result.get();
John McCallf2538342012-07-31 05:14:30 +0000757
758 // Build the pseudo-object expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000759 return ObjCSubscriptRefExpr::Create(Context, BaseExpr, IndexExpr,
760 Context.PseudoObjectTy, getterMethod,
761 setterMethod, RB);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000762}
763
764ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000765 SourceLocation Loc = SR.getBegin();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000766
Alex Denisovb7d85632015-07-24 05:09:40 +0000767 if (!NSArrayDecl) {
768 NSArrayDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
769 Sema::LK_Array);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000770 if (!NSArrayDecl) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000771 return ExprError();
772 }
773 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000774
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000775 // Find the arrayWithObjects:count: method, if we haven't done so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000776 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000777 if (!ArrayWithObjectsMethod) {
778 Selector
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000779 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
780 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000781 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000782 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000783 Method = ObjCMethodDecl::Create(
784 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000785 Context.getTranslationUnitDecl(), false /*Instance*/,
Alp Toker314cc812014-01-25 16:55:45 +0000786 false /*isVariadic*/,
787 /*isPropertyAccessor=*/false,
788 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
789 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000790 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000791 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000792 SourceLocation(),
793 SourceLocation(),
794 &Context.Idents.get("objects"),
795 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000796 /*TInfo=*/nullptr,
797 SC_None, nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000798 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000799 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000800 SourceLocation(),
801 SourceLocation(),
802 &Context.Idents.get("cnt"),
803 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000804 /*TInfo=*/nullptr, SC_None,
805 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000806 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000807 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000808 }
809
Alex Denisovb7d85632015-07-24 05:09:40 +0000810 if (!validateBoxingMethod(*this, Loc, NSArrayDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000811 return ExprError();
Jordy Rose08e500c2012-05-12 17:32:44 +0000812
Jordy Rose4af44872012-05-12 17:32:56 +0000813 // Dig out the type that all elements should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000814 QualType T = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000815 const PointerType *PtrT = T->getAs<PointerType>();
816 if (!PtrT ||
817 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
818 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
819 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000820 Diag(Method->parameters()[0]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000821 diag::note_objc_literal_method_param)
822 << 0 << T
823 << Context.getPointerType(IdT.withConst());
824 return ExprError();
825 }
826
827 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000828 if (!Method->parameters()[1]->getType()->isIntegerType()) {
Jordy Rose4af44872012-05-12 17:32:56 +0000829 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
830 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000831 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000832 diag::note_objc_literal_method_param)
833 << 1
Alp Toker03376dc2014-07-07 09:02:20 +0000834 << Method->parameters()[1]->getType()
Jordy Rose4af44872012-05-12 17:32:56 +0000835 << "integral";
836 return ExprError();
837 }
838
839 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rose08e500c2012-05-12 17:32:44 +0000840 ArrayWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000841 }
842
Alp Toker03376dc2014-07-07 09:02:20 +0000843 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000844 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000845
846 // Check that each of the elements provided is valid in a collection literal,
847 // performing conversions as necessary.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000848 Expr **ElementsBuffer = Elements.data();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000849 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
850 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
851 ElementsBuffer[I],
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000852 RequiredType, true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000853 if (Converted.isInvalid())
854 return ExprError();
855
856 ElementsBuffer[I] = Converted.get();
857 }
858
859 QualType Ty
860 = Context.getObjCObjectPointerType(
861 Context.getObjCInterfaceType(NSArrayDecl));
862
863 return MaybeBindToTemporary(
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000864 ObjCArrayLiteral::Create(Context, Elements, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000865 ArrayWithObjectsMethod, SR));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000866}
867
Craig Topperd4336e02015-12-24 23:58:15 +0000868ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
869 MutableArrayRef<ObjCDictionaryElement> Elements) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000870 SourceLocation Loc = SR.getBegin();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000871
Alex Denisovb7d85632015-07-24 05:09:40 +0000872 if (!NSDictionaryDecl) {
873 NSDictionaryDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
874 Sema::LK_Dictionary);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000875 if (!NSDictionaryDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000876 return ExprError();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000877 }
878 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000879
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000880 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
881 // so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000882 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000883 if (!DictionaryWithObjectsMethod) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000884 Selector Sel = NSAPIObj->getNSDictionarySelector(
885 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
886 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000887 if (!Method && getLangOpts().DebuggerObjCLiteral) {
888 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000889 SourceLocation(), SourceLocation(), Sel,
890 IdT,
Craig Topperc3ec1492014-05-26 06:22:03 +0000891 nullptr /*TypeSourceInfo */,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000892 Context.getTranslationUnitDecl(),
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000893 false /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000894 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000895 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
896 ObjCMethodDecl::Required,
897 false);
898 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000899 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000900 SourceLocation(),
901 SourceLocation(),
902 &Context.Idents.get("objects"),
903 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000904 /*TInfo=*/nullptr, SC_None,
905 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000906 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000907 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000908 SourceLocation(),
909 SourceLocation(),
910 &Context.Idents.get("keys"),
911 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000912 /*TInfo=*/nullptr, SC_None,
913 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000914 Params.push_back(keys);
Jordy Rose08e500c2012-05-12 17:32:44 +0000915 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000916 SourceLocation(),
917 SourceLocation(),
918 &Context.Idents.get("cnt"),
919 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000920 /*TInfo=*/nullptr, SC_None,
921 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000922 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000923 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000924 }
925
Jordy Rose08e500c2012-05-12 17:32:44 +0000926 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
927 Method))
928 return ExprError();
929
Jordy Rose4af44872012-05-12 17:32:56 +0000930 // Dig out the type that all values should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000931 QualType ValueT = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000932 const PointerType *PtrValue = ValueT->getAs<PointerType>();
933 if (!PtrValue ||
934 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000935 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000936 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000937 Diag(Method->parameters()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000938 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000939 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000940 << Context.getPointerType(IdT.withConst());
941 return ExprError();
942 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000943
Jordy Rose4af44872012-05-12 17:32:56 +0000944 // Dig out the type that all keys should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000945 QualType KeyT = Method->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000946 const PointerType *PtrKey = KeyT->getAs<PointerType>();
947 if (!PtrKey ||
948 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
949 IdT)) {
950 bool err = true;
951 if (PtrKey) {
952 if (QIDNSCopying.isNull()) {
953 // key argument of selector is id<NSCopying>?
954 if (ObjCProtocolDecl *NSCopyingPDecl =
955 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
956 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
957 QIDNSCopying =
Douglas Gregore9d95f12015-07-07 03:57:35 +0000958 Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { },
959 llvm::makeArrayRef(
960 (ObjCProtocolDecl**) PQ,
Douglas Gregorab209d82015-07-07 03:58:42 +0000961 1),
962 false);
Jordy Rose4af44872012-05-12 17:32:56 +0000963 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
964 }
965 }
966 if (!QIDNSCopying.isNull())
967 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
968 QIDNSCopying);
969 }
970
971 if (err) {
972 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
973 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000974 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000975 diag::note_objc_literal_method_param)
976 << 1 << KeyT
977 << Context.getPointerType(IdT.withConst());
978 return ExprError();
979 }
980 }
981
982 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000983 QualType CountType = Method->parameters()[2]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000984 if (!CountType->isIntegerType()) {
985 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
986 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000987 Diag(Method->parameters()[2]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000988 diag::note_objc_literal_method_param)
989 << 2 << CountType
990 << "integral";
991 return ExprError();
992 }
993
994 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
995 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000996 }
997
Alp Toker03376dc2014-07-07 09:02:20 +0000998 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000999 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
Alp Toker03376dc2014-07-07 09:02:20 +00001000 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +00001001 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
1002
Ted Kremeneke65b0862012-03-06 20:05:56 +00001003 // Check that each of the keys and values provided is valid in a collection
1004 // literal, performing conversions as necessary.
1005 bool HasPackExpansions = false;
Craig Topperd4336e02015-12-24 23:58:15 +00001006 for (ObjCDictionaryElement &Element : Elements) {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001007 // Check the key.
Craig Topperd4336e02015-12-24 23:58:15 +00001008 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Element.Key,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001009 KeyT);
1010 if (Key.isInvalid())
1011 return ExprError();
1012
1013 // Check the value.
1014 ExprResult Value
Craig Topperd4336e02015-12-24 23:58:15 +00001015 = CheckObjCCollectionLiteralElement(*this, Element.Value, ValueT);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001016 if (Value.isInvalid())
1017 return ExprError();
1018
Craig Topperd4336e02015-12-24 23:58:15 +00001019 Element.Key = Key.get();
1020 Element.Value = Value.get();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001021
Craig Topperd4336e02015-12-24 23:58:15 +00001022 if (Element.EllipsisLoc.isInvalid())
Ted Kremeneke65b0862012-03-06 20:05:56 +00001023 continue;
1024
Craig Topperd4336e02015-12-24 23:58:15 +00001025 if (!Element.Key->containsUnexpandedParameterPack() &&
1026 !Element.Value->containsUnexpandedParameterPack()) {
1027 Diag(Element.EllipsisLoc,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001028 diag::err_pack_expansion_without_parameter_packs)
Craig Topperd4336e02015-12-24 23:58:15 +00001029 << SourceRange(Element.Key->getLocStart(),
1030 Element.Value->getLocEnd());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001031 return ExprError();
1032 }
1033
1034 HasPackExpansions = true;
1035 }
1036
1037
1038 QualType Ty
1039 = Context.getObjCObjectPointerType(
Robert Wilhelm88e02492013-08-19 07:57:02 +00001040 Context.getObjCInterfaceType(NSDictionaryDecl));
1041 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
Craig Topperd4336e02015-12-24 23:58:15 +00001042 Context, Elements, HasPackExpansions, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +00001043 DictionaryWithObjectsMethod, SR));
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001044}
1045
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001046ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregorabd9e962010-04-20 15:39:42 +00001047 TypeSourceInfo *EncodedTypeInfo,
Anders Carlsson315d2292009-06-07 18:45:35 +00001048 SourceLocation RParenLoc) {
Douglas Gregorabd9e962010-04-20 15:39:42 +00001049 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlsson315d2292009-06-07 18:45:35 +00001050 QualType StrTy;
Mike Stump11289f42009-09-09 15:08:12 +00001051 if (EncodedType->isDependentType())
Anders Carlsson315d2292009-06-07 18:45:35 +00001052 StrTy = Context.DependentTy;
1053 else {
Fariborz Jahaniand9bc6c32011-06-16 22:34:44 +00001054 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
1055 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001056 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001057 diag::err_incomplete_type_objc_at_encode,
1058 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001059 return ExprError();
1060
Anders Carlsson315d2292009-06-07 18:45:35 +00001061 std::string Str;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00001062 QualType NotEncodedT;
1063 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
1064 if (!NotEncodedT.isNull())
1065 Diag(AtLoc, diag::warn_incomplete_encoded_type)
1066 << EncodedType << NotEncodedT;
Anders Carlsson315d2292009-06-07 18:45:35 +00001067
1068 // The type of @encode is the same as the type of the corresponding string,
1069 // which is an array type.
1070 StrTy = Context.CharTy;
1071 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001072 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlsson315d2292009-06-07 18:45:35 +00001073 StrTy.addConst();
1074 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
1075 ArrayType::Normal, 0);
1076 }
Mike Stump11289f42009-09-09 15:08:12 +00001077
Douglas Gregorabd9e962010-04-20 15:39:42 +00001078 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlsson315d2292009-06-07 18:45:35 +00001079}
1080
John McCallfaf5fb42010-08-26 23:41:50 +00001081ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1082 SourceLocation EncodeLoc,
1083 SourceLocation LParenLoc,
1084 ParsedType ty,
1085 SourceLocation RParenLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001086 // FIXME: Preserve type source info ?
Douglas Gregorabd9e962010-04-20 15:39:42 +00001087 TypeSourceInfo *TInfo;
1088 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1089 if (!TInfo)
1090 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
Craig Topper07fa1762015-11-15 02:31:46 +00001091 getLocForEndOfToken(LParenLoc));
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001092
Douglas Gregorabd9e962010-04-20 15:39:42 +00001093 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001094}
1095
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001096static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1097 SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001098 SourceLocation LParenLoc,
1099 SourceLocation RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001100 ObjCMethodDecl *Method,
1101 ObjCMethodList &MethList) {
1102 ObjCMethodList *M = &MethList;
1103 bool Warned = false;
1104 for (M = M->getNext(); M; M=M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00001105 ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001106 if (MatchingMethodDecl == Method ||
1107 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1108 MatchingMethodDecl->getSelector() != Method->getSelector())
1109 continue;
1110 if (!S.MatchTwoMethodDeclarations(Method,
1111 MatchingMethodDecl, Sema::MMS_loose)) {
1112 if (!Warned) {
1113 Warned = true;
1114 S.Diag(AtLoc, diag::warning_multiple_selectors)
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001115 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1116 << FixItHint::CreateInsertion(RParenLoc, ")");
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001117 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1118 << Method->getDeclName();
1119 }
1120 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1121 << MatchingMethodDecl->getDeclName();
1122 }
1123 }
1124 return Warned;
1125}
1126
1127static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001128 ObjCMethodDecl *Method,
1129 SourceLocation LParenLoc,
1130 SourceLocation RParenLoc,
1131 bool WarnMultipleSelectors) {
1132 if (!WarnMultipleSelectors ||
1133 S.Diags.isIgnored(diag::warning_multiple_selectors, SourceLocation()))
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001134 return;
1135 bool Warned = false;
1136 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1137 e = S.MethodPool.end(); b != e; b++) {
1138 // first, instance methods
1139 ObjCMethodList &InstMethList = b->second.first;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001140 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001141 Method, InstMethList))
1142 Warned = true;
1143
1144 // second, class methods
1145 ObjCMethodList &ClsMethList = b->second.second;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001146 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1147 Method, ClsMethList) || Warned)
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001148 return;
1149 }
1150}
1151
John McCallfaf5fb42010-08-26 23:41:50 +00001152ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1153 SourceLocation AtLoc,
1154 SourceLocation SelLoc,
1155 SourceLocation LParenLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001156 SourceLocation RParenLoc,
1157 bool WarnMultipleSelectors) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001158 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00001159 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001160 if (!Method)
1161 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian0571d9b2009-06-16 16:25:00 +00001162 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00001163 if (!Method) {
1164 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1165 Selector MatchedSel = OM->getSelector();
1166 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1167 RParenLoc.getLocWithOffset(-1));
1168 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1169 << Sel << MatchedSel
1170 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1171
1172 } else
1173 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001174 } else
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001175 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1176 WarnMultipleSelectors);
Chandler Carruth12c8f652015-03-27 00:55:05 +00001177
Fariborz Jahanian65a78b52014-05-09 19:51:39 +00001178 if (Method &&
1179 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
Chandler Carruth12c8f652015-03-27 00:55:05 +00001180 !getSourceManager().isInSystemHeader(Method->getLocation()))
1181 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001182
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001183 // In ARC, forbid the user from using @selector for
John McCall31168b02011-06-15 23:02:42 +00001184 // retain/release/autorelease/dealloc/retainCount.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001185 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001186 switch (Sel.getMethodFamily()) {
1187 case OMF_retain:
1188 case OMF_release:
1189 case OMF_autorelease:
1190 case OMF_retainCount:
1191 case OMF_dealloc:
1192 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1193 Sel << SourceRange(LParenLoc, RParenLoc);
1194 break;
1195
1196 case OMF_None:
1197 case OMF_alloc:
1198 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00001199 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00001200 case OMF_init:
1201 case OMF_mutableCopy:
1202 case OMF_new:
1203 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00001204 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001205 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001206 break;
1207 }
1208 }
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001209 QualType Ty = Context.getObjCSelType();
Daniel Dunbar45858d22010-02-03 20:11:42 +00001210 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001211}
1212
John McCallfaf5fb42010-08-26 23:41:50 +00001213ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1214 SourceLocation AtLoc,
1215 SourceLocation ProtoLoc,
1216 SourceLocation LParenLoc,
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001217 SourceLocation ProtoIdLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00001218 SourceLocation RParenLoc) {
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001219 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001220 if (!PDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001221 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001222 return true;
1223 }
Fariborz Jahaniana57d91c22014-07-25 19:45:01 +00001224 if (PDecl->hasDefinition())
1225 PDecl = PDecl->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00001226
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001227 QualType Ty = Context.getObjCProtoType();
1228 if (Ty.isNull())
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001229 return true;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001230 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001231 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001232}
1233
John McCall5f2d5562011-02-03 09:00:02 +00001234/// Try to capture an implicit reference to 'self'.
Eli Friedman24af8502012-02-03 22:47:37 +00001235ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1236 DeclContext *DC = getFunctionLevelDeclContext();
John McCall5f2d5562011-02-03 09:00:02 +00001237
1238 // If we're not in an ObjC method, error out. Note that, unlike the
1239 // C++ case, we don't require an instance method --- class methods
1240 // still have a 'self', and we really do still need to capture it!
1241 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1242 if (!method)
Craig Topperc3ec1492014-05-26 06:22:03 +00001243 return nullptr;
John McCall5f2d5562011-02-03 09:00:02 +00001244
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001245 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall5f2d5562011-02-03 09:00:02 +00001246
1247 return method;
1248}
1249
Douglas Gregor64910ca2011-09-09 20:05:21 +00001250static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
Douglas Gregor813a0662015-06-19 18:14:38 +00001251 QualType origType = T;
1252 if (auto nullability = AttributedType::stripOuterNullability(T)) {
1253 if (T == Context.getObjCInstanceType()) {
1254 return Context.getAttributedType(
1255 AttributedType::getNullabilityAttrKind(*nullability),
1256 Context.getObjCIdType(),
1257 Context.getObjCIdType());
1258 }
1259
1260 return origType;
1261 }
1262
Douglas Gregor64910ca2011-09-09 20:05:21 +00001263 if (T == Context.getObjCInstanceType())
1264 return Context.getObjCIdType();
1265
Douglas Gregor813a0662015-06-19 18:14:38 +00001266 return origType;
Douglas Gregor64910ca2011-09-09 20:05:21 +00001267}
1268
Douglas Gregor813a0662015-06-19 18:14:38 +00001269/// Determine the result type of a message send based on the receiver type,
1270/// method, and the kind of message send.
1271///
1272/// This is the "base" result type, which will still need to be adjusted
1273/// to account for nullability.
1274static QualType getBaseMessageSendResultType(Sema &S,
1275 QualType ReceiverType,
1276 ObjCMethodDecl *Method,
1277 bool isClassMessage,
1278 bool isSuperMessage) {
Douglas Gregor33823722011-06-11 01:09:30 +00001279 assert(Method && "Must have a method");
1280 if (!Method->hasRelatedResultType())
Douglas Gregore83b9562015-07-07 03:57:53 +00001281 return Method->getSendResultType(ReceiverType);
Douglas Gregor813a0662015-06-19 18:14:38 +00001282
1283 ASTContext &Context = S.Context;
1284
1285 // Local function that transfers the nullability of the method's
1286 // result type to the returned result.
1287 auto transferNullability = [&](QualType type) -> QualType {
1288 // If the method's result type has nullability, extract it.
Douglas Gregore83b9562015-07-07 03:57:53 +00001289 if (auto nullability = Method->getSendResultType(ReceiverType)
1290 ->getNullability(Context)){
Douglas Gregor813a0662015-06-19 18:14:38 +00001291 // Strip off any outer nullability sugar from the provided type.
1292 (void)AttributedType::stripOuterNullability(type);
1293
1294 // Form a new attributed type using the method result type's nullability.
1295 return Context.getAttributedType(
1296 AttributedType::getNullabilityAttrKind(*nullability),
1297 type,
1298 type);
1299 }
1300
1301 return type;
1302 };
1303
Douglas Gregor33823722011-06-11 01:09:30 +00001304 // If a method has a related return type:
1305 // - if the method found is an instance method, but the message send
1306 // was a class message send, T is the declared return type of the method
1307 // found
1308 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregore83b9562015-07-07 03:57:53 +00001309 return stripObjCInstanceType(Context,
1310 Method->getSendResultType(ReceiverType));
Douglas Gregor813a0662015-06-19 18:14:38 +00001311
1312 // - if the receiver is super, T is a pointer to the class of the
Douglas Gregor33823722011-06-11 01:09:30 +00001313 // enclosing method definition
1314 if (isSuperMessage) {
Douglas Gregor813a0662015-06-19 18:14:38 +00001315 if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
1316 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1317 return transferNullability(
1318 Context.getObjCObjectPointerType(
1319 Context.getObjCInterfaceType(Class)));
1320 }
Douglas Gregor33823722011-06-11 01:09:30 +00001321 }
Douglas Gregor813a0662015-06-19 18:14:38 +00001322
Douglas Gregor33823722011-06-11 01:09:30 +00001323 // - if the receiver is the name of a class U, T is a pointer to U
Douglas Gregore83b9562015-07-07 03:57:53 +00001324 if (ReceiverType->getAsObjCInterfaceType())
Douglas Gregor813a0662015-06-19 18:14:38 +00001325 return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
1326 // - if the receiver is of type Class or qualified Class type,
Douglas Gregor33823722011-06-11 01:09:30 +00001327 // T is the declared return type of the method.
1328 if (ReceiverType->isObjCClassType() ||
1329 ReceiverType->isObjCQualifiedClassType())
Douglas Gregore83b9562015-07-07 03:57:53 +00001330 return stripObjCInstanceType(Context,
1331 Method->getSendResultType(ReceiverType));
Douglas Gregor813a0662015-06-19 18:14:38 +00001332
Douglas Gregor33823722011-06-11 01:09:30 +00001333 // - if the receiver is id, qualified id, Class, or qualified Class, T
1334 // is the receiver type, otherwise
1335 // - T is the type of the receiver expression.
Douglas Gregor813a0662015-06-19 18:14:38 +00001336 return transferNullability(ReceiverType);
1337}
1338
1339QualType Sema::getMessageSendResultType(QualType ReceiverType,
1340 ObjCMethodDecl *Method,
1341 bool isClassMessage,
1342 bool isSuperMessage) {
1343 // Produce the result type.
1344 QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
1345 Method,
1346 isClassMessage,
1347 isSuperMessage);
1348
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001349 // If this is a class message, ignore the nullability of the receiver.
1350 if (isClassMessage)
1351 return resultType;
1352
Douglas Gregor813a0662015-06-19 18:14:38 +00001353 // Map the nullability of the result into a table index.
1354 unsigned receiverNullabilityIdx = 0;
1355 if (auto nullability = ReceiverType->getNullability(Context))
1356 receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1357
1358 unsigned resultNullabilityIdx = 0;
1359 if (auto nullability = resultType->getNullability(Context))
1360 resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1361
1362 // The table of nullability mappings, indexed by the receiver's nullability
1363 // and then the result type's nullability.
1364 static const uint8_t None = 0;
1365 static const uint8_t NonNull = 1;
1366 static const uint8_t Nullable = 2;
1367 static const uint8_t Unspecified = 3;
1368 static const uint8_t nullabilityMap[4][4] = {
1369 // None NonNull Nullable Unspecified
1370 /* None */ { None, None, Nullable, None },
1371 /* NonNull */ { None, NonNull, Nullable, Unspecified },
1372 /* Nullable */ { Nullable, Nullable, Nullable, Nullable },
1373 /* Unspecified */ { None, Unspecified, Nullable, Unspecified }
1374 };
1375
1376 unsigned newResultNullabilityIdx
1377 = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
1378 if (newResultNullabilityIdx == resultNullabilityIdx)
1379 return resultType;
1380
1381 // Strip off the existing nullability. This removes as little type sugar as
1382 // possible.
1383 do {
1384 if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
1385 resultType = attributed->getModifiedType();
1386 } else {
1387 resultType = resultType.getDesugaredType(Context);
1388 }
1389 } while (resultType->getNullability(Context));
1390
1391 // Add nullability back if needed.
1392 if (newResultNullabilityIdx > 0) {
1393 auto newNullability
1394 = static_cast<NullabilityKind>(newResultNullabilityIdx-1);
1395 return Context.getAttributedType(
1396 AttributedType::getNullabilityAttrKind(newNullability),
1397 resultType, resultType);
1398 }
1399
1400 return resultType;
Douglas Gregor33823722011-06-11 01:09:30 +00001401}
John McCall5f2d5562011-02-03 09:00:02 +00001402
John McCall5ec7e7d2013-03-19 07:04:25 +00001403/// Look for an ObjC method whose result type exactly matches the given type.
1404static const ObjCMethodDecl *
1405findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1406 QualType instancetype) {
Alp Toker314cc812014-01-25 16:55:45 +00001407 if (MD->getReturnType() == instancetype)
1408 return MD;
John McCall5ec7e7d2013-03-19 07:04:25 +00001409
1410 // For these purposes, a method in an @implementation overrides a
1411 // declaration in the @interface.
1412 if (const ObjCImplDecl *impl =
1413 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1414 const ObjCContainerDecl *iface;
1415 if (const ObjCCategoryImplDecl *catImpl =
1416 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1417 iface = catImpl->getCategoryDecl();
1418 } else {
1419 iface = impl->getClassInterface();
1420 }
1421
1422 const ObjCMethodDecl *ifaceMD =
1423 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1424 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1425 }
1426
1427 SmallVector<const ObjCMethodDecl *, 4> overrides;
1428 MD->getOverriddenMethods(overrides);
1429 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1430 if (const ObjCMethodDecl *result =
1431 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1432 return result;
1433 }
1434
Craig Topperc3ec1492014-05-26 06:22:03 +00001435 return nullptr;
John McCall5ec7e7d2013-03-19 07:04:25 +00001436}
1437
1438void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1439 // Only complain if we're in an ObjC method and the required return
1440 // type doesn't match the method's declared return type.
1441 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1442 if (!MD || !MD->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +00001443 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
John McCall5ec7e7d2013-03-19 07:04:25 +00001444 return;
1445
1446 // Look for a method overridden by this method which explicitly uses
1447 // 'instancetype'.
1448 if (const ObjCMethodDecl *overridden =
1449 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +00001450 SourceRange range = overridden->getReturnTypeSourceRange();
1451 SourceLocation loc = range.getBegin();
John McCall5ec7e7d2013-03-19 07:04:25 +00001452 if (loc.isInvalid())
1453 loc = overridden->getLocation();
1454 Diag(loc, diag::note_related_result_type_explicit)
1455 << /*current method*/ 1 << range;
1456 return;
1457 }
1458
1459 // Otherwise, if we have an interesting method family, note that.
1460 // This should always trigger if the above didn't.
1461 if (ObjCMethodFamily family = MD->getMethodFamily())
1462 Diag(MD->getLocation(), diag::note_related_result_type_family)
1463 << /*current method*/ 1
1464 << family;
1465}
1466
Douglas Gregor33823722011-06-11 01:09:30 +00001467void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1468 E = E->IgnoreParenImpCasts();
1469 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1470 if (!MsgSend)
1471 return;
1472
1473 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1474 if (!Method)
1475 return;
1476
1477 if (!Method->hasRelatedResultType())
1478 return;
Alp Toker314cc812014-01-25 16:55:45 +00001479
1480 if (Context.hasSameUnqualifiedType(
1481 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
Douglas Gregor33823722011-06-11 01:09:30 +00001482 return;
Alp Toker314cc812014-01-25 16:55:45 +00001483
1484 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
Douglas Gregorbab8a962011-09-08 01:46:34 +00001485 Context.getObjCInstanceType()))
1486 return;
1487
Douglas Gregor33823722011-06-11 01:09:30 +00001488 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1489 << Method->isInstanceMethod() << Method->getSelector()
1490 << MsgSend->getType();
1491}
1492
1493bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001494 MultiExprArg Args,
1495 Selector Sel,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001496 ArrayRef<SourceLocation> SelectorLocs,
1497 ObjCMethodDecl *Method,
Douglas Gregor33823722011-06-11 01:09:30 +00001498 bool isClassMessage, bool isSuperMessage,
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001499 SourceLocation lbrac, SourceLocation rbrac,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001500 SourceRange RecRange,
John McCall7decc9e2010-11-18 06:31:45 +00001501 QualType &ReturnType, ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001502 SourceLocation SelLoc;
1503 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1504 SelLoc = SelectorLocs.front();
1505 else
1506 SelLoc = lbrac;
1507
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001508 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001509 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001510 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001511 if (Args[i]->isTypeDependent())
1512 continue;
1513
John McCallcc5788c2013-03-04 07:34:02 +00001514 ExprResult result;
1515 if (getLangOpts().DebuggerSupport) {
1516 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001517 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001518 } else {
1519 result = DefaultArgumentPromotion(Args[i]);
1520 }
1521 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001522 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001523 Args[i] = result.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001524 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001525
John McCall31168b02011-06-15 23:02:42 +00001526 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001527 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001528 DiagID = diag::err_arc_method_not_found;
1529 else
1530 DiagID = isClassMessage ? diag::warn_class_method_not_found
1531 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001532 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001533 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahanian06499232013-06-18 17:10:58 +00001534 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001535 if (getLangOpts().ObjCAutoRefCount)
1536 DiagID = diag::error_method_not_found_with_typo;
1537 else
1538 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1539 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001540 Selector MatchedSel = OMD->getSelector();
1541 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian5ab87502014-08-12 22:16:41 +00001542 if (MatchedSel.isUnarySelector())
1543 Diag(SelLoc, DiagID)
1544 << Sel<< isClassMessage << MatchedSel
1545 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1546 else
1547 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001548 }
1549 else
1550 Diag(SelLoc, DiagID)
1551 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001552 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001553 // Find the class to which we are sending this message.
1554 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001555 if (ObjCInterfaceDecl *ThisClass =
1556 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
1557 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1558 if (!RecRange.isInvalid())
1559 if (ThisClass->lookupClassMethod(Sel))
1560 Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
1561 << FixItHint::CreateReplacement(RecRange,
1562 ThisClass->getNameAsString());
1563 }
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001564 }
1565 }
John McCall3f4138c2011-07-13 17:56:40 +00001566
1567 // In debuggers, we want to use __unknown_anytype for these
1568 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001569 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001570 ReturnType = Context.UnknownAnyTy;
1571 } else {
1572 ReturnType = Context.getObjCIdType();
1573 }
John McCall7decc9e2010-11-18 06:31:45 +00001574 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001575 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001576 }
Mike Stump11289f42009-09-09 15:08:12 +00001577
Douglas Gregor33823722011-06-11 01:09:30 +00001578 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1579 isSuperMessage);
Alp Toker314cc812014-01-25 16:55:45 +00001580 VK = Expr::getValueKindForType(Method->getReturnType());
Mike Stump11289f42009-09-09 15:08:12 +00001581
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001582 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001583 // Method might have more arguments than selector indicates. This is due
1584 // to addition of c-style arguments in method.
1585 if (Method->param_size() > Sel.getNumArgs())
1586 NumNamedArgs = Method->param_size();
1587 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001588 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001589 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001590 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001591 return false;
1592 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001593
Douglas Gregore83b9562015-07-07 03:57:53 +00001594 // Compute the set of type arguments to be substituted into each parameter
1595 // type.
1596 Optional<ArrayRef<QualType>> typeArgs
1597 = ReceiverType->getObjCSubstitutions(Method->getDeclContext());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001598 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001599 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001600 // We can't do any type-checking on a type-dependent argument.
1601 if (Args[i]->isTypeDependent())
1602 continue;
1603
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001604 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001605
Alp Toker03376dc2014-07-07 09:02:20 +00001606 ParmVarDecl *param = Method->parameters()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001607 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001608
John McCall4124c492011-10-17 18:40:02 +00001609 // Strip the unbridged-cast placeholder expression off unless it's
1610 // a consumed argument.
1611 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1612 !param->hasAttr<CFConsumedAttr>())
1613 argExpr = stripARCUnbridgedCast(argExpr);
1614
John McCallea0a39e2012-11-14 00:49:39 +00001615 // If the parameter is __unknown_anytype, infer its type
1616 // from the argument.
1617 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001618 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001619 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001620 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001621 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001622 } else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001623 Args[i] = argE.get();
John McCallea0a39e2012-11-14 00:49:39 +00001624
John McCallcc5788c2013-03-04 07:34:02 +00001625 // Update the parameter type in-place.
1626 param->setType(paramType);
1627 }
1628 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001629 }
1630
Douglas Gregore83b9562015-07-07 03:57:53 +00001631 QualType origParamType = param->getType();
1632 QualType paramType = param->getType();
1633 if (typeArgs)
1634 paramType = paramType.substObjCTypeArgs(
1635 Context,
1636 *typeArgs,
1637 ObjCSubstitutionContext::Parameter);
1638
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001639 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
Douglas Gregore83b9562015-07-07 03:57:53 +00001640 paramType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001641 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001642 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001643
Douglas Gregore83b9562015-07-07 03:57:53 +00001644 InitializedEntity Entity
1645 = InitializedEntity::InitializeParameter(Context, param, paramType);
Fariborz Jahaniana1db7df2014-07-31 17:39:50 +00001646 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001647 if (ArgE.isInvalid())
1648 IsError = true;
Douglas Gregore83b9562015-07-07 03:57:53 +00001649 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001650 Args[i] = ArgE.getAs<Expr>();
Douglas Gregore83b9562015-07-07 03:57:53 +00001651
1652 // If we are type-erasing a block to a block-compatible
1653 // Objective-C pointer type, we may need to extend the lifetime
1654 // of the block object.
1655 if (typeArgs && Args[i]->isRValue() && paramType->isBlockPointerType() &&
Bob Wilson7e9fd562015-10-02 01:05:29 +00001656 Args[i]->getType()->isBlockPointerType() &&
1657 origParamType->isObjCObjectPointerType()) {
Douglas Gregore83b9562015-07-07 03:57:53 +00001658 ExprResult arg = Args[i];
1659 maybeExtendBlockObject(arg);
1660 Args[i] = arg.get();
1661 }
1662 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001663 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001664
1665 // Promote additional arguments to variadic methods.
1666 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001667 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001668 if (Args[i]->isTypeDependent())
1669 continue;
1670
Jordy Roseaca01f92012-05-12 17:32:52 +00001671 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
Craig Topperc3ec1492014-05-26 06:22:03 +00001672 nullptr);
John Wiegley01296292011-04-08 18:41:53 +00001673 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001674 Args[i] = Arg.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001675 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001676 } else {
1677 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001678 if (Args.size() != NumNamedArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00001679 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001680 diag::err_typecheck_call_too_many_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001681 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001682 << Method->getSourceRange()
Chris Lattner3b054132008-11-19 05:08:23 +00001683 << SourceRange(Args[NumNamedArgs]->getLocStart(),
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001684 Args.back()->getLocEnd());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001685 }
1686 }
1687
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001688 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001689
1690 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001691 IsError |= CheckObjCMethodCall(
Craig Topper8c2a2a02014-08-30 16:55:39 +00001692 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001693
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001694 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001695}
1696
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001697bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001698 // 'self' is objc 'self' in an objc method only.
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001699 ObjCMethodDecl *Method =
1700 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1701 return isSelfExpr(RExpr, Method);
1702}
1703
1704bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
John McCallfe96e0b2011-11-06 09:01:30 +00001705 if (!method) return false;
1706
John McCall31168b02011-06-15 23:02:42 +00001707 receiver = receiver->IgnoreParenLValueCasts();
1708 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001709 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001710 return true;
1711 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001712}
1713
John McCall526ab472011-10-25 17:37:35 +00001714/// LookupMethodInType - Look up a method in an ObjCObjectType.
1715ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1716 bool isInstance) {
1717 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1718 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1719 // Look it up in the main interface (and categories, etc.)
1720 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1721 return method;
1722
1723 // Okay, look for "private" methods declared in any
1724 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001725 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1726 return method;
John McCall526ab472011-10-25 17:37:35 +00001727 }
1728
1729 // Check qualifiers.
Aaron Ballman1683f7b2014-03-17 15:55:30 +00001730 for (const auto *I : objType->quals())
1731 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
John McCall526ab472011-10-25 17:37:35 +00001732 return method;
1733
Craig Topperc3ec1492014-05-26 06:22:03 +00001734 return nullptr;
John McCall526ab472011-10-25 17:37:35 +00001735}
1736
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001737/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1738/// list of a qualified objective pointer type.
1739ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1740 const ObjCObjectPointerType *OPT,
1741 bool Instance)
1742{
Craig Topperc3ec1492014-05-26 06:22:03 +00001743 ObjCMethodDecl *MD = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +00001744 for (const auto *PROTO : OPT->quals()) {
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001745 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1746 return MD;
1747 }
1748 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001749 return nullptr;
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001750}
1751
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001752/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1753/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001754ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001755HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001756 Expr *BaseExpr, SourceLocation OpLoc,
1757 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001758 SourceLocation MemberLoc,
1759 SourceLocation SuperLoc, QualType SuperType,
1760 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001761 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1762 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001763
Benjamin Kramer365082d2012-05-19 16:34:46 +00001764 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001765 Diag(MemberLoc, diag::err_invalid_property_name)
1766 << MemberName << QualType(OPT, 0);
1767 return ExprError();
1768 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001769
1770 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregord6459312011-04-20 18:19:55 +00001771
Douglas Gregor4123a862011-11-14 22:10:01 +00001772 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1773 : BaseExpr->getSourceRange();
1774 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001775 diag::err_property_not_found_forward_class,
1776 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001777 return ExprError();
Douglas Gregoracf4fd32015-11-03 01:15:46 +00001778
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001779 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001780 // Check whether we can reference this property.
1781 if (DiagnoseUseOfDecl(PD, MemberLoc))
1782 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001783 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001784 return new (Context)
1785 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1786 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001787 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001788 return new (Context)
1789 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1790 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001791 }
1792 // Check protocols on qualified interfaces.
Aaron Ballman83731462014-03-17 16:14:00 +00001793 for (const auto *I : OPT->quals())
1794 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001795 // Check whether we can reference this property.
1796 if (DiagnoseUseOfDecl(PD, MemberLoc))
1797 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001798
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001799 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001800 return new (Context) ObjCPropertyRefExpr(
1801 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1802 SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001803 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001804 return new (Context)
1805 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1806 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001807 }
1808 // If that failed, look for an "implicit" property by seeing if the nullary
1809 // selector is implemented.
1810
1811 // FIXME: The logic for looking up nullary and unary selectors should be
1812 // shared with the code in ActOnInstanceMessage.
1813
1814 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1815 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001816
1817 // May be founf in property's qualified list.
1818 if (!Getter)
1819 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001820
1821 // If this reference is in an @implementation, check for 'private' methods.
1822 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001823 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001824
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001825 if (Getter) {
1826 // Check if we can reference this property.
1827 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1828 return ExprError();
1829 }
1830 // If we found a getter then this may be a valid dot-reference, we
1831 // will look for the matching setter, in case it is needed.
1832 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001833 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1834 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001835 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001836
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001837 // May be founf in property's qualified list.
1838 if (!Setter)
1839 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1840
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001841 if (!Setter) {
1842 // If this reference is in an @implementation, also check for 'private'
1843 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001844 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001845 }
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001846
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001847 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1848 return ExprError();
1849
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001850 // Special warning if member name used in a property-dot for a setter accessor
1851 // does not use a property with same name; e.g. obj.X = ... for a property with
1852 // name 'x'.
1853 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor()
1854 && !IFace->FindPropertyDeclaration(Member)) {
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001855 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
1856 // Do not warn if user is using property-dot syntax to make call to
1857 // user named setter.
1858 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001859 Diag(MemberLoc,
1860 diag::warn_property_access_suggest)
1861 << MemberName << QualType(OPT, 0) << PDecl->getName()
1862 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001863 }
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001864 }
1865
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001866 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001867 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001868 return new (Context)
1869 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1870 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001871 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001872 return new (Context)
1873 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1874 OK_ObjCProperty, MemberLoc, BaseExpr);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001875
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001876 }
1877
1878 // Attempt to correct for typos in property names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001879 if (TypoCorrection Corrected =
1880 CorrectTypo(DeclarationNameInfo(MemberName, MemberLoc),
1881 LookupOrdinaryName, nullptr, nullptr,
1882 llvm::make_unique<DeclFilterCCC<ObjCPropertyDecl>>(),
1883 CTK_ErrorRecovery, IFace, false, OPT)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001884 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1885 << MemberName << QualType(OPT, 0));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001886 DeclarationName TypoResult = Corrected.getCorrection();
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001887 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1888 TypoResult, MemberLoc,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001889 SuperLoc, SuperType, Super);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001890 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001891 ObjCInterfaceDecl *ClassDeclared;
1892 if (ObjCIvarDecl *Ivar =
1893 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1894 QualType T = Ivar->getType();
1895 if (const ObjCObjectPointerType * OBJPT =
1896 T->getAsObjCInterfacePointerType()) {
Douglas Gregor4123a862011-11-14 22:10:01 +00001897 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001898 diag::err_property_not_as_forward_class,
1899 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001900 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001901 }
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001902 Diag(MemberLoc,
1903 diag::err_ivar_access_using_property_syntax_suggest)
1904 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1905 << FixItHint::CreateReplacement(OpLoc, "->");
1906 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001907 }
Chris Lattner90c58fa2010-04-11 07:51:10 +00001908
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001909 Diag(MemberLoc, diag::err_property_not_found)
1910 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001911 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001912 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001913 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001914 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001915}
1916
1917
1918
John McCalldadc5752010-08-24 06:29:42 +00001919ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001920ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1921 IdentifierInfo &propertyName,
1922 SourceLocation receiverNameLoc,
1923 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001924
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001925 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001926 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1927 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001928
Douglas Gregore83b9562015-07-07 03:57:53 +00001929 QualType SuperType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001930 if (!IFace) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001931 // If the "receiver" is 'super' in a method, handle it as an expression-like
1932 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001933 if (receiverNamePtr->isStr("super")) {
Eli Friedman24af8502012-02-03 22:47:37 +00001934 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Douglas Gregore83b9562015-07-07 03:57:53 +00001935 if (auto classDecl = CurMethod->getClassInterface()) {
1936 SuperType = QualType(classDecl->getSuperClassType(), 0);
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001937 if (CurMethod->isInstanceMethod()) {
Douglas Gregore83b9562015-07-07 03:57:53 +00001938 if (SuperType.isNull()) {
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001939 // The current class does not have a superclass.
1940 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
Douglas Gregore83b9562015-07-07 03:57:53 +00001941 << CurMethod->getClassInterface()->getIdentifier();
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001942 return ExprError();
1943 }
Douglas Gregore83b9562015-07-07 03:57:53 +00001944 QualType T = Context.getObjCObjectPointerType(SuperType);
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001945
Douglas Gregore83b9562015-07-07 03:57:53 +00001946 return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(),
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001947 /*BaseExpr*/nullptr,
1948 SourceLocation()/*OpLoc*/,
1949 &propertyName,
1950 propertyNameLoc,
1951 receiverNameLoc, T, true);
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00001952 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001953
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001954 // Otherwise, if this is a class method, try dispatching to our
1955 // superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00001956 IFace = CurMethod->getClassInterface()->getSuperClass();
Chris Lattnera36ec422010-04-11 08:28:14 +00001957 }
Chris Lattnera36ec422010-04-11 08:28:14 +00001958 }
John McCall5f2d5562011-02-03 09:00:02 +00001959 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001960
1961 if (!IFace) {
Alp Tokerec543272013-12-24 09:48:30 +00001962 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1963 << tok::l_paren;
Chris Lattnera36ec422010-04-11 08:28:14 +00001964 return ExprError();
1965 }
1966 }
1967
1968 // Search for a declared property first.
Steve Naroff9527bbf2009-03-09 21:12:44 +00001969 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001970 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001971
1972 // If this reference is in an @implementation, check for 'private' methods.
1973 if (!Getter)
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001974 Getter = IFace->lookupPrivateClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001975
1976 if (Getter) {
1977 // FIXME: refactor/share with ActOnMemberReference().
1978 // Check if we can reference this property.
1979 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1980 return ExprError();
1981 }
Mike Stump11289f42009-09-09 15:08:12 +00001982
Steve Naroff9527bbf2009-03-09 21:12:44 +00001983 // Look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00001984 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001985 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
Douglas Gregore83b9562015-07-07 03:57:53 +00001986 PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001987 &propertyName);
Mike Stump11289f42009-09-09 15:08:12 +00001988
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001989 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001990 if (!Setter) {
1991 // If this reference is in an @implementation, also check for 'private'
1992 // methods.
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001993 Setter = IFace->lookupPrivateClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001994 }
1995 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00001996 if (!Setter)
1997 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001998
1999 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
2000 return ExprError();
2001
2002 if (Getter || Setter) {
Douglas Gregore83b9562015-07-07 03:57:53 +00002003 if (!SuperType.isNull())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002004 return new (Context)
2005 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2006 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
Douglas Gregore83b9562015-07-07 03:57:53 +00002007 SuperType);
Douglas Gregor33823722011-06-11 01:09:30 +00002008
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002009 return new (Context) ObjCPropertyRefExpr(
2010 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
2011 propertyNameLoc, receiverNameLoc, IFace);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002012 }
2013 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
2014 << &propertyName << Context.getObjCInterfaceType(IFace));
2015}
2016
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002017namespace {
2018
2019class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
2020 public:
2021 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
2022 // Determine whether "super" is acceptable in the current context.
2023 if (Method && Method->getClassInterface())
2024 WantObjCSuper = Method->getClassInterface()->getSuperClass();
2025 }
2026
Craig Toppere14c0f82014-03-12 04:55:44 +00002027 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002028 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
2029 candidate.isKeyword("super");
2030 }
2031};
2032
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002033}
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002034
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002035Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00002036 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002037 SourceLocation NameLoc,
2038 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00002039 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00002040 ParsedType &ReceiverType) {
2041 ReceiverType = ParsedType();
Douglas Gregore5798dc2010-04-21 20:38:13 +00002042
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002043 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00002044 // messaging super. If the identifier is "super" and there is a
2045 // trailing dot, it's an instance message.
2046 if (IsSuper && S->isInObjcMethodScope())
2047 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002048
2049 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
2050 LookupName(Result, S);
2051
2052 switch (Result.getResultKind()) {
2053 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00002054 // Normal name lookup didn't find anything. If we're in an
2055 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00002056 // FIXME: This is a hack. Ivar lookup should be part of normal
2057 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00002058 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00002059 if (!Method->getClassInterface()) {
2060 // Fall back: let the parser try to parse it as an instance message.
2061 return ObjCInstanceMessage;
2062 }
2063
Douglas Gregorca7136b2010-04-19 20:09:36 +00002064 ObjCInterfaceDecl *ClassDeclared;
2065 if (Method->getClassInterface()->lookupInstanceVariable(Name,
2066 ClassDeclared))
2067 return ObjCInstanceMessage;
2068 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00002069
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002070 // Break out; we'll perform typo correction below.
2071 break;
2072
2073 case LookupResult::NotFoundInCurrentInstantiation:
2074 case LookupResult::FoundOverloaded:
2075 case LookupResult::FoundUnresolvedValue:
2076 case LookupResult::Ambiguous:
2077 Result.suppressDiagnostics();
2078 return ObjCInstanceMessage;
2079
2080 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00002081 // If the identifier is a class or not, and there is a trailing dot,
2082 // it's an instance message.
2083 if (HasTrailingDot)
2084 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002085 // We found something. If it's a type, then we have a class
2086 // message. Otherwise, it's an instance message.
2087 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00002088 QualType T;
2089 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
2090 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00002091 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00002092 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00002093 DiagnoseUseOfDecl(Type, NameLoc);
2094 }
2095 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00002096 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002097
Douglas Gregore5798dc2010-04-21 20:38:13 +00002098 // We have a class message, and T is the type we're
2099 // messaging. Build source-location information for it.
2100 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00002101 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00002102 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002103 }
2104 }
2105
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002106 if (TypoCorrection Corrected = CorrectTypo(
2107 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr,
2108 llvm::make_unique<ObjCInterfaceOrSuperCCC>(getCurMethodDecl()),
2109 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002110 if (Corrected.isKeyword()) {
2111 // If we've found the keyword "super" (the only keyword that would be
2112 // returned by CorrectTypo), this is a send to super.
Richard Smithf9b15102013-08-17 00:46:16 +00002113 diagnoseTypo(Corrected,
2114 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002115 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002116 } else if (ObjCInterfaceDecl *Class =
Richard Smithf9b15102013-08-17 00:46:16 +00002117 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002118 // If we found a declaration, correct when it refers to an Objective-C
2119 // class.
Richard Smithf9b15102013-08-17 00:46:16 +00002120 diagnoseTypo(Corrected,
2121 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002122 QualType T = Context.getObjCInterfaceType(Class);
2123 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2124 ReceiverType = CreateParsedType(T, TSInfo);
2125 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002126 }
2127 }
Richard Smithf9b15102013-08-17 00:46:16 +00002128
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002129 // Fall back: let the parser try to parse it as an instance message.
2130 return ObjCInstanceMessage;
2131}
Steve Naroff9527bbf2009-03-09 21:12:44 +00002132
John McCalldadc5752010-08-24 06:29:42 +00002133ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002134 SourceLocation SuperLoc,
2135 Selector Sel,
2136 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002137 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002138 SourceLocation RBracLoc,
2139 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002140 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00002141 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00002142 if (!Method) {
2143 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
2144 return ExprError();
2145 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002146
Douglas Gregor4fdba132010-04-21 20:01:04 +00002147 ObjCInterfaceDecl *Class = Method->getClassInterface();
2148 if (!Class) {
2149 Diag(SuperLoc, diag::error_no_super_class_message)
2150 << Method->getDeclName();
2151 return ExprError();
2152 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002153
Douglas Gregore83b9562015-07-07 03:57:53 +00002154 QualType SuperTy(Class->getSuperClassType(), 0);
2155 if (SuperTy.isNull()) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002156 // The current class does not have a superclass.
Ted Kremenek499897b2011-01-23 17:21:34 +00002157 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
2158 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002159 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002160 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002161
Douglas Gregor4fdba132010-04-21 20:01:04 +00002162 // We are in a method whose class has a superclass, so 'super'
2163 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00002164 if (Method->getSelector() == Sel)
2165 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00002166
Jordan Rose2afd6612012-10-19 16:05:26 +00002167 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00002168 // Since we are in an instance method, this is an instance
2169 // message to the superclass instance.
Douglas Gregor4fdba132010-04-21 20:01:04 +00002170 SuperTy = Context.getObjCObjectPointerType(SuperTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00002171 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2172 Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002173 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002174 }
Douglas Gregor4fdba132010-04-21 20:01:04 +00002175
2176 // Since we are in a class method, this is a class message to
2177 // the superclass.
Craig Topperc3ec1492014-05-26 06:22:03 +00002178 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
Douglas Gregore83b9562015-07-07 03:57:53 +00002179 SuperTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00002180 SuperLoc, Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002181 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002182}
2183
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002184
2185ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2186 bool isSuperReceiver,
2187 SourceLocation Loc,
2188 Selector Sel,
2189 ObjCMethodDecl *Method,
2190 MultiExprArg Args) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002191 TypeSourceInfo *receiverTypeInfo = nullptr;
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002192 if (!ReceiverType.isNull())
2193 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2194
2195 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2196 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2197 Sel, Method, Loc, Loc, Loc, Args,
2198 /*isImplicit=*/true);
2199
2200}
2201
Ted Kremeneke65b0862012-03-06 20:05:56 +00002202static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2203 unsigned DiagID,
2204 bool (*refactor)(const ObjCMessageExpr *,
2205 const NSAPI &, edit::Commit &)) {
2206 SourceLocation MsgLoc = Msg->getExprLoc();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002207 if (S.Diags.isIgnored(DiagID, MsgLoc))
Ted Kremeneke65b0862012-03-06 20:05:56 +00002208 return;
2209
2210 SourceManager &SM = S.SourceMgr;
2211 edit::Commit ECommit(SM, S.LangOpts);
2212 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2213 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2214 << Msg->getSelector() << Msg->getSourceRange();
2215 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2216 if (!ECommit.isCommitable())
2217 return;
2218 for (edit::Commit::edit_iterator
2219 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2220 const edit::Commit::Edit &Edit = *I;
2221 switch (Edit.Kind) {
2222 case edit::Commit::Act_Insert:
2223 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2224 Edit.Text,
2225 Edit.BeforePrev));
2226 break;
2227 case edit::Commit::Act_InsertFromRange:
2228 Builder.AddFixItHint(
2229 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2230 Edit.getInsertFromRange(SM),
2231 Edit.BeforePrev));
2232 break;
2233 case edit::Commit::Act_Remove:
2234 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2235 break;
2236 }
2237 }
2238 }
2239}
2240
2241static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2242 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2243 edit::rewriteObjCRedundantCallWithLiteral);
2244}
2245
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002246/// \brief Diagnose use of %s directive in an NSString which is being passed
2247/// as formatting string to formatting method.
2248static void
2249DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2250 ObjCMethodDecl *Method,
2251 Selector Sel,
2252 Expr **Args, unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002253 unsigned Idx = 0;
2254 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002255 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2256 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002257 Idx = 0;
2258 Format = true;
2259 }
2260 else if (Method) {
2261 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2262 if (S.GetFormatNSStringIdx(I, Idx)) {
2263 Format = true;
2264 break;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002265 }
2266 }
2267 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002268 if (!Format || NumArgs <= Idx)
2269 return;
2270
2271 Expr *FormatExpr = Args[Idx];
2272 if (ObjCStringLiteral *OSL =
2273 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2274 StringLiteral *FormatString = OSL->getString();
2275 if (S.FormatStringHasSArg(FormatString)) {
2276 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2277 << "%s" << 0 << 0;
2278 if (Method)
2279 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2280 << Method->getDeclName();
2281 }
2282 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002283}
2284
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002285/// \brief Build an Objective-C class message expression.
2286///
2287/// This routine takes care of both normal class messages and
2288/// class messages to the superclass.
2289///
2290/// \param ReceiverTypeInfo Type source information that describes the
2291/// receiver of this message. This may be NULL, in which case we are
2292/// sending to the superclass and \p SuperLoc must be a valid source
2293/// location.
2294
2295/// \param ReceiverType The type of the object receiving the
2296/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2297/// type as that refers to. For a superclass send, this is the type of
2298/// the superclass.
2299///
2300/// \param SuperLoc The location of the "super" keyword in a
2301/// superclass message.
2302///
2303/// \param Sel The selector to which the message is being sent.
2304///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002305/// \param Method The method that this class message is invoking, if
2306/// already known.
2307///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002308/// \param LBracLoc The location of the opening square bracket ']'.
2309///
James Dennettffad8b72012-06-22 08:10:18 +00002310/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002311///
James Dennettffad8b72012-06-22 08:10:18 +00002312/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002313ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002314 QualType ReceiverType,
2315 SourceLocation SuperLoc,
2316 Selector Sel,
2317 ObjCMethodDecl *Method,
2318 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002319 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002320 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002321 MultiExprArg ArgsIn,
2322 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002323 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002324 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002325 if (LBracLoc.isInvalid()) {
2326 Diag(Loc, diag::err_missing_open_square_message_send)
2327 << FixItHint::CreateInsertion(Loc, "[");
2328 LBracLoc = Loc;
2329 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002330 SourceLocation SelLoc;
2331 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2332 SelLoc = SelectorLocs.front();
2333 else
2334 SelLoc = Loc;
2335
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002336 if (ReceiverType->isDependentType()) {
2337 // If the receiver type is dependent, we can't type-check anything
2338 // at this point. Build a dependent expression.
2339 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002340 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002341 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002342 return ObjCMessageExpr::Create(
2343 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2344 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2345 isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002346 }
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002347
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002348 // Find the class to which we are sending this message.
Craig Topperc3ec1492014-05-26 06:22:03 +00002349 ObjCInterfaceDecl *Class = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00002350 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2351 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002352 Diag(Loc, diag::err_invalid_receiver_class_message)
2353 << ReceiverType;
2354 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002355 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002356 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002357 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002358 if (!getLangOpts().CPlusPlus)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002359 (void)DiagnoseUseOfDecl(Class, SelLoc);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002360 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002361 if (!Method) {
Douglas Gregor4123a862011-11-14 22:10:01 +00002362 SourceRange TypeRange
2363 = SuperLoc.isValid()? SourceRange(SuperLoc)
2364 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002365 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002366 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002367 ? diag::err_arc_receiver_forward_class
2368 : diag::warn_receiver_forward_class),
2369 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002370 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorb5186b12010-04-22 17:01:48 +00002371 Method = LookupFactoryMethodInGlobalPool(Sel,
2372 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002373 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002374 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2375 << Method->getDeclName();
2376 }
2377 if (!Method)
2378 Method = Class->lookupClassMethod(Sel);
2379
2380 // If we have an implementation in scope, check "private" methods.
2381 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002382 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002383
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002384 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002385 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002386 }
Mike Stump11289f42009-09-09 15:08:12 +00002387
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002388 // Check the argument types and determine the result type.
2389 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002390 ExprValueKind VK = VK_RValue;
2391
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002392 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002393 Expr **Args = ArgsIn.data();
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002394 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2395 Sel, SelectorLocs,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00002396 Method, true,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002397 SuperLoc.isValid(), LBracLoc, RBracLoc,
2398 SourceRange(),
Douglas Gregor33823722011-06-11 01:09:30 +00002399 ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002400 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002401
Alp Toker314cc812014-01-25 16:55:45 +00002402 if (Method && !Method->getReturnType()->isVoidType() &&
2403 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002404 diag::err_illegal_message_expr_incomplete_type))
2405 return ExprError();
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002406
Fariborz Jahaniane8b45502014-08-22 19:52:49 +00002407 // Warn about explicit call of +initialize on its own class. But not on 'super'.
Fariborz Jahanian42292282014-08-25 21:27:38 +00002408 if (Method && Method->getMethodFamily() == OMF_initialize) {
2409 if (!SuperLoc.isValid()) {
2410 const ObjCInterfaceDecl *ID =
2411 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2412 if (ID == Class) {
2413 Diag(Loc, diag::warn_direct_initialize_call);
2414 Diag(Method->getLocation(), diag::note_method_declared_at)
2415 << Method->getDeclName();
2416 }
2417 }
2418 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2419 // [super initialize] is allowed only within an +initialize implementation
2420 if (CurMeth->getMethodFamily() != OMF_initialize) {
2421 Diag(Loc, diag::warn_direct_super_initialize_call);
2422 Diag(Method->getLocation(), diag::note_method_declared_at)
2423 << Method->getDeclName();
2424 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2425 << CurMeth->getDeclName();
2426 }
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002427 }
2428 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002429
2430 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2431
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002432 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002433 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002434 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002435 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002436 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002437 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002438 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002439 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002440 else {
John McCall7decc9e2010-11-18 06:31:45 +00002441 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002442 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002443 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002444 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002445 if (!isImplicit)
2446 checkCocoaAPI(*this, Result);
2447 }
Douglas Gregoraae38d62010-05-22 05:17:18 +00002448 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002449}
2450
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002451// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002452// ArgExprs is optional - if it is present, the number of expressions
2453// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002454ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002455 ParsedType Receiver,
2456 Selector Sel,
2457 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002458 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002459 SourceLocation RBracLoc,
2460 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002461 TypeSourceInfo *ReceiverTypeInfo;
2462 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2463 if (ReceiverType.isNull())
2464 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002465
Mike Stump11289f42009-09-09 15:08:12 +00002466
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002467 if (!ReceiverTypeInfo)
2468 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2469
2470 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002471 /*SuperLoc=*/SourceLocation(), Sel,
2472 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2473 Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002474}
2475
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002476ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2477 QualType ReceiverType,
2478 SourceLocation Loc,
2479 Selector Sel,
2480 ObjCMethodDecl *Method,
2481 MultiExprArg Args) {
2482 return BuildInstanceMessage(Receiver, ReceiverType,
2483 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2484 Sel, Method, Loc, Loc, Loc, Args,
2485 /*isImplicit=*/true);
2486}
2487
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002488/// \brief Build an Objective-C instance message expression.
2489///
2490/// This routine takes care of both normal instance messages and
2491/// instance messages to the superclass instance.
2492///
2493/// \param Receiver The expression that computes the object that will
2494/// receive this message. This may be empty, in which case we are
2495/// sending to the superclass instance and \p SuperLoc must be a valid
2496/// source location.
2497///
2498/// \param ReceiverType The (static) type of the object receiving the
2499/// message. When a \p Receiver expression is provided, this is the
2500/// same type as that expression. For a superclass instance send, this
2501/// is a pointer to the type of the superclass.
2502///
2503/// \param SuperLoc The location of the "super" keyword in a
2504/// superclass instance message.
2505///
2506/// \param Sel The selector to which the message is being sent.
2507///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002508/// \param Method The method that this instance message is invoking, if
2509/// already known.
2510///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002511/// \param LBracLoc The location of the opening square bracket ']'.
2512///
James Dennettffad8b72012-06-22 08:10:18 +00002513/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002514///
James Dennettffad8b72012-06-22 08:10:18 +00002515/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002516ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002517 QualType ReceiverType,
2518 SourceLocation SuperLoc,
2519 Selector Sel,
2520 ObjCMethodDecl *Method,
2521 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002522 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002523 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002524 MultiExprArg ArgsIn,
2525 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002526 // The location of the receiver.
2527 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002528 SourceRange RecRange =
2529 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2530 SourceLocation SelLoc;
2531 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2532 SelLoc = SelectorLocs.front();
2533 else
2534 SelLoc = Loc;
2535
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002536 if (LBracLoc.isInvalid()) {
2537 Diag(Loc, diag::err_missing_open_square_message_send)
2538 << FixItHint::CreateInsertion(Loc, "[");
2539 LBracLoc = Loc;
2540 }
2541
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002542 // If we have a receiver expression, perform appropriate promotions
2543 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002544 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002545 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002546 ExprResult Result;
2547 if (Receiver->getType() == Context.UnknownAnyTy)
2548 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2549 else
2550 Result = CheckPlaceholderExpr(Receiver);
2551 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002552 Receiver = Result.get();
John McCall4124c492011-10-17 18:40:02 +00002553 }
2554
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002555 if (Receiver->isTypeDependent()) {
2556 // If the receiver is type-dependent, we can't type-check anything
2557 // at this point. Build a dependent expression.
2558 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002559 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002560 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002561 return ObjCMessageExpr::Create(
2562 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2563 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2564 RBracLoc, isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002565 }
2566
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002567 // If necessary, apply function/array conversion to the receiver.
2568 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002569 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2570 if (Result.isInvalid())
2571 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002572 Receiver = Result.get();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002573 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002574
2575 // If the receiver is an ObjC pointer, a block pointer, or an
2576 // __attribute__((NSObject)) pointer, we don't need to do any
2577 // special conversion in order to look up a receiver.
2578 if (ReceiverType->isObjCRetainableType()) {
2579 // do nothing
2580 } else if (!getLangOpts().ObjCAutoRefCount &&
2581 !Context.getObjCIdType().isNull() &&
2582 (ReceiverType->isPointerType() ||
2583 ReceiverType->isIntegerType())) {
2584 // Implicitly convert integers and pointers to 'id' but emit a warning.
2585 // But not in ARC.
2586 Diag(Loc, diag::warn_bad_receiver_type)
2587 << ReceiverType
2588 << Receiver->getSourceRange();
2589 if (ReceiverType->isPointerType()) {
2590 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002591 CK_CPointerToObjCPointerCast).get();
John McCall80c93a02013-03-01 09:20:14 +00002592 } else {
2593 // TODO: specialized warning on null receivers?
2594 bool IsNull = Receiver->isNullPointerConstant(Context,
2595 Expr::NPC_ValueDependentIsNull);
2596 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2597 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002598 Kind).get();
John McCall80c93a02013-03-01 09:20:14 +00002599 }
2600 ReceiverType = Receiver->getType();
2601 } else if (getLangOpts().CPlusPlus) {
Douglas Gregor4b60a152013-11-07 22:34:54 +00002602 // The receiver must be a complete type.
2603 if (RequireCompleteType(Loc, Receiver->getType(),
2604 diag::err_incomplete_receiver_type))
2605 return ExprError();
2606
John McCall80c93a02013-03-01 09:20:14 +00002607 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2608 if (result.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002609 Receiver = result.get();
John McCall80c93a02013-03-01 09:20:14 +00002610 ReceiverType = Receiver->getType();
2611 }
2612 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002613 }
2614
John McCall80c93a02013-03-01 09:20:14 +00002615 // There's a somewhat weird interaction here where we assume that we
2616 // won't actually have a method unless we also don't need to do some
2617 // of the more detailed type-checking on the receiver.
2618
Douglas Gregorb5186b12010-04-22 17:01:48 +00002619 if (!Method) {
Douglas Gregorab209d82015-07-07 03:58:42 +00002620 // Handle messages to id and __kindof types (where we use the
2621 // global method pool).
2622 // FIXME: The type bound is currently ignored by lookup in the
2623 // global pool.
2624 const ObjCObjectType *typeBound = nullptr;
2625 bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
2626 typeBound);
2627 if (receiverIsIdLike || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002628 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2629 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002630 SourceRange(LBracLoc, RBracLoc),
Douglas Gregorab209d82015-07-07 03:58:42 +00002631 receiverIsIdLike);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002632 if (!Method)
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002633 Method = LookupFactoryMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002634 SourceRange(LBracLoc,RBracLoc),
Douglas Gregorab209d82015-07-07 03:58:42 +00002635 receiverIsIdLike);
Fariborz Jahanian05e77f82014-11-07 23:51:15 +00002636 if (Method) {
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002637 if (ObjCMethodDecl *BestMethod =
Fariborz Jahaniand288fad2014-08-13 23:38:04 +00002638 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002639 Method = BestMethod;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002640 if (!AreMultipleMethodsInGlobalPool(Sel, Method,
2641 SourceRange(LBracLoc, RBracLoc),
Douglas Gregorab209d82015-07-07 03:58:42 +00002642 receiverIsIdLike)) {
Sylvestre Ledru30f17082014-11-17 18:26:39 +00002643 DiagnoseUseOfDecl(Method, SelLoc);
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002644 }
Fariborz Jahanian05e77f82014-11-07 23:51:15 +00002645 }
Douglas Gregorab209d82015-07-07 03:58:42 +00002646 } else if (ReceiverType->isObjCClassOrClassKindOfType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002647 ReceiverType->isObjCQualifiedClassType()) {
2648 // Handle messages to Class.
Nico Weber2e0c8f72014-12-27 03:58:08 +00002649 // We allow sending a message to a qualified Class ("Class<foo>"), which
2650 // is ok as long as one of the protocols implements the selector (if not,
2651 // warn).
Douglas Gregorab209d82015-07-07 03:58:42 +00002652 if (!ReceiverType->isObjCClassOrClassKindOfType()) {
2653 const ObjCObjectPointerType *QClassTy
2654 = ReceiverType->getAsObjCQualifiedClassType();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002655 // Search protocols for class methods.
2656 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2657 if (!Method) {
2658 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2659 // warn if instance method found for a Class message.
2660 if (Method) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002661 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002662 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002663 Diag(Method->getLocation(), diag::note_method_declared_at)
2664 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002665 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002666 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002667 } else {
2668 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2669 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2670 // First check the public methods in the class interface.
2671 Method = ClassDecl->lookupClassMethod(Sel);
2672
2673 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002674 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002675 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002676 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002677 return ExprError();
2678 }
2679 if (!Method) {
2680 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002681 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002682 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002683 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002684 if (!Method) {
2685 // If no class (factory) method was found, check if an _instance_
2686 // method of the same name exists in the root class only.
2687 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002688 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002689 if (Method)
2690 if (const ObjCInterfaceDecl *ID =
2691 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2692 if (ID->getSuperClass())
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002693 Diag(SelLoc, diag::warn_root_inst_method_not_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002694 << Sel << SourceRange(LBracLoc, RBracLoc);
2695 }
2696 }
Fariborz Jahaniand288fad2014-08-13 23:38:04 +00002697 if (Method)
2698 if (ObjCMethodDecl *BestMethod =
2699 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
2700 Method = BestMethod;
Douglas Gregor9a129192010-04-21 00:45:42 +00002701 }
2702 }
2703 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002704 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002705 ObjCInterfaceDecl *ClassDecl = nullptr;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002706
2707 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2708 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002709 // And as long as message is not deprecated/unavailable (warn if it is).
Douglas Gregorb5186b12010-04-22 17:01:48 +00002710 if (const ObjCObjectPointerType *QIdTy
2711 = ReceiverType->getAsObjCQualifiedIdType()) {
2712 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002713 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2714 if (!Method)
2715 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002716 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002717 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002718 } else if (const ObjCObjectPointerType *OCIType
2719 = ReceiverType->getAsObjCInterfacePointerType()) {
2720 // We allow sending a message to a pointer to an interface (an object).
2721 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002722
Douglas Gregor4123a862011-11-14 22:10:01 +00002723 // Try to complete the type. Under ARC, this is a hard error from which
2724 // we don't try to recover.
Richard Smithdb0ac552015-12-18 22:40:25 +00002725 // FIXME: In the non-ARC case, this will still be a hard error if the
2726 // definition is found in a module that's not visible.
Craig Topperc3ec1492014-05-26 06:22:03 +00002727 const ObjCInterfaceDecl *forwardClass = nullptr;
Douglas Gregor4123a862011-11-14 22:10:01 +00002728 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002729 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002730 ? diag::err_arc_receiver_forward_instance
2731 : diag::warn_receiver_forward_instance,
2732 Receiver? Receiver->getSourceRange()
2733 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002734 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002735 return ExprError();
2736
2737 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanianc934de62012-02-03 01:02:44 +00002738 Diag(Receiver ? Receiver->getLocStart()
2739 : SuperLoc, diag::note_receiver_is_id);
Craig Topperc3ec1492014-05-26 06:22:03 +00002740 Method = nullptr;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002741 } else {
2742 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002743 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002744
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002745 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002746 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002747 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2748
Douglas Gregorb5186b12010-04-22 17:01:48 +00002749 if (!Method) {
2750 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002751 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002752
David Blaikiebbafb8a2012-03-11 07:00:24 +00002753 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002754 Diag(SelLoc, diag::err_arc_may_not_respond)
2755 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002756 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002757 return ExprError();
2758 }
2759
Douglas Gregor486b74e2011-09-27 16:10:05 +00002760 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002761 // If we still haven't found a method, look in the global pool. This
2762 // behavior isn't very desirable, however we need it for GCC
2763 // compatibility. FIXME: should we deviate??
2764 if (OCIType->qual_empty()) {
2765 Method = LookupInstanceMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002766 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002767 if (Method) {
2768 if (auto BestMethod =
2769 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
2770 Method = BestMethod;
2771 AreMultipleMethodsInGlobalPool(Sel, Method,
2772 SourceRange(LBracLoc, RBracLoc),
2773 true);
2774 }
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002775 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002776 Diag(SelLoc, diag::warn_maynot_respond)
2777 << OCIType->getInterfaceDecl()->getIdentifier()
2778 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002779 }
2780 }
2781 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002782 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002783 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002784 } else {
John McCall80c93a02013-03-01 09:20:14 +00002785 // Reject other random receiver types (e.g. structs).
2786 Diag(Loc, diag::err_bad_receiver_type)
2787 << ReceiverType << Receiver->getSourceRange();
2788 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002789 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002790 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002791 }
Mike Stump11289f42009-09-09 15:08:12 +00002792
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002793 FunctionScopeInfo *DIFunctionScopeInfo =
2794 (Method && Method->getMethodFamily() == OMF_init)
Craig Topperc3ec1492014-05-26 06:22:03 +00002795 ? getEnclosingFunction() : nullptr;
2796
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002797 if (DIFunctionScopeInfo &&
2798 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002799 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2800 bool isDesignatedInitChain = false;
2801 if (SuperLoc.isValid()) {
2802 if (const ObjCObjectPointerType *
2803 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2804 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
Argyrios Kyrtzidisd664a342013-12-13 03:48:17 +00002805 // Either we know this is a designated initializer or we
2806 // conservatively assume it because we don't know for sure.
2807 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2808 ID->isDesignatedInitializer(Sel)) {
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002809 isDesignatedInitChain = true;
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002810 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002811 }
2812 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002813 }
2814 }
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002815 if (!isDesignatedInitChain) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002816 const ObjCMethodDecl *InitMethod = nullptr;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002817 bool isDesignated =
2818 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2819 assert(isDesignated && InitMethod);
2820 (void)isDesignated;
2821 Diag(SelLoc, SuperLoc.isValid() ?
2822 diag::warn_objc_designated_init_non_designated_init_call :
2823 diag::warn_objc_designated_init_non_super_designated_init_call);
2824 Diag(InitMethod->getLocation(),
2825 diag::note_objc_designated_init_marked_here);
2826 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002827 }
2828
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002829 if (DIFunctionScopeInfo &&
2830 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002831 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2832 if (SuperLoc.isValid()) {
2833 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2834 } else {
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002835 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002836 }
2837 }
2838
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002839 // Check the message arguments.
2840 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002841 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002842 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002843 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00002844 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2845 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002846 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2847 Sel, SelectorLocs, Method,
Douglas Gregor33823722011-06-11 01:09:30 +00002848 ClassMessage, SuperLoc.isValid(),
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002849 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002850 return ExprError();
Alp Toker314cc812014-01-25 16:55:45 +00002851
2852 if (Method && !Method->getReturnType()->isVoidType() &&
2853 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002854 diag::err_illegal_message_expr_incomplete_type))
2855 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00002856
John McCall31168b02011-06-15 23:02:42 +00002857 // In ARC, forbid the user from sending messages to
2858 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002859 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002860 ObjCMethodFamily family =
2861 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2862 switch (family) {
2863 case OMF_init:
2864 if (Method)
2865 checkInitMethod(Method, ReceiverType);
2866
2867 case OMF_None:
2868 case OMF_alloc:
2869 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00002870 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002871 case OMF_mutableCopy:
2872 case OMF_new:
2873 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002874 case OMF_initialize:
John McCall31168b02011-06-15 23:02:42 +00002875 break;
2876
2877 case OMF_dealloc:
2878 case OMF_retain:
2879 case OMF_release:
2880 case OMF_autorelease:
2881 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002882 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2883 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00002884 break;
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002885
2886 case OMF_performSelector:
2887 if (Method && NumArgs >= 1) {
2888 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2889 Selector ArgSel = SelExp->getSelector();
2890 ObjCMethodDecl *SelMethod =
2891 LookupInstanceMethodInGlobalPool(ArgSel,
2892 SelExp->getSourceRange());
2893 if (!SelMethod)
2894 SelMethod =
2895 LookupFactoryMethodInGlobalPool(ArgSel,
2896 SelExp->getSourceRange());
2897 if (SelMethod) {
2898 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2899 switch (SelFamily) {
2900 case OMF_alloc:
2901 case OMF_copy:
2902 case OMF_mutableCopy:
2903 case OMF_new:
2904 case OMF_self:
2905 case OMF_init:
2906 // Issue error, unless ns_returns_not_retained.
2907 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2908 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002909 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002910 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002911 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2912 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002913 }
2914 break;
2915 default:
2916 // +0 call. OK. unless ns_returns_retained.
2917 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2918 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002919 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002920 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002921 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2922 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002923 }
2924 break;
2925 }
2926 }
2927 } else {
2928 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002929 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002930 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2931 }
2932 }
2933 break;
John McCall31168b02011-06-15 23:02:42 +00002934 }
2935 }
2936
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002937 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2938
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002939 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00002940 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002941 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002942 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002943 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002944 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002945 makeArrayRef(Args, NumArgs), RBracLoc,
2946 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002947 else {
John McCall7decc9e2010-11-18 06:31:45 +00002948 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002949 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002950 makeArrayRef(Args, NumArgs), RBracLoc,
2951 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002952 if (!isImplicit)
2953 checkCocoaAPI(*this, Result);
2954 }
John McCall31168b02011-06-15 23:02:42 +00002955
David Blaikiebbafb8a2012-03-11 07:00:24 +00002956 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002957 // In ARC, annotate delegate init calls.
2958 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00002959 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00002960 // Only consider init calls *directly* in init implementations,
2961 // not within blocks.
2962 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2963 if (method && method->getMethodFamily() == OMF_init) {
2964 // The implicit assignment to self means we also don't want to
2965 // consume the result.
2966 Result->setDelegateInitCall(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002967 return Result;
John McCall31168b02011-06-15 23:02:42 +00002968 }
2969 }
2970
2971 // In ARC, check for message sends which are likely to introduce
2972 // retain cycles.
2973 checkRetainCycles(Result);
Jordan Rose22487652012-10-11 16:06:21 +00002974
2975 if (!isImplicit && Method) {
2976 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2977 bool IsWeak =
2978 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2979 if (!IsWeak && Sel.isUnarySelector())
2980 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002981 if (IsWeak &&
2982 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
2983 getCurFunction()->recordUseOfWeak(Result, Prop);
Jordan Rose22487652012-10-11 16:06:21 +00002984 }
2985 }
John McCall31168b02011-06-15 23:02:42 +00002986 }
Alex Denisove1d882c2015-03-04 17:55:52 +00002987
2988 CheckObjCCircularContainer(Result);
2989
Douglas Gregoraae38d62010-05-22 05:17:18 +00002990 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002991}
2992
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002993static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2994 if (ObjCSelectorExpr *OSE =
2995 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2996 Selector Sel = OSE->getSelector();
2997 SourceLocation Loc = OSE->getAtLoc();
Chandler Carruth12c8f652015-03-27 00:55:05 +00002998 auto Pos = S.ReferencedSelectors.find(Sel);
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002999 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
3000 S.ReferencedSelectors.erase(Pos);
3001 }
3002}
3003
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003004// ActOnInstanceMessage - used for both unary and keyword messages.
3005// ArgExprs is optional - if it is present, the number of expressions
3006// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00003007ExprResult Sema::ActOnInstanceMessage(Scope *S,
3008 Expr *Receiver,
3009 Selector Sel,
3010 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00003011 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00003012 SourceLocation RBracLoc,
3013 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003014 if (!Receiver)
3015 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00003016
3017 // A ParenListExpr can show up while doing error recovery with invalid code.
3018 if (isa<ParenListExpr>(Receiver)) {
3019 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
3020 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003021 Receiver = Result.get();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00003022 }
Fariborz Jahanian17748062013-01-22 19:05:17 +00003023
3024 if (RespondsToSelectorSel.isNull()) {
3025 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
3026 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
3027 }
3028 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00003029 RemoveSelectorFromWarningCache(*this, Args[0]);
Craig Topperc3ec1492014-05-26 06:22:03 +00003030
John McCallb268a282010-08-23 23:25:46 +00003031 return BuildInstanceMessage(Receiver, Receiver->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003032 /*SuperLoc=*/SourceLocation(), Sel,
3033 /*Method=*/nullptr, LBracLoc, SelectorLocs,
3034 RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00003035}
Chris Lattner2a3569b2008-04-07 05:30:13 +00003036
John McCall31168b02011-06-15 23:02:42 +00003037enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00003038 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00003039 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00003040
3041 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00003042 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00003043
3044 /// id*, id***, void (^*)(),
3045 ACTC_indirectRetainable,
3046
3047 /// void* might be a normal C type, or it might a CF type.
3048 ACTC_voidPtr,
3049
3050 /// struct A*
3051 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00003052};
John McCalle4fe2452011-10-01 01:01:08 +00003053static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
3054 return (ACTC == ACTC_retainable ||
3055 ACTC == ACTC_coreFoundation ||
3056 ACTC == ACTC_voidPtr);
3057}
3058static bool isAnyCLike(ARCConversionTypeClass ACTC) {
3059 return ACTC == ACTC_none ||
3060 ACTC == ACTC_voidPtr ||
3061 ACTC == ACTC_coreFoundation;
3062}
3063
John McCall31168b02011-06-15 23:02:42 +00003064static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00003065 bool isIndirect = false;
John McCall31168b02011-06-15 23:02:42 +00003066
3067 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00003068 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00003069 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00003070 isIndirect = true;
3071 }
John McCall31168b02011-06-15 23:02:42 +00003072
3073 // Drill through pointers and arrays recursively.
3074 while (true) {
3075 if (const PointerType *ptr = type->getAs<PointerType>()) {
3076 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00003077
3078 // The first level of pointer may be the innermost pointer on a CF type.
3079 if (!isIndirect) {
3080 if (type->isVoidType()) return ACTC_voidPtr;
3081 if (type->isRecordType()) return ACTC_coreFoundation;
3082 }
John McCall31168b02011-06-15 23:02:42 +00003083 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
3084 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
3085 } else {
3086 break;
3087 }
John McCalle4fe2452011-10-01 01:01:08 +00003088 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00003089 }
3090
John McCalle4fe2452011-10-01 01:01:08 +00003091 if (isIndirect) {
3092 if (type->isObjCARCBridgableType())
3093 return ACTC_indirectRetainable;
3094 return ACTC_none;
3095 }
3096
3097 if (type->isObjCARCBridgableType())
3098 return ACTC_retainable;
3099
3100 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00003101}
3102
3103namespace {
John McCalle4fe2452011-10-01 01:01:08 +00003104 /// A result from the cast checker.
3105 enum ACCResult {
3106 /// Cannot be casted.
3107 ACC_invalid,
3108
3109 /// Can be safely retained or not retained.
3110 ACC_bottom,
3111
3112 /// Can be casted at +0.
3113 ACC_plusZero,
3114
3115 /// Can be casted at +1.
3116 ACC_plusOne
3117 };
3118 ACCResult merge(ACCResult left, ACCResult right) {
3119 if (left == right) return left;
3120 if (left == ACC_bottom) return right;
3121 if (right == ACC_bottom) return left;
3122 return ACC_invalid;
3123 }
3124
3125 /// A checker which white-lists certain expressions whose conversion
3126 /// to or from retainable type would otherwise be forbidden in ARC.
3127 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
3128 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
3129
John McCall31168b02011-06-15 23:02:42 +00003130 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00003131 ARCConversionTypeClass SourceClass;
3132 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003133 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00003134
3135 static bool isCFType(QualType type) {
3136 // Someday this can use ns_bridged. For now, it has to do this.
3137 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00003138 }
John McCalle4fe2452011-10-01 01:01:08 +00003139
3140 public:
3141 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003142 ARCConversionTypeClass target, bool diagnose)
3143 : Context(Context), SourceClass(source), TargetClass(target),
3144 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00003145
3146 using super::Visit;
3147 ACCResult Visit(Expr *e) {
3148 return super::Visit(e->IgnoreParens());
3149 }
3150
3151 ACCResult VisitStmt(Stmt *s) {
3152 return ACC_invalid;
3153 }
3154
3155 /// Null pointer constants can be casted however you please.
3156 ACCResult VisitExpr(Expr *e) {
3157 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
3158 return ACC_bottom;
3159 return ACC_invalid;
3160 }
3161
3162 /// Objective-C string literals can be safely casted.
3163 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3164 // If we're casting to any retainable type, go ahead. Global
3165 // strings are immune to retains, so this is bottom.
3166 if (isAnyRetainable(TargetClass)) return ACC_bottom;
3167
3168 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00003169 }
3170
John McCalle4fe2452011-10-01 01:01:08 +00003171 /// Look through certain implicit and explicit casts.
3172 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003173 switch (e->getCastKind()) {
3174 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00003175 return ACC_bottom;
3176
John McCall31168b02011-06-15 23:02:42 +00003177 case CK_NoOp:
3178 case CK_LValueToRValue:
3179 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00003180 case CK_CPointerToObjCPointerCast:
3181 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00003182 case CK_AnyPointerToBlockPointerCast:
3183 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00003184
John McCall31168b02011-06-15 23:02:42 +00003185 default:
John McCalle4fe2452011-10-01 01:01:08 +00003186 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00003187 }
3188 }
John McCalle4fe2452011-10-01 01:01:08 +00003189
3190 /// Look through unary extension.
3191 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003192 return Visit(e->getSubExpr());
3193 }
John McCalle4fe2452011-10-01 01:01:08 +00003194
3195 /// Ignore the LHS of a comma operator.
3196 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003197 return Visit(e->getRHS());
3198 }
John McCalle4fe2452011-10-01 01:01:08 +00003199
3200 /// Conditional operators are okay if both sides are okay.
3201 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3202 ACCResult left = Visit(e->getTrueExpr());
3203 if (left == ACC_invalid) return ACC_invalid;
3204 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00003205 }
John McCalle4fe2452011-10-01 01:01:08 +00003206
John McCallfe96e0b2011-11-06 09:01:30 +00003207 /// Look through pseudo-objects.
3208 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3209 // If we're getting here, we should always have a result.
3210 return Visit(e->getResultExpr());
3211 }
3212
John McCalle4fe2452011-10-01 01:01:08 +00003213 /// Statement expressions are okay if their result expression is okay.
3214 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003215 return Visit(e->getSubStmt()->body_back());
3216 }
John McCall31168b02011-06-15 23:02:42 +00003217
John McCalle4fe2452011-10-01 01:01:08 +00003218 /// Some declaration references are okay.
3219 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
John McCalle4fe2452011-10-01 01:01:08 +00003220 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
Ben Langmuir443aa4b2015-02-25 20:09:06 +00003221 // References to global constants are okay.
John McCalle4fe2452011-10-01 01:01:08 +00003222 if (isAnyRetainable(TargetClass) &&
3223 isAnyRetainable(SourceClass) &&
3224 var &&
3225 var->getStorageClass() == SC_Extern &&
Ben Langmuir443aa4b2015-02-25 20:09:06 +00003226 var->getType().isConstQualified()) {
3227
3228 // In system headers, they can also be assumed to be immune to retains.
3229 // These are things like 'kCFStringTransformToLatin'.
3230 if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
3231 return ACC_bottom;
3232
3233 return ACC_plusZero;
John McCalle4fe2452011-10-01 01:01:08 +00003234 }
3235
3236 // Nothing else.
3237 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00003238 }
John McCalle4fe2452011-10-01 01:01:08 +00003239
3240 /// Some calls are okay.
3241 ACCResult VisitCallExpr(CallExpr *e) {
3242 if (FunctionDecl *fn = e->getDirectCallee())
3243 if (ACCResult result = checkCallToFunction(fn))
3244 return result;
3245
3246 return super::VisitCallExpr(e);
3247 }
3248
3249 ACCResult checkCallToFunction(FunctionDecl *fn) {
3250 // Require a CF*Ref return type.
Alp Toker314cc812014-01-25 16:55:45 +00003251 if (!isCFType(fn->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003252 return ACC_invalid;
3253
3254 if (!isAnyRetainable(TargetClass))
3255 return ACC_invalid;
3256
3257 // Honor an explicit 'not retained' attribute.
3258 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3259 return ACC_plusZero;
3260
3261 // Honor an explicit 'retained' attribute, except that for
3262 // now we're not going to permit implicit handling of +1 results,
3263 // because it's a bit frightening.
3264 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003265 return Diagnose ? ACC_plusOne
3266 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003267
3268 // Recognize this specific builtin function, which is used by CFSTR.
3269 unsigned builtinID = fn->getBuiltinID();
3270 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3271 return ACC_bottom;
3272
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003273 // Otherwise, don't do anything implicit with an unaudited function.
3274 if (!fn->hasAttr<CFAuditedTransferAttr>())
3275 return ACC_invalid;
3276
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003277 // Otherwise, it's +0 unless it follows the create convention.
3278 if (ento::coreFoundation::followsCreateRule(fn))
3279 return Diagnose ? ACC_plusOne
3280 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003281
John McCalle4fe2452011-10-01 01:01:08 +00003282 return ACC_plusZero;
3283 }
3284
3285 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3286 return checkCallToMethod(e->getMethodDecl());
3287 }
3288
3289 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3290 ObjCMethodDecl *method;
3291 if (e->isExplicitProperty())
3292 method = e->getExplicitProperty()->getGetterMethodDecl();
3293 else
3294 method = e->getImplicitPropertyGetter();
3295 return checkCallToMethod(method);
3296 }
3297
3298 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3299 if (!method) return ACC_invalid;
3300
3301 // Check for message sends to functions returning CF types. We
3302 // just obey the Cocoa conventions with these, even though the
3303 // return type is CF.
Alp Toker314cc812014-01-25 16:55:45 +00003304 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003305 return ACC_invalid;
3306
3307 // If the method is explicitly marked not-retained, it's +0.
3308 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3309 return ACC_plusZero;
3310
3311 // If the method is explicitly marked as returning retained, or its
3312 // selector follows a +1 Cocoa convention, treat it as +1.
3313 if (method->hasAttr<CFReturnsRetainedAttr>())
3314 return ACC_plusOne;
3315
3316 switch (method->getSelector().getMethodFamily()) {
3317 case OMF_alloc:
3318 case OMF_copy:
3319 case OMF_mutableCopy:
3320 case OMF_new:
3321 return ACC_plusOne;
3322
3323 default:
3324 // Otherwise, treat it as +0.
3325 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00003326 }
3327 }
John McCalle4fe2452011-10-01 01:01:08 +00003328 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003329}
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00003330
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003331bool Sema::isKnownName(StringRef name) {
3332 if (name.empty())
3333 return false;
3334 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003335 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003336 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003337}
3338
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003339static void addFixitForObjCARCConversion(Sema &S,
3340 DiagnosticBuilder &DiagB,
3341 Sema::CheckedConversionKind CCK,
3342 SourceLocation afterLParen,
3343 QualType castType,
3344 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003345 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003346 const char *bridgeKeyword,
3347 const char *CFBridgeName) {
3348 // We handle C-style and implicit casts here.
3349 switch (CCK) {
3350 case Sema::CCK_ImplicitConversion:
3351 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003352 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003353 break;
3354 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003355 return;
3356 }
3357
3358 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003359 if (CCK == Sema::CCK_OtherCast) {
3360 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3361 SourceRange range(NCE->getOperatorLoc(),
3362 NCE->getAngleBrackets().getEnd());
3363 SmallString<32> BridgeCall;
3364
3365 SourceManager &SM = S.getSourceManager();
3366 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3367 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3368 BridgeCall += ' ';
3369
3370 BridgeCall += CFBridgeName;
3371 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3372 }
3373 return;
3374 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003375 Expr *castedE = castExpr;
3376 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3377 castedE = CCE->getSubExpr();
3378 castedE = castedE->IgnoreImpCasts();
3379 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00003380
3381 SmallString<32> BridgeCall;
3382
3383 SourceManager &SM = S.getSourceManager();
3384 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3385 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3386 BridgeCall += ' ';
3387
3388 BridgeCall += CFBridgeName;
3389
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003390 if (isa<ParenExpr>(castedE)) {
3391 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003392 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003393 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00003394 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003395 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003396 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003397 DiagB.AddFixItHint(FixItHint::CreateInsertion(
Craig Topper07fa1762015-11-15 02:31:46 +00003398 S.getLocForEndOfToken(range.getEnd()),
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003399 ")"));
3400 }
3401 return;
3402 }
3403
3404 if (CCK == Sema::CCK_CStyleCast) {
3405 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003406 } else if (CCK == Sema::CCK_OtherCast) {
3407 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3408 std::string castCode = "(";
3409 castCode += bridgeKeyword;
3410 castCode += castType.getAsString();
3411 castCode += ")";
3412 SourceRange Range(NCE->getOperatorLoc(),
3413 NCE->getAngleBrackets().getEnd());
3414 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3415 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003416 } else {
3417 std::string castCode = "(";
3418 castCode += bridgeKeyword;
3419 castCode += castType.getAsString();
3420 castCode += ")";
3421 Expr *castedE = castExpr->IgnoreImpCasts();
3422 SourceRange range = castedE->getSourceRange();
3423 if (isa<ParenExpr>(castedE)) {
3424 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3425 castCode));
3426 } else {
3427 castCode += "(";
3428 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3429 castCode));
3430 DiagB.AddFixItHint(FixItHint::CreateInsertion(
Craig Topper07fa1762015-11-15 02:31:46 +00003431 S.getLocForEndOfToken(range.getEnd()),
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003432 ")"));
3433 }
3434 }
3435}
3436
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003437template <typename T>
3438static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3439 TypedefNameDecl *TDNDecl = TD->getDecl();
3440 QualType QT = TDNDecl->getUnderlyingType();
3441 if (QT->isPointerType()) {
3442 QT = QT->getPointeeType();
3443 if (const RecordType *RT = QT->getAs<RecordType>())
Fariborz Jahanian9af6a782014-06-11 19:10:46 +00003444 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
Aaron Ballman2084f8f2013-12-19 13:20:36 +00003445 return RD->getAttr<T>();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003446 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003447 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003448}
3449
3450static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3451 TypedefNameDecl *&TDNDecl) {
3452 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3453 TDNDecl = TD->getDecl();
3454 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3455 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3456 return ObjCBAttr;
3457 T = TDNDecl->getUnderlyingType();
3458 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003459 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003460}
3461
John McCall4124c492011-10-17 18:40:02 +00003462static void
3463diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3464 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003465 Expr *castExpr, Expr *realCast,
3466 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003467 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003468 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003469 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00003470
John McCall4124c492011-10-17 18:40:02 +00003471 if (S.makeUnavailableInSystemHeader(loc,
John McCallc6af8c62015-10-28 05:03:19 +00003472 UnavailableAttr::IR_ARCForbiddenConversion))
John McCall31168b02011-06-15 23:02:42 +00003473 return;
John McCall4124c492011-10-17 18:40:02 +00003474
3475 QualType castExprType = castExpr->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003476 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003477 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3478 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3479 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
Fariborz Jahanian1ad83a32014-06-18 23:22:38 +00003480 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003481 return;
John McCall31168b02011-06-15 23:02:42 +00003482
John McCall640767f2011-06-17 06:50:50 +00003483 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003484 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003485 case ACTC_none:
3486 case ACTC_coreFoundation:
3487 case ACTC_voidPtr:
3488 srcKind = (castExprType->isPointerType() ? 1 : 0);
3489 break;
3490 case ACTC_retainable:
3491 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3492 break;
3493 case ACTC_indirectRetainable:
3494 srcKind = 4;
3495 break;
John McCall31168b02011-06-15 23:02:42 +00003496 }
3497
John McCall4124c492011-10-17 18:40:02 +00003498 // Check whether this could be fixed with a bridge cast.
Craig Topper07fa1762015-11-15 02:31:46 +00003499 SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin());
John McCall4124c492011-10-17 18:40:02 +00003500 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003501
John McCall4124c492011-10-17 18:40:02 +00003502 // Bridge from an ARC type to a CF type.
3503 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003504
John McCall4124c492011-10-17 18:40:02 +00003505 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3506 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3507 << 2 // of C pointer type
3508 << castExprType
3509 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3510 << castType
3511 << castRange
3512 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003513 bool br = S.isKnownName("CFBridgingRelease");
Jordan Rose4502b532012-07-31 01:07:43 +00003514 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003515 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003516 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003517 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003518 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003519 DiagnosticBuilder DiagB =
3520 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3521 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Craig Topperc3ec1492014-05-26 06:22:03 +00003522
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003523 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003524 castType, castExpr, realCast, "__bridge ",
3525 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003526 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003527 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003528 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003529 DiagnosticBuilder DiagB =
3530 (CCK == Sema::CCK_OtherCast && !br) ?
3531 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3532 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3533 diag::note_arc_bridge_transfer)
3534 << castExprType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003535
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003536 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003537 castType, castExpr, realCast, "__bridge_transfer ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003538 br ? "CFBridgingRelease" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003539 }
John McCall4124c492011-10-17 18:40:02 +00003540
3541 return;
3542 }
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003543
John McCall4124c492011-10-17 18:40:02 +00003544 // Bridge from a CF type to an ARC type.
3545 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003546 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003547 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3548 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3549 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3550 << castExprType
3551 << 2 // to C pointer type
3552 << castType
3553 << castRange
3554 << castExpr->getSourceRange();
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003555 ACCResult CreateRule =
3556 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003557 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003558 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003559 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003560 DiagnosticBuilder DiagB =
3561 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3562 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003563 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003564 castType, castExpr, realCast, "__bridge ",
3565 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003566 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003567 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003568 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003569 DiagnosticBuilder DiagB =
3570 (CCK == Sema::CCK_OtherCast && !br) ?
3571 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3572 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3573 diag::note_arc_bridge_retained)
3574 << castType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003575
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003576 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003577 castType, castExpr, realCast, "__bridge_retained ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003578 br ? "CFBridgingRetain" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003579 }
John McCall4124c492011-10-17 18:40:02 +00003580
3581 return;
John McCall31168b02011-06-15 23:02:42 +00003582 }
3583
John McCall4124c492011-10-17 18:40:02 +00003584 S.Diag(loc, diag::err_arc_mismatched_cast)
3585 << (CCK != Sema::CCK_ImplicitConversion)
3586 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003587 << castRange << castExpr->getSourceRange();
3588}
3589
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003590template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003591static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3592 bool &HadTheAttribute, bool warn) {
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003593 QualType T = castExpr->getType();
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003594 HadTheAttribute = false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003595 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3596 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003597 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003598 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003599 HadTheAttribute = true;
Fariborz Jahanianc9e266b2014-12-11 22:56:26 +00003600 if (Parm->isStr("id"))
3601 return true;
3602
Craig Topperc3ec1492014-05-26 06:22:03 +00003603 NamedDecl *Target = nullptr;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003604 // Check for an existing type with this name.
3605 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3606 Sema::LookupOrdinaryName);
3607 if (S.LookupName(R, S.TUScope)) {
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003608 Target = R.getFoundDecl();
3609 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3610 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3611 if (const ObjCObjectPointerType *InterfacePointerType =
3612 castType->getAsObjCInterfacePointerType()) {
3613 ObjCInterfaceDecl *CastClass
3614 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003615 if ((CastClass == ExprClass) ||
Fariborz Jahanian27aa9b42015-04-10 22:07:47 +00003616 (CastClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003617 return true;
3618 if (warn)
3619 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3620 << T << Target->getName() << castType->getPointeeType();
3621 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003622 } else if (castType->isObjCIdType() ||
3623 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3624 castType, ExprClass)))
3625 // ok to cast to 'id'.
3626 // casting to id<p-list> is ok if bridge type adopts all of
3627 // p-list protocols.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003628 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003629 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003630 if (warn) {
3631 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3632 << T << Target->getName() << castType;
3633 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3634 S.Diag(Target->getLocStart(), diag::note_declared_at);
3635 }
3636 return false;
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003637 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003638 }
Fariborz Jahanian696c8872015-04-09 23:39:53 +00003639 } else if (!castType->isObjCIdType()) {
3640 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
3641 << castExpr->getType() << Parm;
3642 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3643 if (Target)
3644 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003645 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003646 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003647 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003648 return false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003649 }
3650 T = TDNDecl->getUnderlyingType();
3651 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003652 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003653}
3654
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003655template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003656static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3657 bool &HadTheAttribute, bool warn) {
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003658 QualType T = castType;
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003659 HadTheAttribute = false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003660 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3661 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003662 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003663 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003664 HadTheAttribute = true;
John McCallaf6b3f82015-03-10 18:41:23 +00003665 if (Parm->isStr("id"))
3666 return true;
3667
Craig Topperc3ec1492014-05-26 06:22:03 +00003668 NamedDecl *Target = nullptr;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003669 // Check for an existing type with this name.
3670 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3671 Sema::LookupOrdinaryName);
3672 if (S.LookupName(R, S.TUScope)) {
3673 Target = R.getFoundDecl();
3674 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3675 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3676 if (const ObjCObjectPointerType *InterfacePointerType =
3677 castExpr->getType()->getAsObjCInterfacePointerType()) {
3678 ObjCInterfaceDecl *ExprClass
3679 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003680 if ((CastClass == ExprClass) ||
3681 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003682 return true;
3683 if (warn) {
3684 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3685 << castExpr->getType()->getPointeeType() << T;
3686 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3687 }
3688 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003689 } else if (castExpr->getType()->isObjCIdType() ||
3690 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3691 castExpr->getType(), CastClass)))
3692 // ok to cast an 'id' expression to a CFtype.
3693 // ok to cast an 'id<plist>' expression to CFtype provided plist
3694 // adopts all of CFtype's ObjetiveC's class plist.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003695 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003696 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003697 if (warn) {
3698 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3699 << castExpr->getType() << castType;
3700 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3701 S.Diag(Target->getLocStart(), diag::note_declared_at);
3702 }
3703 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003704 }
3705 }
3706 }
3707 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3708 << castExpr->getType() << castType;
3709 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3710 if (Target)
3711 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003712 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003713 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003714 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003715 }
3716 T = TDNDecl->getUnderlyingType();
3717 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003718 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003719}
3720
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003721void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003722 if (!getLangOpts().ObjC1)
3723 return;
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003724 // warn in presence of __bridge casting to or from a toll free bridge cast.
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003725 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3726 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003727 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003728 bool HasObjCBridgeAttr;
3729 bool ObjCBridgeAttrWillNotWarn =
3730 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3731 false);
3732 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3733 return;
3734 bool HasObjCBridgeMutableAttr;
3735 bool ObjCBridgeMutableAttrWillNotWarn =
3736 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3737 HasObjCBridgeMutableAttr, false);
3738 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3739 return;
3740
3741 if (HasObjCBridgeAttr)
3742 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3743 true);
3744 else if (HasObjCBridgeMutableAttr)
3745 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3746 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003747 }
3748 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003749 bool HasObjCBridgeAttr;
3750 bool ObjCBridgeAttrWillNotWarn =
3751 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3752 false);
3753 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3754 return;
3755 bool HasObjCBridgeMutableAttr;
3756 bool ObjCBridgeMutableAttrWillNotWarn =
3757 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3758 HasObjCBridgeMutableAttr, false);
3759 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3760 return;
3761
3762 if (HasObjCBridgeAttr)
3763 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3764 true);
3765 else if (HasObjCBridgeMutableAttr)
3766 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3767 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003768 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003769}
3770
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003771void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3772 QualType SrcType = castExpr->getType();
3773 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3774 if (PRE->isExplicitProperty()) {
3775 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3776 SrcType = PDecl->getType();
3777 }
3778 else if (PRE->isImplicitProperty()) {
3779 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3780 SrcType = Getter->getReturnType();
3781
3782 }
3783 }
3784
3785 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3786 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3787 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3788 return;
3789 CheckObjCBridgeRelatedConversions(castExpr->getLocStart(),
3790 castType, SrcType, castExpr);
3791 return;
3792}
3793
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00003794bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3795 CastKind &Kind) {
3796 if (!getLangOpts().ObjC1)
3797 return false;
3798 ARCConversionTypeClass exprACTC =
3799 classifyTypeForARCConversion(castExpr->getType());
3800 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3801 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3802 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3803 CheckTollFreeBridgeCast(castType, castExpr);
3804 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3805 : CK_CPointerToObjCPointerCast;
3806 return true;
3807 }
3808 return false;
3809}
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003810
3811bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3812 QualType DestType, QualType SrcType,
3813 ObjCInterfaceDecl *&RelatedClass,
3814 ObjCMethodDecl *&ClassMethod,
3815 ObjCMethodDecl *&InstanceMethod,
3816 TypedefNameDecl *&TDNDecl,
3817 bool CfToNs) {
3818 QualType T = CfToNs ? SrcType : DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003819 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3820 if (!ObjCBAttr)
3821 return false;
3822
3823 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3824 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3825 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3826 if (!RCId)
3827 return false;
Craig Topperc3ec1492014-05-26 06:22:03 +00003828 NamedDecl *Target = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003829 // Check for an existing type with this name.
3830 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3831 Sema::LookupOrdinaryName);
3832 if (!LookupName(R, TUScope)) {
3833 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003834 << SrcType << DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003835 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3836 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003837 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003838 Target = R.getFoundDecl();
3839 if (Target && isa<ObjCInterfaceDecl>(Target))
3840 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3841 else {
3842 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3843 << SrcType << DestType;
3844 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3845 if (Target)
3846 Diag(Target->getLocStart(), diag::note_declared_at);
3847 return false;
3848 }
3849
3850 // Check for an existing class method with the given selector name.
3851 if (CfToNs && CMId) {
3852 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3853 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3854 if (!ClassMethod) {
3855 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003856 << SrcType << DestType << Sel << false;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003857 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3858 return false;
3859 }
3860 }
3861
3862 // Check for an existing instance method with the given selector name.
3863 if (!CfToNs && IMId) {
3864 Selector Sel = Context.Selectors.getNullarySelector(IMId);
3865 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3866 if (!InstanceMethod) {
3867 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003868 << SrcType << DestType << Sel << true;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003869 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3870 return false;
3871 }
3872 }
3873 return true;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003874}
3875
3876bool
3877Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003878 QualType DestType, QualType SrcType,
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003879 Expr *&SrcExpr) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003880 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3881 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3882 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3883 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3884 if (!CfToNs && !NsToCf)
3885 return false;
3886
3887 ObjCInterfaceDecl *RelatedClass;
Craig Topperc3ec1492014-05-26 06:22:03 +00003888 ObjCMethodDecl *ClassMethod = nullptr;
3889 ObjCMethodDecl *InstanceMethod = nullptr;
3890 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003891 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
3892 ClassMethod, InstanceMethod, TDNDecl, CfToNs))
3893 return false;
3894
3895 if (CfToNs) {
3896 // Implicit conversion from CF to ObjC object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003897 if (ClassMethod) {
3898 std::string ExpressionString = "[";
3899 ExpressionString += RelatedClass->getNameAsString();
3900 ExpressionString += " ";
3901 ExpressionString += ClassMethod->getSelector().getAsString();
Craig Topper07fa1762015-11-15 02:31:46 +00003902 SourceLocation SrcExprEndLoc = getLocForEndOfToken(SrcExpr->getLocEnd());
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003903 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003904 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003905 << SrcType << DestType << ClassMethod->getSelector() << false
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003906 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3907 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003908 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3909 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3910
3911 QualType receiverType =
3912 Context.getObjCInterfaceType(RelatedClass);
3913 // Argument.
3914 Expr *args[] = { SrcExpr };
3915 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
3916 ClassMethod->getLocation(),
3917 ClassMethod->getSelector(), ClassMethod,
3918 MultiExprArg(args, 1));
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003919 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003920 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003921 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003922 }
3923 else {
3924 // Implicit conversion from ObjC type to CF object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003925 if (InstanceMethod) {
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003926 std::string ExpressionString;
Craig Topper07fa1762015-11-15 02:31:46 +00003927 SourceLocation SrcExprEndLoc = getLocForEndOfToken(SrcExpr->getLocEnd());
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003928 if (InstanceMethod->isPropertyAccessor())
3929 if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
3930 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
3931 ExpressionString = ".";
3932 ExpressionString += PDecl->getNameAsString();
3933 Diag(Loc, diag::err_objc_bridged_related_known_method)
3934 << SrcType << DestType << InstanceMethod->getSelector() << true
3935 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3936 }
3937 if (ExpressionString.empty()) {
3938 // Provide a fixit: [ObjectExpr InstanceMethod]
3939 ExpressionString = " ";
3940 ExpressionString += InstanceMethod->getSelector().getAsString();
3941 ExpressionString += "]";
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003942
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003943 Diag(Loc, diag::err_objc_bridged_related_known_method)
3944 << SrcType << DestType << InstanceMethod->getSelector() << true
3945 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3946 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3947 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003948 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3949 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3950
3951 ExprResult msg =
3952 BuildInstanceMessageImplicit(SrcExpr, SrcType,
3953 InstanceMethod->getLocation(),
3954 InstanceMethod->getSelector(),
3955 InstanceMethod, None);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003956 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003957 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003958 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003959 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003960 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003961}
3962
John McCall4124c492011-10-17 18:40:02 +00003963Sema::ARCConversionResult
3964Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003965 Expr *&castExpr, CheckedConversionKind CCK,
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00003966 bool DiagnoseCFAudited,
3967 BinaryOperatorKind Opc) {
John McCall4124c492011-10-17 18:40:02 +00003968 QualType castExprType = castExpr->getType();
3969
3970 // For the purposes of the classification, we assume reference types
3971 // will bind to temporaries.
3972 QualType effCastType = castType;
3973 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3974 effCastType = ref->getPointeeType();
3975
3976 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3977 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003978 if (exprACTC == castACTC) {
3979 // check for viablity and report error if casting an rvalue to a
3980 // life-time qualifier.
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003981 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003982 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003983 (castType != castExprType)) {
3984 const Type *DT = castType.getTypePtr();
3985 QualType QDT = castType;
3986 // We desugar some types but not others. We ignore those
3987 // that cannot happen in a cast; i.e. auto, and those which
3988 // should not be de-sugared; i.e typedef.
3989 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3990 QDT = PT->desugar();
3991 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3992 QDT = TP->desugar();
3993 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3994 QDT = AT->desugar();
3995 if (QDT != castType &&
3996 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3997 SourceLocation loc =
3998 (castRange.isValid() ? castRange.getBegin()
3999 : castExpr->getExprLoc());
4000 Diag(loc, diag::err_arc_nolifetime_behavior);
4001 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004002 }
4003 return ACR_okay;
4004 }
4005
John McCall4124c492011-10-17 18:40:02 +00004006 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
4007
4008 // Allow all of these types to be cast to integer types (but not
4009 // vice-versa).
4010 if (castACTC == ACTC_none && castType->isIntegralType(Context))
4011 return ACR_okay;
4012
4013 // Allow casts between pointers to lifetime types (e.g., __strong id*)
4014 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
4015 // must be explicit.
4016 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
4017 return ACR_okay;
4018 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
4019 CCK != CCK_ImplicitConversion)
4020 return ACR_okay;
4021
Fariborz Jahanian36986c62012-07-27 22:37:07 +00004022 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00004023 // For invalid casts, fall through.
4024 case ACC_invalid:
4025 break;
4026
4027 // Do nothing for both bottom and +0.
4028 case ACC_bottom:
4029 case ACC_plusZero:
4030 return ACR_okay;
4031
4032 // If the result is +1, consume it here.
4033 case ACC_plusOne:
4034 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
4035 CK_ARCConsumeObject, castExpr,
Craig Topperc3ec1492014-05-26 06:22:03 +00004036 nullptr, VK_RValue);
John McCall4124c492011-10-17 18:40:02 +00004037 ExprNeedsCleanups = true;
4038 return ACR_okay;
4039 }
4040
4041 // If this is a non-implicit cast from id or block type to a
4042 // CoreFoundation type, delay complaining in case the cast is used
4043 // in an acceptable context.
4044 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
4045 CCK != CCK_ImplicitConversion)
4046 return ACR_unbridged;
4047
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00004048 // Do not issue bridge cast" diagnostic when implicit casting a cstring
4049 // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
4050 // suitable fix-it.
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004051 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
4052 ConversionToObjCStringLiteralCheck(castType, castExpr))
4053 return ACR_okay;
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00004054
Fariborz Jahanian25eef192013-07-31 21:40:51 +00004055 // Do not issue "bridge cast" diagnostic when implicit casting
4056 // a retainable object to a CF type parameter belonging to an audited
4057 // CF API function. Let caller issue a normal type mismatched diagnostic
4058 // instead.
4059 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
4060 castACTC != ACTC_coreFoundation)
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00004061 if (!(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
4062 (Opc == BO_NE || Opc == BO_EQ)))
4063 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
4064 castExpr, castExpr, exprACTC, CCK);
John McCall4124c492011-10-17 18:40:02 +00004065 return ACR_okay;
4066}
4067
4068/// Given that we saw an expression with the ARCUnbridgedCastTy
4069/// placeholder type, complain bitterly.
4070void Sema::diagnoseARCUnbridgedCast(Expr *e) {
4071 // We expect the spurious ImplicitCastExpr to already have been stripped.
4072 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4073 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
4074
4075 SourceRange castRange;
4076 QualType castType;
4077 CheckedConversionKind CCK;
4078
4079 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
4080 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
4081 castType = cast->getTypeAsWritten();
4082 CCK = CCK_CStyleCast;
4083 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
4084 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
4085 castType = cast->getTypeAsWritten();
4086 CCK = CCK_OtherCast;
4087 } else {
4088 castType = cast->getType();
4089 CCK = CCK_ImplicitConversion;
4090 }
4091
4092 ARCConversionTypeClass castACTC =
4093 classifyTypeForARCConversion(castType.getNonReferenceType());
4094
4095 Expr *castExpr = realCast->getSubExpr();
4096 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
4097
4098 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00004099 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00004100}
4101
4102/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
4103/// type, remove the placeholder cast.
4104Expr *Sema::stripARCUnbridgedCast(Expr *e) {
4105 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4106
4107 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
4108 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
4109 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
4110 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
4111 assert(uo->getOpcode() == UO_Extension);
4112 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
4113 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
4114 sub->getValueKind(), sub->getObjectKind(),
4115 uo->getOperatorLoc());
4116 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
4117 assert(!gse->isResultDependent());
4118
4119 unsigned n = gse->getNumAssocs();
4120 SmallVector<Expr*, 4> subExprs(n);
4121 SmallVector<TypeSourceInfo*, 4> subTypes(n);
4122 for (unsigned i = 0; i != n; ++i) {
4123 subTypes[i] = gse->getAssocTypeSourceInfo(i);
4124 Expr *sub = gse->getAssocExpr(i);
4125 if (i == gse->getResultIndex())
4126 sub = stripARCUnbridgedCast(sub);
4127 subExprs[i] = sub;
4128 }
4129
4130 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
4131 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00004132 subTypes, subExprs,
4133 gse->getDefaultLoc(),
John McCall4124c492011-10-17 18:40:02 +00004134 gse->getRParenLoc(),
4135 gse->containsUnexpandedParameterPack(),
4136 gse->getResultIndex());
4137 } else {
4138 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
4139 return cast<ImplicitCastExpr>(e)->getSubExpr();
4140 }
4141}
4142
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004143bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
4144 QualType exprType) {
4145 QualType canCastType =
4146 Context.getCanonicalType(castType).getUnqualifiedType();
4147 QualType canExprType =
4148 Context.getCanonicalType(exprType).getUnqualifiedType();
4149 if (isa<ObjCObjectPointerType>(canCastType) &&
4150 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
4151 canExprType->isObjCObjectPointerType()) {
4152 if (const ObjCObjectPointerType *ObjT =
4153 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00004154 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4155 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004156 }
4157 return true;
4158}
4159
John McCall4db5c3c2011-07-07 06:58:02 +00004160/// Look for an ObjCReclaimReturnedObject cast and destroy it.
4161static Expr *maybeUndoReclaimObject(Expr *e) {
4162 // For now, we just undo operands that are *immediately* reclaim
4163 // expressions, which prevents the vast majority of potential
4164 // problems here. To catch them all, we'd need to rebuild arbitrary
4165 // value-propagating subexpressions --- we can't reliably rebuild
4166 // in-place because of expression sharing.
4167 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall2d637d22011-09-10 06:18:15 +00004168 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall4db5c3c2011-07-07 06:58:02 +00004169 return ice->getSubExpr();
4170
4171 return e;
4172}
4173
John McCall31168b02011-06-15 23:02:42 +00004174ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
4175 ObjCBridgeCastKind Kind,
4176 SourceLocation BridgeKeywordLoc,
4177 TypeSourceInfo *TSInfo,
4178 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00004179 ExprResult SubResult = UsualUnaryConversions(SubExpr);
4180 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004181 SubExpr = SubResult.get();
John McCalleb075542011-08-26 00:48:42 +00004182
John McCall31168b02011-06-15 23:02:42 +00004183 QualType T = TSInfo->getType();
4184 QualType FromType = SubExpr->getType();
4185
John McCall9320b872011-09-09 05:25:32 +00004186 CastKind CK;
4187
John McCall31168b02011-06-15 23:02:42 +00004188 bool MustConsume = false;
4189 if (T->isDependentType() || SubExpr->isTypeDependent()) {
4190 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00004191 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00004192 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
4193 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00004194 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4195 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00004196 switch (Kind) {
4197 case OBC_Bridge:
4198 break;
4199
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004200 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004201 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00004202 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4203 << 2
4204 << FromType
4205 << (T->isBlockPointerType()? 1 : 0)
4206 << T
4207 << SubExpr->getSourceRange()
4208 << Kind;
4209 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4210 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4211 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004212 << FromType << br
John McCall31168b02011-06-15 23:02:42 +00004213 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004214 br ? "CFBridgingRelease "
4215 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00004216
4217 Kind = OBC_Bridge;
4218 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004219 }
John McCall31168b02011-06-15 23:02:42 +00004220
4221 case OBC_BridgeTransfer:
4222 // We must consume the Objective-C object produced by the cast.
4223 MustConsume = true;
4224 break;
4225 }
4226 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4227 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00004228 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00004229 switch (Kind) {
Fariborz Jahanian214567c2014-10-28 17:26:21 +00004230 case OBC_Bridge:
4231 // Reclaiming a value that's going to be __bridge-casted to CF
4232 // is very dangerous, so we don't do it.
4233 SubExpr = maybeUndoReclaimObject(SubExpr);
4234 break;
John McCall31168b02011-06-15 23:02:42 +00004235
4236 case OBC_BridgeRetained:
4237 // Produce the object before casting it.
4238 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00004239 CK_ARCProduceObject,
Craig Topperc3ec1492014-05-26 06:22:03 +00004240 SubExpr, nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004241 break;
4242
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004243 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004244 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00004245 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4246 << (FromType->isBlockPointerType()? 1 : 0)
4247 << FromType
4248 << 2
4249 << T
4250 << SubExpr->getSourceRange()
4251 << Kind;
4252
4253 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4254 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4255 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004256 << T << br
4257 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4258 br ? "CFBridgingRetain " : "__bridge_retained");
John McCall31168b02011-06-15 23:02:42 +00004259
4260 Kind = OBC_Bridge;
4261 break;
4262 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004263 }
John McCall31168b02011-06-15 23:02:42 +00004264 } else {
4265 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4266 << FromType << T << Kind
4267 << SubExpr->getSourceRange()
4268 << TSInfo->getTypeLoc().getSourceRange();
4269 return ExprError();
4270 }
4271
John McCall9320b872011-09-09 05:25:32 +00004272 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00004273 BridgeKeywordLoc,
4274 TSInfo, SubExpr);
4275
4276 if (MustConsume) {
4277 ExprNeedsCleanups = true;
John McCall2d637d22011-09-10 06:18:15 +00004278 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
Craig Topperc3ec1492014-05-26 06:22:03 +00004279 nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004280 }
4281
4282 return Result;
4283}
4284
4285ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4286 SourceLocation LParenLoc,
4287 ObjCBridgeCastKind Kind,
4288 SourceLocation BridgeKeywordLoc,
4289 ParsedType Type,
4290 SourceLocation RParenLoc,
4291 Expr *SubExpr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004292 TypeSourceInfo *TSInfo = nullptr;
John McCall31168b02011-06-15 23:02:42 +00004293 QualType T = GetTypeFromParser(Type, &TSInfo);
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00004294 if (Kind == OBC_Bridge)
4295 CheckTollFreeBridgeCast(T, SubExpr);
John McCall31168b02011-06-15 23:02:42 +00004296 if (!TSInfo)
4297 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4298 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
4299 SubExpr);
4300}