blob: 3257741429322d9cdac9694e0d122fe82d5da72d [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,
35 Expr **strings,
36 unsigned NumStrings) {
Chris Lattner163ffd22009-02-18 06:48:40 +000037 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
38
Chris Lattnerd7670d92009-02-18 06:13:04 +000039 // Most ObjC strings are formed out of a single piece. However, we *can*
40 // have strings formed out of multiple @ strings with multiple pptokens in
41 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
42 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner163ffd22009-02-18 06:48:40 +000043 StringLiteral *S = Strings[0];
Mike Stump11289f42009-09-09 15:08:12 +000044
Chris Lattnerd7670d92009-02-18 06:13:04 +000045 // If we have a multi-part string, merge it all together.
46 if (NumStrings != 1) {
Chris Lattnera3fc41d2008-01-04 22:32:30 +000047 // Concatenate objc strings.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000048 SmallString<128> StrBuf;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000049 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump11289f42009-09-09 15:08:12 +000050
Chris Lattner630970d2009-02-18 05:49:11 +000051 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner163ffd22009-02-18 06:48:40 +000052 S = Strings[i];
Mike Stump11289f42009-09-09 15:08:12 +000053
Douglas Gregorfb65e592011-07-27 05:40:30 +000054 // ObjC strings can't be wide or UTF.
55 if (!S->isAscii()) {
Chris Lattnerd7670d92009-02-18 06:13:04 +000056 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
57 << S->getSourceRange();
58 return true;
59 }
Mike Stump11289f42009-09-09 15:08:12 +000060
Benjamin Kramer35b077e2010-08-17 12:54:38 +000061 // Append the string.
62 StrBuf += S->getString();
Mike Stump11289f42009-09-09 15:08:12 +000063
Chris Lattner163ffd22009-02-18 06:48:40 +000064 // Get the locations of the string tokens.
65 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000066 }
Mike Stump11289f42009-09-09 15:08:12 +000067
Chris Lattner163ffd22009-02-18 06:48:40 +000068 // Create the aggregate string with the appropriate content and location
69 // information.
Benjamin Kramercdac7612014-02-25 12:26:20 +000070 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
71 assert(CAT && "String literal not of constant array type!");
72 QualType StrTy = Context.getConstantArrayType(
73 CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1),
74 CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
75 S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
76 /*Pascal=*/false, StrTy, &StrLocs[0],
77 StrLocs.size());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000078 }
Ted Kremeneke65b0862012-03-06 20:05:56 +000079
80 return BuildObjCStringLiteral(AtLocs[0], S);
81}
Mike Stump11289f42009-09-09 15:08:12 +000082
Ted Kremeneke65b0862012-03-06 20:05:56 +000083ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
Chris Lattner6436fb62009-02-18 06:01:06 +000084 // Verify that this composite string is acceptable for ObjC strings.
85 if (CheckObjCString(S))
Chris Lattnera3fc41d2008-01-04 22:32:30 +000086 return true;
Chris Lattnerfffd6a72009-02-18 06:06:56 +000087
88 // Initialize the constant string interface lazily. This assumes
Steve Naroff54e59452009-04-07 14:18:33 +000089 // the NSString interface is seen in this translation unit. Note: We
90 // don't use NSConstantString, since the runtime team considers this
91 // interface private (even though it appears in the header files).
Chris Lattnerfffd6a72009-02-18 06:06:56 +000092 QualType Ty = Context.getObjCConstantStringInterface();
93 if (!Ty.isNull()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +000094 Ty = Context.getObjCObjectPointerType(Ty);
David Blaikiebbafb8a2012-03-11 07:00:24 +000095 } else if (getLangOpts().NoConstantCFStrings) {
Craig Topperc3ec1492014-05-26 06:22:03 +000096 IdentifierInfo *NSIdent=nullptr;
David Blaikiebbafb8a2012-03-11 07:00:24 +000097 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +000098
99 if (StringClass.empty())
100 NSIdent = &Context.Idents.get("NSConstantString");
101 else
102 NSIdent = &Context.Idents.get(StringClass);
103
Ted Kremeneke65b0862012-03-06 20:05:56 +0000104 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Fariborz Jahanian07317632010-04-23 23:19:04 +0000105 LookupOrdinaryName);
106 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
107 Context.setObjCConstantStringInterface(StrIF);
108 Ty = Context.getObjCConstantStringInterface();
109 Ty = Context.getObjCObjectPointerType(Ty);
110 } else {
111 // If there is no NSConstantString interface defined then treat this
112 // as error and recover from it.
113 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
114 << S->getSourceRange();
115 Ty = Context.getObjCIdType();
116 }
Chris Lattner091f6982008-06-21 21:44:18 +0000117 } else {
Patrick Beard0caa3942012-04-19 00:25:12 +0000118 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000119 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000120 LookupOrdinaryName);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000121 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
122 Context.setObjCConstantStringInterface(StrIF);
123 Ty = Context.getObjCConstantStringInterface();
Steve Naroff7cae42b2009-07-10 23:34:53 +0000124 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000125 } else {
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000126 // If there is no NSString interface defined, implicitly declare
127 // a @class NSString; and use that instead. This is to make sure
128 // type of an NSString literal is represented correctly, instead of
129 // being an 'id' type.
130 Ty = Context.getObjCNSStringType();
131 if (Ty.isNull()) {
132 ObjCInterfaceDecl *NSStringIDecl =
133 ObjCInterfaceDecl::Create (Context,
134 Context.getTranslationUnitDecl(),
135 SourceLocation(), NSIdent,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000136 nullptr, nullptr, SourceLocation());
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000137 Ty = Context.getObjCInterfaceType(NSStringIDecl);
138 Context.setObjCNSStringType(Ty);
139 }
140 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000141 }
Chris Lattner091f6982008-06-21 21:44:18 +0000142 }
Mike Stump11289f42009-09-09 15:08:12 +0000143
Ted Kremeneke65b0862012-03-06 20:05:56 +0000144 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
145}
146
Jordy Rose08e500c2012-05-12 17:32:44 +0000147/// \brief Emits an error if the given method does not exist, or if the return
148/// type is not an Objective-C object.
149static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
150 const ObjCInterfaceDecl *Class,
151 Selector Sel, const ObjCMethodDecl *Method) {
152 if (!Method) {
153 // FIXME: Is there a better way to avoid quotes than using getName()?
154 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
155 return false;
156 }
157
158 // Make sure the return type is reasonable.
Alp Toker314cc812014-01-25 16:55:45 +0000159 QualType ReturnType = Method->getReturnType();
Jordy Rose08e500c2012-05-12 17:32:44 +0000160 if (!ReturnType->isObjCObjectPointerType()) {
161 S.Diag(Loc, diag::err_objc_literal_method_sig)
162 << Sel;
163 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
164 << ReturnType;
165 return false;
166 }
167
168 return true;
169}
170
Alex Denisovb7d85632015-07-24 05:09:40 +0000171/// \brief Maps ObjCLiteralKind to NSClassIdKindKind
172static NSAPI::NSClassIdKindKind ClassKindFromLiteralKind(
173 Sema::ObjCLiteralKind LiteralKind) {
174 switch (LiteralKind) {
175 case Sema::LK_Array:
176 return NSAPI::ClassId_NSArray;
177 case Sema::LK_Dictionary:
178 return NSAPI::ClassId_NSDictionary;
179 case Sema::LK_Numeric:
180 return NSAPI::ClassId_NSNumber;
181 case Sema::LK_String:
182 return NSAPI::ClassId_NSString;
183 case Sema::LK_Boxed:
184 return NSAPI::ClassId_NSValue;
185
186 // there is no corresponding matching
187 // between LK_None/LK_Block and NSClassIdKindKind
188 case Sema::LK_Block:
189 case Sema::LK_None:
Aaron Ballman3e839de2015-07-24 12:47:27 +0000190 break;
Alex Denisovb7d85632015-07-24 05:09:40 +0000191 }
Aaron Ballman3e839de2015-07-24 12:47:27 +0000192 llvm_unreachable("LiteralKind can't be converted into a ClassKind");
Alex Denisovb7d85632015-07-24 05:09:40 +0000193}
194
195/// \brief Validates ObjCInterfaceDecl availability.
196/// ObjCInterfaceDecl, used to create ObjC literals, should be defined
197/// if clang not in a debugger mode.
198static bool ValidateObjCLiteralInterfaceDecl(Sema &S, ObjCInterfaceDecl *Decl,
199 SourceLocation Loc,
200 Sema::ObjCLiteralKind LiteralKind) {
201 if (!Decl) {
202 NSAPI::NSClassIdKindKind Kind = ClassKindFromLiteralKind(LiteralKind);
203 IdentifierInfo *II = S.NSAPIObj->getNSClassId(Kind);
204 S.Diag(Loc, diag::err_undeclared_objc_literal_class)
205 << II->getName() << LiteralKind;
206 return false;
207 } else if (!Decl->hasDefinition() && !S.getLangOpts().DebuggerObjCLiteral) {
208 S.Diag(Loc, diag::err_undeclared_objc_literal_class)
209 << Decl->getName() << LiteralKind;
210 S.Diag(Decl->getLocation(), diag::note_forward_class);
211 return false;
212 }
213
214 return true;
215}
216
217/// \brief Looks up ObjCInterfaceDecl of a given NSClassIdKindKind.
218/// Used to create ObjC literals, such as NSDictionary (@{}),
219/// NSArray (@[]) and Boxed Expressions (@())
220static ObjCInterfaceDecl *LookupObjCInterfaceDeclForLiteral(Sema &S,
221 SourceLocation Loc,
222 Sema::ObjCLiteralKind LiteralKind) {
223 NSAPI::NSClassIdKindKind ClassKind = ClassKindFromLiteralKind(LiteralKind);
224 IdentifierInfo *II = S.NSAPIObj->getNSClassId(ClassKind);
225 NamedDecl *IF = S.LookupSingleName(S.TUScope, II, Loc,
226 Sema::LookupOrdinaryName);
227 ObjCInterfaceDecl *ID = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
228 if (!ID && S.getLangOpts().DebuggerObjCLiteral) {
229 ASTContext &Context = S.Context;
230 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
231 ID = ObjCInterfaceDecl::Create (Context, TU, SourceLocation(), II,
232 nullptr, nullptr, SourceLocation());
233 }
234
235 if (!ValidateObjCLiteralInterfaceDecl(S, ID, Loc, LiteralKind)) {
236 ID = nullptr;
237 }
238
239 return ID;
240}
241
Ted Kremeneke65b0862012-03-06 20:05:56 +0000242/// \brief Retrieve the NSNumber factory method that should be used to create
243/// an Objective-C literal for the given type.
244static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
Patrick Beard0caa3942012-04-19 00:25:12 +0000245 QualType NumberType,
246 bool isLiteral = false,
247 SourceRange R = SourceRange()) {
David Blaikie05785d12013-02-20 22:23:23 +0000248 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
249 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
250
Ted Kremeneke65b0862012-03-06 20:05:56 +0000251 if (!Kind) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000252 if (isLiteral) {
253 S.Diag(Loc, diag::err_invalid_nsnumber_type)
254 << NumberType << R;
255 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000256 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000257 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000258
Ted Kremeneke65b0862012-03-06 20:05:56 +0000259 // If we already looked up this method, we're done.
260 if (S.NSNumberLiteralMethods[*Kind])
261 return S.NSNumberLiteralMethods[*Kind];
262
263 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
264 /*Instance=*/false);
265
Patrick Beard0caa3942012-04-19 00:25:12 +0000266 ASTContext &CX = S.Context;
267
268 // Look up the NSNumber class, if we haven't done so already. It's cached
269 // in the Sema instance.
270 if (!S.NSNumberDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000271 S.NSNumberDecl = LookupObjCInterfaceDeclForLiteral(S, Loc,
272 Sema::LK_Numeric);
Patrick Beard0caa3942012-04-19 00:25:12 +0000273 if (!S.NSNumberDecl) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000274 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000275 }
Alex Denisove36748a2015-02-16 16:17:05 +0000276 }
277
278 if (S.NSNumberPointer.isNull()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000279 // generate the pointer to NSNumber type.
Jordy Roseaca01f92012-05-12 17:32:52 +0000280 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
281 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000282 }
283
Ted Kremeneke65b0862012-03-06 20:05:56 +0000284 // Look for the appropriate method within NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000285 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000286 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000287 // create a stub definition this NSNumber factory method.
Craig Topperc3ec1492014-05-26 06:22:03 +0000288 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000289 Method =
290 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
291 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
292 /*isInstance=*/false, /*isVariadic=*/false,
293 /*isPropertyAccessor=*/false,
294 /*isImplicitlyDeclared=*/true,
295 /*isDefined=*/false, ObjCMethodDecl::Required,
296 /*HasRelatedResultType=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000297 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
298 SourceLocation(), SourceLocation(),
Patrick Beard0caa3942012-04-19 00:25:12 +0000299 &CX.Idents.get("value"),
Craig Topperc3ec1492014-05-26 06:22:03 +0000300 NumberType, /*TInfo=*/nullptr,
301 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000302 Method->setMethodParams(S.Context, value, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000303 }
304
Jordy Rose08e500c2012-05-12 17:32:44 +0000305 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
Craig Topperc3ec1492014-05-26 06:22:03 +0000306 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000307
308 // Note: if the parameter type is out-of-line, we'll catch it later in the
309 // implicit conversion.
310
311 S.NSNumberLiteralMethods[*Kind] = Method;
312 return Method;
313}
314
Patrick Beard0caa3942012-04-19 00:25:12 +0000315/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
316/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremeneke65b0862012-03-06 20:05:56 +0000317ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000318 // Determine the type of the literal.
319 QualType NumberType = Number->getType();
320 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
321 // In C, character literals have type 'int'. That's not the type we want
322 // to use to determine the Objective-c literal kind.
323 switch (Char->getKind()) {
324 case CharacterLiteral::Ascii:
325 NumberType = Context.CharTy;
326 break;
327
328 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000329 NumberType = Context.getWideCharType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000330 break;
331
332 case CharacterLiteral::UTF16:
333 NumberType = Context.Char16Ty;
334 break;
335
336 case CharacterLiteral::UTF32:
337 NumberType = Context.Char32Ty;
338 break;
339 }
340 }
341
Ted Kremeneke65b0862012-03-06 20:05:56 +0000342 // Look for the appropriate method within NSNumber.
343 // Construct the literal.
Patrick Beard2565c592012-05-01 21:47:19 +0000344 SourceRange NR(Number->getSourceRange());
Patrick Beard0caa3942012-04-19 00:25:12 +0000345 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
Patrick Beard2565c592012-05-01 21:47:19 +0000346 true, NR);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000347 if (!Method)
348 return ExprError();
349
350 // Convert the number to the type that the parameter expects.
Alp Toker03376dc2014-07-07 09:02:20 +0000351 ParmVarDecl *ParamDecl = Method->parameters()[0];
Patrick Beard2565c592012-05-01 21:47:19 +0000352 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
353 ParamDecl);
354 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
355 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000356 Number);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000357 if (ConvertedNumber.isInvalid())
358 return ExprError();
359 Number = ConvertedNumber.get();
360
Patrick Beard2565c592012-05-01 21:47:19 +0000361 // Use the effective source range of the literal, including the leading '@'.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000362 return MaybeBindToTemporary(
Patrick Beard2565c592012-05-01 21:47:19 +0000363 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
364 SourceRange(AtLoc, NR.getEnd())));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000365}
366
367ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
368 SourceLocation ValueLoc,
369 bool Value) {
370 ExprResult Inner;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000371 if (getLangOpts().CPlusPlus) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000372 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
373 } else {
374 // C doesn't actually have a way to represent literal values of type
375 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
376 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
377 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
378 CK_IntegralToBoolean);
379 }
380
381 return BuildObjCNumericLiteral(AtLoc, Inner.get());
382}
383
384/// \brief Check that the given expression is a valid element of an Objective-C
385/// collection literal.
386static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000387 QualType T,
388 bool ArrayLiteral = false) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000389 // If the expression is type-dependent, there's nothing for us to do.
390 if (Element->isTypeDependent())
391 return Element;
392
393 ExprResult Result = S.CheckPlaceholderExpr(Element);
394 if (Result.isInvalid())
395 return ExprError();
396 Element = Result.get();
397
398 // In C++, check for an implicit conversion to an Objective-C object pointer
399 // type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000400 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000401 InitializedEntity Entity
Jordy Roseaca01f92012-05-12 17:32:52 +0000402 = InitializedEntity::InitializeParameter(S.Context, T,
403 /*Consumed=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000404 InitializationKind Kind
Jordy Roseaca01f92012-05-12 17:32:52 +0000405 = InitializationKind::CreateCopy(Element->getLocStart(),
406 SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000407 InitializationSequence Seq(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000408 if (!Seq.Failed())
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000409 return Seq.Perform(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000410 }
411
412 Expr *OrigElement = Element;
413
414 // Perform lvalue-to-rvalue conversion.
415 Result = S.DefaultLvalueConversion(Element);
416 if (Result.isInvalid())
417 return ExprError();
418 Element = Result.get();
419
420 // Make sure that we have an Objective-C pointer type or block.
421 if (!Element->getType()->isObjCObjectPointerType() &&
422 !Element->getType()->isBlockPointerType()) {
423 bool Recovered = false;
424
425 // If this is potentially an Objective-C numeric literal, add the '@'.
426 if (isa<IntegerLiteral>(OrigElement) ||
427 isa<CharacterLiteral>(OrigElement) ||
428 isa<FloatingLiteral>(OrigElement) ||
429 isa<ObjCBoolLiteralExpr>(OrigElement) ||
430 isa<CXXBoolLiteralExpr>(OrigElement)) {
431 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
432 int Which = isa<CharacterLiteral>(OrigElement) ? 1
433 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
434 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
435 : 3;
436
437 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
438 << Which << OrigElement->getSourceRange()
439 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
440
441 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
442 OrigElement);
443 if (Result.isInvalid())
444 return ExprError();
445
446 Element = Result.get();
447 Recovered = true;
448 }
449 }
450 // If this is potentially an Objective-C string literal, add the '@'.
451 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
452 if (String->isAscii()) {
453 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
454 << 0 << OrigElement->getSourceRange()
455 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
456
457 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
458 if (Result.isInvalid())
459 return ExprError();
460
461 Element = Result.get();
462 Recovered = true;
463 }
464 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000465
Ted Kremeneke65b0862012-03-06 20:05:56 +0000466 if (!Recovered) {
467 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
468 << Element->getType();
469 return ExprError();
470 }
471 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000472 if (ArrayLiteral)
Ted Kremenek197fee42013-10-09 22:34:33 +0000473 if (ObjCStringLiteral *getString =
474 dyn_cast<ObjCStringLiteral>(OrigElement)) {
475 if (StringLiteral *SL = getString->getString()) {
476 unsigned numConcat = SL->getNumConcatenated();
477 if (numConcat > 1) {
478 // Only warn if the concatenated string doesn't come from a macro.
479 bool hasMacro = false;
480 for (unsigned i = 0; i < numConcat ; ++i)
481 if (SL->getStrTokenLoc(i).isMacroID()) {
482 hasMacro = true;
483 break;
484 }
485 if (!hasMacro)
486 S.Diag(Element->getLocStart(),
487 diag::warn_concatenated_nsarray_literal)
488 << Element->getType();
489 }
490 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000491 }
492
Ted Kremeneke65b0862012-03-06 20:05:56 +0000493 // Make sure that the element has the type that the container factory
494 // function expects.
495 return S.PerformCopyInitialization(
496 InitializedEntity::InitializeParameter(S.Context, T,
497 /*Consumed=*/false),
498 Element->getLocStart(), Element);
499}
500
Patrick Beard0caa3942012-04-19 00:25:12 +0000501ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
502 if (ValueExpr->isTypeDependent()) {
503 ObjCBoxedExpr *BoxedExpr =
Craig Topperc3ec1492014-05-26 06:22:03 +0000504 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000505 return BoxedExpr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000506 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000507 ObjCMethodDecl *BoxingMethod = nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000508 QualType BoxedType;
509 // Convert the expression to an RValue, so we can check for pointer types...
510 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
511 if (RValue.isInvalid()) {
512 return ExprError();
513 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000514 SourceLocation Loc = SR.getBegin();
Patrick Beard0caa3942012-04-19 00:25:12 +0000515 ValueExpr = RValue.get();
Patrick Beard2565c592012-05-01 21:47:19 +0000516 QualType ValueType(ValueExpr->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +0000517 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
518 QualType PointeeType = PT->getPointeeType();
519 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
520
521 if (!NSStringDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000522 NSStringDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
523 Sema::LK_String);
Patrick Beard0caa3942012-04-19 00:25:12 +0000524 if (!NSStringDecl) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000525 return ExprError();
526 }
Jordy Roseaca01f92012-05-12 17:32:52 +0000527 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
528 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000529 }
530
531 if (!StringWithUTF8StringMethod) {
532 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
533 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
534
535 // Look for the appropriate method within NSString.
Jordy Rose08e500c2012-05-12 17:32:44 +0000536 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
537 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000538 // Debugger needs to work even if NSString hasn't been defined.
Craig Topperc3ec1492014-05-26 06:22:03 +0000539 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000540 ObjCMethodDecl *M = ObjCMethodDecl::Create(
541 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
542 NSStringPointer, ReturnTInfo, NSStringDecl,
543 /*isInstance=*/false, /*isVariadic=*/false,
544 /*isPropertyAccessor=*/false,
545 /*isImplicitlyDeclared=*/true,
546 /*isDefined=*/false, ObjCMethodDecl::Required,
547 /*HasRelatedResultType=*/false);
Jordy Roseaca01f92012-05-12 17:32:52 +0000548 QualType ConstCharType = Context.CharTy.withConst();
Patrick Beard0caa3942012-04-19 00:25:12 +0000549 ParmVarDecl *value =
550 ParmVarDecl::Create(Context, M,
551 SourceLocation(), SourceLocation(),
552 &Context.Idents.get("value"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000553 Context.getPointerType(ConstCharType),
Craig Topperc3ec1492014-05-26 06:22:03 +0000554 /*TInfo=*/nullptr,
555 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000556 M->setMethodParams(Context, value, None);
Jordy Rose08e500c2012-05-12 17:32:44 +0000557 BoxingMethod = M;
Patrick Beard0caa3942012-04-19 00:25:12 +0000558 }
Jordy Rose890f4572012-05-12 15:53:41 +0000559
Alex Denisovb7d85632015-07-24 05:09:40 +0000560 if (!validateBoxingMethod(*this, Loc, NSStringDecl,
Jordy Rose08e500c2012-05-12 17:32:44 +0000561 stringWithUTF8String, BoxingMethod))
562 return ExprError();
563
564 StringWithUTF8StringMethod = BoxingMethod;
Patrick Beard0caa3942012-04-19 00:25:12 +0000565 }
566
567 BoxingMethod = StringWithUTF8StringMethod;
568 BoxedType = NSStringPointer;
569 }
Patrick Beard2565c592012-05-01 21:47:19 +0000570 } else if (ValueType->isBuiltinType()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000571 // The other types we support are numeric, char and BOOL/bool. We could also
572 // provide limited support for structure types, such as NSRange, NSRect, and
573 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
574 // for more details.
575
576 // Check for a top-level character literal.
577 if (const CharacterLiteral *Char =
578 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
579 // In C, character literals have type 'int'. That's not the type we want
580 // to use to determine the Objective-c literal kind.
581 switch (Char->getKind()) {
582 case CharacterLiteral::Ascii:
583 ValueType = Context.CharTy;
584 break;
585
586 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000587 ValueType = Context.getWideCharType();
Patrick Beard0caa3942012-04-19 00:25:12 +0000588 break;
589
590 case CharacterLiteral::UTF16:
591 ValueType = Context.Char16Ty;
592 break;
593
594 case CharacterLiteral::UTF32:
595 ValueType = Context.Char32Ty;
596 break;
597 }
598 }
Fariborz Jahanian5d64abb2014-06-18 20:49:02 +0000599 CheckForIntOverflow(ValueExpr);
Patrick Beard0caa3942012-04-19 00:25:12 +0000600 // FIXME: Do I need to do anything special with BoolTy expressions?
601
602 // Look for the appropriate method within NSNumber.
Alex Denisovb7d85632015-07-24 05:09:40 +0000603 BoxingMethod = getNSNumberFactoryMethod(*this, Loc, ValueType);
Patrick Beard0caa3942012-04-19 00:25:12 +0000604 BoxedType = NSNumberPointer;
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000605 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
606 if (!ET->getDecl()->isComplete()) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000607 Diag(Loc, diag::err_objc_incomplete_boxed_expression_type)
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000608 << ValueType << ValueExpr->getSourceRange();
609 return ExprError();
610 }
611
Alex Denisovb7d85632015-07-24 05:09:40 +0000612 BoxingMethod = getNSNumberFactoryMethod(*this, Loc,
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000613 ET->getDecl()->getIntegerType());
614 BoxedType = NSNumberPointer;
Alex Denisovfde64952015-06-26 05:28:36 +0000615 } else if (ValueType->isObjCBoxableRecordType()) {
616 // Support for structure types, that marked as objc_boxable
617 // struct __attribute__((objc_boxable)) s { ... };
618
619 // Look up the NSValue class, if we haven't done so already. It's cached
620 // in the Sema instance.
621 if (!NSValueDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000622 NSValueDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
623 Sema::LK_Boxed);
Alex Denisovfde64952015-06-26 05:28:36 +0000624 if (!NSValueDecl) {
Alex Denisovfde64952015-06-26 05:28:36 +0000625 return ExprError();
626 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000627
Alex Denisovfde64952015-06-26 05:28:36 +0000628 // generate the pointer to NSValue type.
629 QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
630 NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
631 }
632
633 if (!ValueWithBytesObjCTypeMethod) {
634 IdentifierInfo *II[] = {
635 &Context.Idents.get("valueWithBytes"),
636 &Context.Idents.get("objCType")
637 };
638 Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
639
640 // Look for the appropriate method within NSValue.
641 BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
642 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
643 // Debugger needs to work even if NSValue hasn't been defined.
644 TypeSourceInfo *ReturnTInfo = nullptr;
645 ObjCMethodDecl *M = ObjCMethodDecl::Create(
646 Context,
647 SourceLocation(),
648 SourceLocation(),
649 ValueWithBytesObjCType,
650 NSValuePointer,
651 ReturnTInfo,
652 NSValueDecl,
653 /*isInstance=*/false,
654 /*isVariadic=*/false,
655 /*isPropertyAccessor=*/false,
656 /*isImplicitlyDeclared=*/true,
657 /*isDefined=*/false,
658 ObjCMethodDecl::Required,
659 /*HasRelatedResultType=*/false);
660
661 SmallVector<ParmVarDecl *, 2> Params;
662
663 ParmVarDecl *bytes =
664 ParmVarDecl::Create(Context, M,
665 SourceLocation(), SourceLocation(),
666 &Context.Idents.get("bytes"),
667 Context.VoidPtrTy.withConst(),
668 /*TInfo=*/nullptr,
669 SC_None, nullptr);
670 Params.push_back(bytes);
671
672 QualType ConstCharType = Context.CharTy.withConst();
673 ParmVarDecl *type =
674 ParmVarDecl::Create(Context, M,
675 SourceLocation(), SourceLocation(),
676 &Context.Idents.get("type"),
677 Context.getPointerType(ConstCharType),
678 /*TInfo=*/nullptr,
679 SC_None, nullptr);
680 Params.push_back(type);
681
682 M->setMethodParams(Context, Params, None);
683 BoxingMethod = M;
684 }
685
Alex Denisovb7d85632015-07-24 05:09:40 +0000686 if (!validateBoxingMethod(*this, Loc, NSValueDecl,
Alex Denisovfde64952015-06-26 05:28:36 +0000687 ValueWithBytesObjCType, BoxingMethod))
688 return ExprError();
689
690 ValueWithBytesObjCTypeMethod = BoxingMethod;
691 }
692
693 if (!ValueType.isTriviallyCopyableType(Context)) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000694 Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type)
Alex Denisovfde64952015-06-26 05:28:36 +0000695 << ValueType << ValueExpr->getSourceRange();
696 return ExprError();
697 }
698
699 BoxingMethod = ValueWithBytesObjCTypeMethod;
700 BoxedType = NSValuePointer;
Patrick Beard0caa3942012-04-19 00:25:12 +0000701 }
702
703 if (!BoxingMethod) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000704 Diag(Loc, diag::err_objc_illegal_boxed_expression_type)
Patrick Beard0caa3942012-04-19 00:25:12 +0000705 << ValueType << ValueExpr->getSourceRange();
706 return ExprError();
707 }
708
Alex Denisovb7d85632015-07-24 05:09:40 +0000709 DiagnoseUseOfDecl(BoxingMethod, Loc);
Alex Denisovfde64952015-06-26 05:28:36 +0000710
711 ExprResult ConvertedValueExpr;
712 if (ValueType->isObjCBoxableRecordType()) {
713 InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
714 ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
715 ValueExpr);
716 } else {
717 // Convert the expression to the type that the parameter requires.
718 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
719 InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
720 ParamDecl);
721 ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
722 ValueExpr);
723 }
724
Patrick Beard0caa3942012-04-19 00:25:12 +0000725 if (ConvertedValueExpr.isInvalid())
726 return ExprError();
727 ValueExpr = ConvertedValueExpr.get();
728
729 ObjCBoxedExpr *BoxedExpr =
730 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
731 BoxingMethod, SR);
732 return MaybeBindToTemporary(BoxedExpr);
733}
734
John McCallf2538342012-07-31 05:14:30 +0000735/// Build an ObjC subscript pseudo-object expression, given that
736/// that's supported by the runtime.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000737ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
738 Expr *IndexExpr,
739 ObjCMethodDecl *getterMethod,
740 ObjCMethodDecl *setterMethod) {
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +0000741 assert(!LangOpts.isSubscriptPointerArithmetic());
John McCall5fb5df92012-06-20 06:18:46 +0000742
John McCallf2538342012-07-31 05:14:30 +0000743 // We can't get dependent types here; our callers should have
744 // filtered them out.
745 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
746 "base or index cannot have dependent type here");
747
748 // Filter out placeholders in the index. In theory, overloads could
749 // be preserved here, although that might not actually work correctly.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000750 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
751 if (Result.isInvalid())
752 return ExprError();
753 IndexExpr = Result.get();
754
John McCallf2538342012-07-31 05:14:30 +0000755 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000756 Result = DefaultLvalueConversion(BaseExpr);
757 if (Result.isInvalid())
758 return ExprError();
759 BaseExpr = Result.get();
John McCallf2538342012-07-31 05:14:30 +0000760
761 // Build the pseudo-object expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000762 return ObjCSubscriptRefExpr::Create(Context, BaseExpr, IndexExpr,
763 Context.PseudoObjectTy, getterMethod,
764 setterMethod, RB);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000765}
766
767ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000768 SourceLocation Loc = SR.getBegin();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000769
Alex Denisovb7d85632015-07-24 05:09:40 +0000770 if (!NSArrayDecl) {
771 NSArrayDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
772 Sema::LK_Array);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000773 if (!NSArrayDecl) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000774 return ExprError();
775 }
776 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000777
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000778 // Find the arrayWithObjects:count: method, if we haven't done so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000779 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000780 if (!ArrayWithObjectsMethod) {
781 Selector
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000782 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
783 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000784 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000785 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000786 Method = ObjCMethodDecl::Create(
787 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000788 Context.getTranslationUnitDecl(), false /*Instance*/,
Alp Toker314cc812014-01-25 16:55:45 +0000789 false /*isVariadic*/,
790 /*isPropertyAccessor=*/false,
791 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
792 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000793 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000794 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000795 SourceLocation(),
796 SourceLocation(),
797 &Context.Idents.get("objects"),
798 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000799 /*TInfo=*/nullptr,
800 SC_None, nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000801 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000802 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000803 SourceLocation(),
804 SourceLocation(),
805 &Context.Idents.get("cnt"),
806 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000807 /*TInfo=*/nullptr, SC_None,
808 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000809 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000810 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000811 }
812
Alex Denisovb7d85632015-07-24 05:09:40 +0000813 if (!validateBoxingMethod(*this, Loc, NSArrayDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000814 return ExprError();
Jordy Rose08e500c2012-05-12 17:32:44 +0000815
Jordy Rose4af44872012-05-12 17:32:56 +0000816 // Dig out the type that all elements should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000817 QualType T = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000818 const PointerType *PtrT = T->getAs<PointerType>();
819 if (!PtrT ||
820 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
821 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
822 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000823 Diag(Method->parameters()[0]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000824 diag::note_objc_literal_method_param)
825 << 0 << T
826 << Context.getPointerType(IdT.withConst());
827 return ExprError();
828 }
829
830 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000831 if (!Method->parameters()[1]->getType()->isIntegerType()) {
Jordy Rose4af44872012-05-12 17:32:56 +0000832 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
833 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000834 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000835 diag::note_objc_literal_method_param)
836 << 1
Alp Toker03376dc2014-07-07 09:02:20 +0000837 << Method->parameters()[1]->getType()
Jordy Rose4af44872012-05-12 17:32:56 +0000838 << "integral";
839 return ExprError();
840 }
841
842 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rose08e500c2012-05-12 17:32:44 +0000843 ArrayWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000844 }
845
Alp Toker03376dc2014-07-07 09:02:20 +0000846 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000847 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000848
849 // Check that each of the elements provided is valid in a collection literal,
850 // performing conversions as necessary.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000851 Expr **ElementsBuffer = Elements.data();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000852 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
853 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
854 ElementsBuffer[I],
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000855 RequiredType, true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000856 if (Converted.isInvalid())
857 return ExprError();
858
859 ElementsBuffer[I] = Converted.get();
860 }
861
862 QualType Ty
863 = Context.getObjCObjectPointerType(
864 Context.getObjCInterfaceType(NSArrayDecl));
865
866 return MaybeBindToTemporary(
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000867 ObjCArrayLiteral::Create(Context, Elements, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000868 ArrayWithObjectsMethod, SR));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000869}
870
871ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
872 ObjCDictionaryElement *Elements,
873 unsigned NumElements) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000874 SourceLocation Loc = SR.getBegin();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000875
Alex Denisovb7d85632015-07-24 05:09:40 +0000876 if (!NSDictionaryDecl) {
877 NSDictionaryDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
878 Sema::LK_Dictionary);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000879 if (!NSDictionaryDecl) {
Alex Denisovb7d85632015-07-24 05:09:40 +0000880 return ExprError();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000881 }
882 }
Alex Denisovb7d85632015-07-24 05:09:40 +0000883
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000884 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
885 // so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000886 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000887 if (!DictionaryWithObjectsMethod) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000888 Selector Sel = NSAPIObj->getNSDictionarySelector(
889 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
890 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000891 if (!Method && getLangOpts().DebuggerObjCLiteral) {
892 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000893 SourceLocation(), SourceLocation(), Sel,
894 IdT,
Craig Topperc3ec1492014-05-26 06:22:03 +0000895 nullptr /*TypeSourceInfo */,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000896 Context.getTranslationUnitDecl(),
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000897 false /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000898 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000899 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
900 ObjCMethodDecl::Required,
901 false);
902 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000903 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000904 SourceLocation(),
905 SourceLocation(),
906 &Context.Idents.get("objects"),
907 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000908 /*TInfo=*/nullptr, SC_None,
909 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000910 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000911 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000912 SourceLocation(),
913 SourceLocation(),
914 &Context.Idents.get("keys"),
915 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000916 /*TInfo=*/nullptr, SC_None,
917 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000918 Params.push_back(keys);
Jordy Rose08e500c2012-05-12 17:32:44 +0000919 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000920 SourceLocation(),
921 SourceLocation(),
922 &Context.Idents.get("cnt"),
923 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000924 /*TInfo=*/nullptr, SC_None,
925 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000926 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000927 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000928 }
929
Jordy Rose08e500c2012-05-12 17:32:44 +0000930 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
931 Method))
932 return ExprError();
933
Jordy Rose4af44872012-05-12 17:32:56 +0000934 // Dig out the type that all values should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000935 QualType ValueT = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000936 const PointerType *PtrValue = ValueT->getAs<PointerType>();
937 if (!PtrValue ||
938 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000939 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000940 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000941 Diag(Method->parameters()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000942 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000943 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000944 << Context.getPointerType(IdT.withConst());
945 return ExprError();
946 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000947
Jordy Rose4af44872012-05-12 17:32:56 +0000948 // Dig out the type that all keys should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000949 QualType KeyT = Method->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000950 const PointerType *PtrKey = KeyT->getAs<PointerType>();
951 if (!PtrKey ||
952 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
953 IdT)) {
954 bool err = true;
955 if (PtrKey) {
956 if (QIDNSCopying.isNull()) {
957 // key argument of selector is id<NSCopying>?
958 if (ObjCProtocolDecl *NSCopyingPDecl =
959 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
960 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
961 QIDNSCopying =
Douglas Gregore9d95f12015-07-07 03:57:35 +0000962 Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { },
963 llvm::makeArrayRef(
964 (ObjCProtocolDecl**) PQ,
Douglas Gregorab209d82015-07-07 03:58:42 +0000965 1),
966 false);
Jordy Rose4af44872012-05-12 17:32:56 +0000967 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
968 }
969 }
970 if (!QIDNSCopying.isNull())
971 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
972 QIDNSCopying);
973 }
974
975 if (err) {
976 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
977 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000978 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000979 diag::note_objc_literal_method_param)
980 << 1 << KeyT
981 << Context.getPointerType(IdT.withConst());
982 return ExprError();
983 }
984 }
985
986 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000987 QualType CountType = Method->parameters()[2]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000988 if (!CountType->isIntegerType()) {
989 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
990 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000991 Diag(Method->parameters()[2]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000992 diag::note_objc_literal_method_param)
993 << 2 << CountType
994 << "integral";
995 return ExprError();
996 }
997
998 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
999 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001000 }
1001
Alp Toker03376dc2014-07-07 09:02:20 +00001002 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +00001003 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
Alp Toker03376dc2014-07-07 09:02:20 +00001004 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +00001005 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
1006
Ted Kremeneke65b0862012-03-06 20:05:56 +00001007 // Check that each of the keys and values provided is valid in a collection
1008 // literal, performing conversions as necessary.
1009 bool HasPackExpansions = false;
1010 for (unsigned I = 0, N = NumElements; I != N; ++I) {
1011 // Check the key.
1012 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
1013 KeyT);
1014 if (Key.isInvalid())
1015 return ExprError();
1016
1017 // Check the value.
1018 ExprResult Value
1019 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
1020 if (Value.isInvalid())
1021 return ExprError();
1022
1023 Elements[I].Key = Key.get();
1024 Elements[I].Value = Value.get();
1025
1026 if (Elements[I].EllipsisLoc.isInvalid())
1027 continue;
1028
1029 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
1030 !Elements[I].Value->containsUnexpandedParameterPack()) {
1031 Diag(Elements[I].EllipsisLoc,
1032 diag::err_pack_expansion_without_parameter_packs)
1033 << SourceRange(Elements[I].Key->getLocStart(),
1034 Elements[I].Value->getLocEnd());
1035 return ExprError();
1036 }
1037
1038 HasPackExpansions = true;
1039 }
1040
1041
1042 QualType Ty
1043 = Context.getObjCObjectPointerType(
Robert Wilhelm88e02492013-08-19 07:57:02 +00001044 Context.getObjCInterfaceType(NSDictionaryDecl));
1045 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
1046 Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +00001047 DictionaryWithObjectsMethod, SR));
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001048}
1049
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001050ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregorabd9e962010-04-20 15:39:42 +00001051 TypeSourceInfo *EncodedTypeInfo,
Anders Carlsson315d2292009-06-07 18:45:35 +00001052 SourceLocation RParenLoc) {
Douglas Gregorabd9e962010-04-20 15:39:42 +00001053 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlsson315d2292009-06-07 18:45:35 +00001054 QualType StrTy;
Mike Stump11289f42009-09-09 15:08:12 +00001055 if (EncodedType->isDependentType())
Anders Carlsson315d2292009-06-07 18:45:35 +00001056 StrTy = Context.DependentTy;
1057 else {
Fariborz Jahaniand9bc6c32011-06-16 22:34:44 +00001058 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
1059 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001060 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001061 diag::err_incomplete_type_objc_at_encode,
1062 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001063 return ExprError();
1064
Anders Carlsson315d2292009-06-07 18:45:35 +00001065 std::string Str;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +00001066 QualType NotEncodedT;
1067 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
1068 if (!NotEncodedT.isNull())
1069 Diag(AtLoc, diag::warn_incomplete_encoded_type)
1070 << EncodedType << NotEncodedT;
Anders Carlsson315d2292009-06-07 18:45:35 +00001071
1072 // The type of @encode is the same as the type of the corresponding string,
1073 // which is an array type.
1074 StrTy = Context.CharTy;
1075 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001076 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlsson315d2292009-06-07 18:45:35 +00001077 StrTy.addConst();
1078 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
1079 ArrayType::Normal, 0);
1080 }
Mike Stump11289f42009-09-09 15:08:12 +00001081
Douglas Gregorabd9e962010-04-20 15:39:42 +00001082 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlsson315d2292009-06-07 18:45:35 +00001083}
1084
John McCallfaf5fb42010-08-26 23:41:50 +00001085ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1086 SourceLocation EncodeLoc,
1087 SourceLocation LParenLoc,
1088 ParsedType ty,
1089 SourceLocation RParenLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001090 // FIXME: Preserve type source info ?
Douglas Gregorabd9e962010-04-20 15:39:42 +00001091 TypeSourceInfo *TInfo;
1092 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1093 if (!TInfo)
1094 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
1095 PP.getLocForEndOfToken(LParenLoc));
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001096
Douglas Gregorabd9e962010-04-20 15:39:42 +00001097 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001098}
1099
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001100static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1101 SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001102 SourceLocation LParenLoc,
1103 SourceLocation RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001104 ObjCMethodDecl *Method,
1105 ObjCMethodList &MethList) {
1106 ObjCMethodList *M = &MethList;
1107 bool Warned = false;
1108 for (M = M->getNext(); M; M=M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00001109 ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001110 if (MatchingMethodDecl == Method ||
1111 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1112 MatchingMethodDecl->getSelector() != Method->getSelector())
1113 continue;
1114 if (!S.MatchTwoMethodDeclarations(Method,
1115 MatchingMethodDecl, Sema::MMS_loose)) {
1116 if (!Warned) {
1117 Warned = true;
1118 S.Diag(AtLoc, diag::warning_multiple_selectors)
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001119 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1120 << FixItHint::CreateInsertion(RParenLoc, ")");
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001121 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1122 << Method->getDeclName();
1123 }
1124 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1125 << MatchingMethodDecl->getDeclName();
1126 }
1127 }
1128 return Warned;
1129}
1130
1131static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001132 ObjCMethodDecl *Method,
1133 SourceLocation LParenLoc,
1134 SourceLocation RParenLoc,
1135 bool WarnMultipleSelectors) {
1136 if (!WarnMultipleSelectors ||
1137 S.Diags.isIgnored(diag::warning_multiple_selectors, SourceLocation()))
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001138 return;
1139 bool Warned = false;
1140 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1141 e = S.MethodPool.end(); b != e; b++) {
1142 // first, instance methods
1143 ObjCMethodList &InstMethList = b->second.first;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001144 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001145 Method, InstMethList))
1146 Warned = true;
1147
1148 // second, class methods
1149 ObjCMethodList &ClsMethList = b->second.second;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001150 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1151 Method, ClsMethList) || Warned)
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001152 return;
1153 }
1154}
1155
John McCallfaf5fb42010-08-26 23:41:50 +00001156ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1157 SourceLocation AtLoc,
1158 SourceLocation SelLoc,
1159 SourceLocation LParenLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001160 SourceLocation RParenLoc,
1161 bool WarnMultipleSelectors) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001162 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00001163 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001164 if (!Method)
1165 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian0571d9b2009-06-16 16:25:00 +00001166 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00001167 if (!Method) {
1168 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1169 Selector MatchedSel = OM->getSelector();
1170 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1171 RParenLoc.getLocWithOffset(-1));
1172 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1173 << Sel << MatchedSel
1174 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1175
1176 } else
1177 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001178 } else
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001179 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1180 WarnMultipleSelectors);
Chandler Carruth12c8f652015-03-27 00:55:05 +00001181
Fariborz Jahanian65a78b52014-05-09 19:51:39 +00001182 if (Method &&
1183 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
Chandler Carruth12c8f652015-03-27 00:55:05 +00001184 !getSourceManager().isInSystemHeader(Method->getLocation()))
1185 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001186
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001187 // In ARC, forbid the user from using @selector for
John McCall31168b02011-06-15 23:02:42 +00001188 // retain/release/autorelease/dealloc/retainCount.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001189 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001190 switch (Sel.getMethodFamily()) {
1191 case OMF_retain:
1192 case OMF_release:
1193 case OMF_autorelease:
1194 case OMF_retainCount:
1195 case OMF_dealloc:
1196 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1197 Sel << SourceRange(LParenLoc, RParenLoc);
1198 break;
1199
1200 case OMF_None:
1201 case OMF_alloc:
1202 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00001203 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00001204 case OMF_init:
1205 case OMF_mutableCopy:
1206 case OMF_new:
1207 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00001208 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001209 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001210 break;
1211 }
1212 }
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001213 QualType Ty = Context.getObjCSelType();
Daniel Dunbar45858d22010-02-03 20:11:42 +00001214 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001215}
1216
John McCallfaf5fb42010-08-26 23:41:50 +00001217ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1218 SourceLocation AtLoc,
1219 SourceLocation ProtoLoc,
1220 SourceLocation LParenLoc,
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001221 SourceLocation ProtoIdLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00001222 SourceLocation RParenLoc) {
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001223 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001224 if (!PDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001225 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001226 return true;
1227 }
Fariborz Jahaniana57d91c22014-07-25 19:45:01 +00001228 if (PDecl->hasDefinition())
1229 PDecl = PDecl->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00001230
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001231 QualType Ty = Context.getObjCProtoType();
1232 if (Ty.isNull())
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001233 return true;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001234 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001235 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001236}
1237
John McCall5f2d5562011-02-03 09:00:02 +00001238/// Try to capture an implicit reference to 'self'.
Eli Friedman24af8502012-02-03 22:47:37 +00001239ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1240 DeclContext *DC = getFunctionLevelDeclContext();
John McCall5f2d5562011-02-03 09:00:02 +00001241
1242 // If we're not in an ObjC method, error out. Note that, unlike the
1243 // C++ case, we don't require an instance method --- class methods
1244 // still have a 'self', and we really do still need to capture it!
1245 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1246 if (!method)
Craig Topperc3ec1492014-05-26 06:22:03 +00001247 return nullptr;
John McCall5f2d5562011-02-03 09:00:02 +00001248
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001249 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall5f2d5562011-02-03 09:00:02 +00001250
1251 return method;
1252}
1253
Douglas Gregor64910ca2011-09-09 20:05:21 +00001254static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
Douglas Gregor813a0662015-06-19 18:14:38 +00001255 QualType origType = T;
1256 if (auto nullability = AttributedType::stripOuterNullability(T)) {
1257 if (T == Context.getObjCInstanceType()) {
1258 return Context.getAttributedType(
1259 AttributedType::getNullabilityAttrKind(*nullability),
1260 Context.getObjCIdType(),
1261 Context.getObjCIdType());
1262 }
1263
1264 return origType;
1265 }
1266
Douglas Gregor64910ca2011-09-09 20:05:21 +00001267 if (T == Context.getObjCInstanceType())
1268 return Context.getObjCIdType();
1269
Douglas Gregor813a0662015-06-19 18:14:38 +00001270 return origType;
Douglas Gregor64910ca2011-09-09 20:05:21 +00001271}
1272
Douglas Gregor813a0662015-06-19 18:14:38 +00001273/// Determine the result type of a message send based on the receiver type,
1274/// method, and the kind of message send.
1275///
1276/// This is the "base" result type, which will still need to be adjusted
1277/// to account for nullability.
1278static QualType getBaseMessageSendResultType(Sema &S,
1279 QualType ReceiverType,
1280 ObjCMethodDecl *Method,
1281 bool isClassMessage,
1282 bool isSuperMessage) {
Douglas Gregor33823722011-06-11 01:09:30 +00001283 assert(Method && "Must have a method");
1284 if (!Method->hasRelatedResultType())
Douglas Gregore83b9562015-07-07 03:57:53 +00001285 return Method->getSendResultType(ReceiverType);
Douglas Gregor813a0662015-06-19 18:14:38 +00001286
1287 ASTContext &Context = S.Context;
1288
1289 // Local function that transfers the nullability of the method's
1290 // result type to the returned result.
1291 auto transferNullability = [&](QualType type) -> QualType {
1292 // If the method's result type has nullability, extract it.
Douglas Gregore83b9562015-07-07 03:57:53 +00001293 if (auto nullability = Method->getSendResultType(ReceiverType)
1294 ->getNullability(Context)){
Douglas Gregor813a0662015-06-19 18:14:38 +00001295 // Strip off any outer nullability sugar from the provided type.
1296 (void)AttributedType::stripOuterNullability(type);
1297
1298 // Form a new attributed type using the method result type's nullability.
1299 return Context.getAttributedType(
1300 AttributedType::getNullabilityAttrKind(*nullability),
1301 type,
1302 type);
1303 }
1304
1305 return type;
1306 };
1307
Douglas Gregor33823722011-06-11 01:09:30 +00001308 // If a method has a related return type:
1309 // - if the method found is an instance method, but the message send
1310 // was a class message send, T is the declared return type of the method
1311 // found
1312 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregore83b9562015-07-07 03:57:53 +00001313 return stripObjCInstanceType(Context,
1314 Method->getSendResultType(ReceiverType));
Douglas Gregor813a0662015-06-19 18:14:38 +00001315
1316 // - if the receiver is super, T is a pointer to the class of the
Douglas Gregor33823722011-06-11 01:09:30 +00001317 // enclosing method definition
1318 if (isSuperMessage) {
Douglas Gregor813a0662015-06-19 18:14:38 +00001319 if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
1320 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1321 return transferNullability(
1322 Context.getObjCObjectPointerType(
1323 Context.getObjCInterfaceType(Class)));
1324 }
Douglas Gregor33823722011-06-11 01:09:30 +00001325 }
Douglas Gregor813a0662015-06-19 18:14:38 +00001326
Douglas Gregor33823722011-06-11 01:09:30 +00001327 // - if the receiver is the name of a class U, T is a pointer to U
Douglas Gregore83b9562015-07-07 03:57:53 +00001328 if (ReceiverType->getAsObjCInterfaceType())
Douglas Gregor813a0662015-06-19 18:14:38 +00001329 return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
1330 // - if the receiver is of type Class or qualified Class type,
Douglas Gregor33823722011-06-11 01:09:30 +00001331 // T is the declared return type of the method.
1332 if (ReceiverType->isObjCClassType() ||
1333 ReceiverType->isObjCQualifiedClassType())
Douglas Gregore83b9562015-07-07 03:57:53 +00001334 return stripObjCInstanceType(Context,
1335 Method->getSendResultType(ReceiverType));
Douglas Gregor813a0662015-06-19 18:14:38 +00001336
Douglas Gregor33823722011-06-11 01:09:30 +00001337 // - if the receiver is id, qualified id, Class, or qualified Class, T
1338 // is the receiver type, otherwise
1339 // - T is the type of the receiver expression.
Douglas Gregor813a0662015-06-19 18:14:38 +00001340 return transferNullability(ReceiverType);
1341}
1342
1343QualType Sema::getMessageSendResultType(QualType ReceiverType,
1344 ObjCMethodDecl *Method,
1345 bool isClassMessage,
1346 bool isSuperMessage) {
1347 // Produce the result type.
1348 QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
1349 Method,
1350 isClassMessage,
1351 isSuperMessage);
1352
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001353 // If this is a class message, ignore the nullability of the receiver.
1354 if (isClassMessage)
1355 return resultType;
1356
Douglas Gregor813a0662015-06-19 18:14:38 +00001357 // Map the nullability of the result into a table index.
1358 unsigned receiverNullabilityIdx = 0;
1359 if (auto nullability = ReceiverType->getNullability(Context))
1360 receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1361
1362 unsigned resultNullabilityIdx = 0;
1363 if (auto nullability = resultType->getNullability(Context))
1364 resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1365
1366 // The table of nullability mappings, indexed by the receiver's nullability
1367 // and then the result type's nullability.
1368 static const uint8_t None = 0;
1369 static const uint8_t NonNull = 1;
1370 static const uint8_t Nullable = 2;
1371 static const uint8_t Unspecified = 3;
1372 static const uint8_t nullabilityMap[4][4] = {
1373 // None NonNull Nullable Unspecified
1374 /* None */ { None, None, Nullable, None },
1375 /* NonNull */ { None, NonNull, Nullable, Unspecified },
1376 /* Nullable */ { Nullable, Nullable, Nullable, Nullable },
1377 /* Unspecified */ { None, Unspecified, Nullable, Unspecified }
1378 };
1379
1380 unsigned newResultNullabilityIdx
1381 = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
1382 if (newResultNullabilityIdx == resultNullabilityIdx)
1383 return resultType;
1384
1385 // Strip off the existing nullability. This removes as little type sugar as
1386 // possible.
1387 do {
1388 if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
1389 resultType = attributed->getModifiedType();
1390 } else {
1391 resultType = resultType.getDesugaredType(Context);
1392 }
1393 } while (resultType->getNullability(Context));
1394
1395 // Add nullability back if needed.
1396 if (newResultNullabilityIdx > 0) {
1397 auto newNullability
1398 = static_cast<NullabilityKind>(newResultNullabilityIdx-1);
1399 return Context.getAttributedType(
1400 AttributedType::getNullabilityAttrKind(newNullability),
1401 resultType, resultType);
1402 }
1403
1404 return resultType;
Douglas Gregor33823722011-06-11 01:09:30 +00001405}
John McCall5f2d5562011-02-03 09:00:02 +00001406
John McCall5ec7e7d2013-03-19 07:04:25 +00001407/// Look for an ObjC method whose result type exactly matches the given type.
1408static const ObjCMethodDecl *
1409findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1410 QualType instancetype) {
Alp Toker314cc812014-01-25 16:55:45 +00001411 if (MD->getReturnType() == instancetype)
1412 return MD;
John McCall5ec7e7d2013-03-19 07:04:25 +00001413
1414 // For these purposes, a method in an @implementation overrides a
1415 // declaration in the @interface.
1416 if (const ObjCImplDecl *impl =
1417 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1418 const ObjCContainerDecl *iface;
1419 if (const ObjCCategoryImplDecl *catImpl =
1420 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1421 iface = catImpl->getCategoryDecl();
1422 } else {
1423 iface = impl->getClassInterface();
1424 }
1425
1426 const ObjCMethodDecl *ifaceMD =
1427 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1428 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1429 }
1430
1431 SmallVector<const ObjCMethodDecl *, 4> overrides;
1432 MD->getOverriddenMethods(overrides);
1433 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1434 if (const ObjCMethodDecl *result =
1435 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1436 return result;
1437 }
1438
Craig Topperc3ec1492014-05-26 06:22:03 +00001439 return nullptr;
John McCall5ec7e7d2013-03-19 07:04:25 +00001440}
1441
1442void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1443 // Only complain if we're in an ObjC method and the required return
1444 // type doesn't match the method's declared return type.
1445 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1446 if (!MD || !MD->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +00001447 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
John McCall5ec7e7d2013-03-19 07:04:25 +00001448 return;
1449
1450 // Look for a method overridden by this method which explicitly uses
1451 // 'instancetype'.
1452 if (const ObjCMethodDecl *overridden =
1453 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +00001454 SourceRange range = overridden->getReturnTypeSourceRange();
1455 SourceLocation loc = range.getBegin();
John McCall5ec7e7d2013-03-19 07:04:25 +00001456 if (loc.isInvalid())
1457 loc = overridden->getLocation();
1458 Diag(loc, diag::note_related_result_type_explicit)
1459 << /*current method*/ 1 << range;
1460 return;
1461 }
1462
1463 // Otherwise, if we have an interesting method family, note that.
1464 // This should always trigger if the above didn't.
1465 if (ObjCMethodFamily family = MD->getMethodFamily())
1466 Diag(MD->getLocation(), diag::note_related_result_type_family)
1467 << /*current method*/ 1
1468 << family;
1469}
1470
Douglas Gregor33823722011-06-11 01:09:30 +00001471void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1472 E = E->IgnoreParenImpCasts();
1473 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1474 if (!MsgSend)
1475 return;
1476
1477 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1478 if (!Method)
1479 return;
1480
1481 if (!Method->hasRelatedResultType())
1482 return;
Alp Toker314cc812014-01-25 16:55:45 +00001483
1484 if (Context.hasSameUnqualifiedType(
1485 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
Douglas Gregor33823722011-06-11 01:09:30 +00001486 return;
Alp Toker314cc812014-01-25 16:55:45 +00001487
1488 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
Douglas Gregorbab8a962011-09-08 01:46:34 +00001489 Context.getObjCInstanceType()))
1490 return;
1491
Douglas Gregor33823722011-06-11 01:09:30 +00001492 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1493 << Method->isInstanceMethod() << Method->getSelector()
1494 << MsgSend->getType();
1495}
1496
1497bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001498 MultiExprArg Args,
1499 Selector Sel,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001500 ArrayRef<SourceLocation> SelectorLocs,
1501 ObjCMethodDecl *Method,
Douglas Gregor33823722011-06-11 01:09:30 +00001502 bool isClassMessage, bool isSuperMessage,
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001503 SourceLocation lbrac, SourceLocation rbrac,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001504 SourceRange RecRange,
John McCall7decc9e2010-11-18 06:31:45 +00001505 QualType &ReturnType, ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001506 SourceLocation SelLoc;
1507 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1508 SelLoc = SelectorLocs.front();
1509 else
1510 SelLoc = lbrac;
1511
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001512 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001513 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001514 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001515 if (Args[i]->isTypeDependent())
1516 continue;
1517
John McCallcc5788c2013-03-04 07:34:02 +00001518 ExprResult result;
1519 if (getLangOpts().DebuggerSupport) {
1520 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001521 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001522 } else {
1523 result = DefaultArgumentPromotion(Args[i]);
1524 }
1525 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001526 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001527 Args[i] = result.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001528 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001529
John McCall31168b02011-06-15 23:02:42 +00001530 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001531 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001532 DiagID = diag::err_arc_method_not_found;
1533 else
1534 DiagID = isClassMessage ? diag::warn_class_method_not_found
1535 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001536 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001537 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahanian06499232013-06-18 17:10:58 +00001538 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001539 if (getLangOpts().ObjCAutoRefCount)
1540 DiagID = diag::error_method_not_found_with_typo;
1541 else
1542 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1543 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001544 Selector MatchedSel = OMD->getSelector();
1545 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian5ab87502014-08-12 22:16:41 +00001546 if (MatchedSel.isUnarySelector())
1547 Diag(SelLoc, DiagID)
1548 << Sel<< isClassMessage << MatchedSel
1549 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1550 else
1551 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001552 }
1553 else
1554 Diag(SelLoc, DiagID)
1555 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001556 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001557 // Find the class to which we are sending this message.
1558 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001559 if (ObjCInterfaceDecl *ThisClass =
1560 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
1561 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1562 if (!RecRange.isInvalid())
1563 if (ThisClass->lookupClassMethod(Sel))
1564 Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
1565 << FixItHint::CreateReplacement(RecRange,
1566 ThisClass->getNameAsString());
1567 }
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001568 }
1569 }
John McCall3f4138c2011-07-13 17:56:40 +00001570
1571 // In debuggers, we want to use __unknown_anytype for these
1572 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001573 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001574 ReturnType = Context.UnknownAnyTy;
1575 } else {
1576 ReturnType = Context.getObjCIdType();
1577 }
John McCall7decc9e2010-11-18 06:31:45 +00001578 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001579 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001580 }
Mike Stump11289f42009-09-09 15:08:12 +00001581
Douglas Gregor33823722011-06-11 01:09:30 +00001582 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1583 isSuperMessage);
Alp Toker314cc812014-01-25 16:55:45 +00001584 VK = Expr::getValueKindForType(Method->getReturnType());
Mike Stump11289f42009-09-09 15:08:12 +00001585
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001586 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001587 // Method might have more arguments than selector indicates. This is due
1588 // to addition of c-style arguments in method.
1589 if (Method->param_size() > Sel.getNumArgs())
1590 NumNamedArgs = Method->param_size();
1591 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001592 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001593 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001594 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001595 return false;
1596 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001597
Douglas Gregore83b9562015-07-07 03:57:53 +00001598 // Compute the set of type arguments to be substituted into each parameter
1599 // type.
1600 Optional<ArrayRef<QualType>> typeArgs
1601 = ReceiverType->getObjCSubstitutions(Method->getDeclContext());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001602 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001603 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001604 // We can't do any type-checking on a type-dependent argument.
1605 if (Args[i]->isTypeDependent())
1606 continue;
1607
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001608 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001609
Alp Toker03376dc2014-07-07 09:02:20 +00001610 ParmVarDecl *param = Method->parameters()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001611 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001612
John McCall4124c492011-10-17 18:40:02 +00001613 // Strip the unbridged-cast placeholder expression off unless it's
1614 // a consumed argument.
1615 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1616 !param->hasAttr<CFConsumedAttr>())
1617 argExpr = stripARCUnbridgedCast(argExpr);
1618
John McCallea0a39e2012-11-14 00:49:39 +00001619 // If the parameter is __unknown_anytype, infer its type
1620 // from the argument.
1621 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001622 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001623 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001624 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001625 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001626 } else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001627 Args[i] = argE.get();
John McCallea0a39e2012-11-14 00:49:39 +00001628
John McCallcc5788c2013-03-04 07:34:02 +00001629 // Update the parameter type in-place.
1630 param->setType(paramType);
1631 }
1632 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001633 }
1634
Douglas Gregore83b9562015-07-07 03:57:53 +00001635 QualType origParamType = param->getType();
1636 QualType paramType = param->getType();
1637 if (typeArgs)
1638 paramType = paramType.substObjCTypeArgs(
1639 Context,
1640 *typeArgs,
1641 ObjCSubstitutionContext::Parameter);
1642
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001643 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
Douglas Gregore83b9562015-07-07 03:57:53 +00001644 paramType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001645 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001646 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001647
Douglas Gregore83b9562015-07-07 03:57:53 +00001648 InitializedEntity Entity
1649 = InitializedEntity::InitializeParameter(Context, param, paramType);
Fariborz Jahaniana1db7df2014-07-31 17:39:50 +00001650 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001651 if (ArgE.isInvalid())
1652 IsError = true;
Douglas Gregore83b9562015-07-07 03:57:53 +00001653 else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001654 Args[i] = ArgE.getAs<Expr>();
Douglas Gregore83b9562015-07-07 03:57:53 +00001655
1656 // If we are type-erasing a block to a block-compatible
1657 // Objective-C pointer type, we may need to extend the lifetime
1658 // of the block object.
1659 if (typeArgs && Args[i]->isRValue() && paramType->isBlockPointerType() &&
Bob Wilson7e9fd562015-10-02 01:05:29 +00001660 Args[i]->getType()->isBlockPointerType() &&
1661 origParamType->isObjCObjectPointerType()) {
Douglas Gregore83b9562015-07-07 03:57:53 +00001662 ExprResult arg = Args[i];
1663 maybeExtendBlockObject(arg);
1664 Args[i] = arg.get();
1665 }
1666 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001667 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001668
1669 // Promote additional arguments to variadic methods.
1670 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001671 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001672 if (Args[i]->isTypeDependent())
1673 continue;
1674
Jordy Roseaca01f92012-05-12 17:32:52 +00001675 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
Craig Topperc3ec1492014-05-26 06:22:03 +00001676 nullptr);
John Wiegley01296292011-04-08 18:41:53 +00001677 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001678 Args[i] = Arg.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001679 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001680 } else {
1681 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001682 if (Args.size() != NumNamedArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00001683 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001684 diag::err_typecheck_call_too_many_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001685 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001686 << Method->getSourceRange()
Chris Lattner3b054132008-11-19 05:08:23 +00001687 << SourceRange(Args[NumNamedArgs]->getLocStart(),
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001688 Args.back()->getLocEnd());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001689 }
1690 }
1691
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001692 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001693
1694 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001695 IsError |= CheckObjCMethodCall(
Craig Topper8c2a2a02014-08-30 16:55:39 +00001696 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001697
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001698 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001699}
1700
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001701bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001702 // 'self' is objc 'self' in an objc method only.
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001703 ObjCMethodDecl *Method =
1704 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1705 return isSelfExpr(RExpr, Method);
1706}
1707
1708bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
John McCallfe96e0b2011-11-06 09:01:30 +00001709 if (!method) return false;
1710
John McCall31168b02011-06-15 23:02:42 +00001711 receiver = receiver->IgnoreParenLValueCasts();
1712 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001713 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001714 return true;
1715 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001716}
1717
John McCall526ab472011-10-25 17:37:35 +00001718/// LookupMethodInType - Look up a method in an ObjCObjectType.
1719ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1720 bool isInstance) {
1721 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1722 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1723 // Look it up in the main interface (and categories, etc.)
1724 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1725 return method;
1726
1727 // Okay, look for "private" methods declared in any
1728 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001729 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1730 return method;
John McCall526ab472011-10-25 17:37:35 +00001731 }
1732
1733 // Check qualifiers.
Aaron Ballman1683f7b2014-03-17 15:55:30 +00001734 for (const auto *I : objType->quals())
1735 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
John McCall526ab472011-10-25 17:37:35 +00001736 return method;
1737
Craig Topperc3ec1492014-05-26 06:22:03 +00001738 return nullptr;
John McCall526ab472011-10-25 17:37:35 +00001739}
1740
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001741/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1742/// list of a qualified objective pointer type.
1743ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1744 const ObjCObjectPointerType *OPT,
1745 bool Instance)
1746{
Craig Topperc3ec1492014-05-26 06:22:03 +00001747 ObjCMethodDecl *MD = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +00001748 for (const auto *PROTO : OPT->quals()) {
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001749 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1750 return MD;
1751 }
1752 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001753 return nullptr;
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001754}
1755
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001756/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1757/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001758ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001759HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001760 Expr *BaseExpr, SourceLocation OpLoc,
1761 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001762 SourceLocation MemberLoc,
1763 SourceLocation SuperLoc, QualType SuperType,
1764 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001765 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1766 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001767
Benjamin Kramer365082d2012-05-19 16:34:46 +00001768 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001769 Diag(MemberLoc, diag::err_invalid_property_name)
1770 << MemberName << QualType(OPT, 0);
1771 return ExprError();
1772 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001773
1774 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregord6459312011-04-20 18:19:55 +00001775
Douglas Gregor4123a862011-11-14 22:10:01 +00001776 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1777 : BaseExpr->getSourceRange();
1778 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001779 diag::err_property_not_found_forward_class,
1780 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001781 return ExprError();
Douglas Gregoracf4fd32015-11-03 01:15:46 +00001782
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001783 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001784 // Check whether we can reference this property.
1785 if (DiagnoseUseOfDecl(PD, MemberLoc))
1786 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001787 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001788 return new (Context)
1789 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1790 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001791 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001792 return new (Context)
1793 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1794 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001795 }
1796 // Check protocols on qualified interfaces.
Aaron Ballman83731462014-03-17 16:14:00 +00001797 for (const auto *I : OPT->quals())
1798 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001799 // Check whether we can reference this property.
1800 if (DiagnoseUseOfDecl(PD, MemberLoc))
1801 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001802
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001803 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001804 return new (Context) ObjCPropertyRefExpr(
1805 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1806 SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001807 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001808 return new (Context)
1809 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1810 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001811 }
1812 // If that failed, look for an "implicit" property by seeing if the nullary
1813 // selector is implemented.
1814
1815 // FIXME: The logic for looking up nullary and unary selectors should be
1816 // shared with the code in ActOnInstanceMessage.
1817
1818 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1819 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001820
1821 // May be founf in property's qualified list.
1822 if (!Getter)
1823 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001824
1825 // If this reference is in an @implementation, check for 'private' methods.
1826 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001827 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001828
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001829 if (Getter) {
1830 // Check if we can reference this property.
1831 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1832 return ExprError();
1833 }
1834 // If we found a getter then this may be a valid dot-reference, we
1835 // will look for the matching setter, in case it is needed.
1836 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001837 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1838 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001839 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001840
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001841 // May be founf in property's qualified list.
1842 if (!Setter)
1843 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1844
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001845 if (!Setter) {
1846 // If this reference is in an @implementation, also check for 'private'
1847 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001848 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001849 }
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001850
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001851 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1852 return ExprError();
1853
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001854 // Special warning if member name used in a property-dot for a setter accessor
1855 // does not use a property with same name; e.g. obj.X = ... for a property with
1856 // name 'x'.
1857 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor()
1858 && !IFace->FindPropertyDeclaration(Member)) {
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001859 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
1860 // Do not warn if user is using property-dot syntax to make call to
1861 // user named setter.
1862 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001863 Diag(MemberLoc,
1864 diag::warn_property_access_suggest)
1865 << MemberName << QualType(OPT, 0) << PDecl->getName()
1866 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001867 }
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001868 }
1869
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001870 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001871 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001872 return new (Context)
1873 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1874 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001875 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001876 return new (Context)
1877 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1878 OK_ObjCProperty, MemberLoc, BaseExpr);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001879
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001880 }
1881
1882 // Attempt to correct for typos in property names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001883 if (TypoCorrection Corrected =
1884 CorrectTypo(DeclarationNameInfo(MemberName, MemberLoc),
1885 LookupOrdinaryName, nullptr, nullptr,
1886 llvm::make_unique<DeclFilterCCC<ObjCPropertyDecl>>(),
1887 CTK_ErrorRecovery, IFace, false, OPT)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001888 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1889 << MemberName << QualType(OPT, 0));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001890 DeclarationName TypoResult = Corrected.getCorrection();
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001891 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1892 TypoResult, MemberLoc,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001893 SuperLoc, SuperType, Super);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001894 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001895 ObjCInterfaceDecl *ClassDeclared;
1896 if (ObjCIvarDecl *Ivar =
1897 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1898 QualType T = Ivar->getType();
1899 if (const ObjCObjectPointerType * OBJPT =
1900 T->getAsObjCInterfacePointerType()) {
Douglas Gregor4123a862011-11-14 22:10:01 +00001901 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001902 diag::err_property_not_as_forward_class,
1903 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001904 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001905 }
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001906 Diag(MemberLoc,
1907 diag::err_ivar_access_using_property_syntax_suggest)
1908 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1909 << FixItHint::CreateReplacement(OpLoc, "->");
1910 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001911 }
Chris Lattner90c58fa2010-04-11 07:51:10 +00001912
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001913 Diag(MemberLoc, diag::err_property_not_found)
1914 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001915 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001916 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001917 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001918 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001919}
1920
1921
1922
John McCalldadc5752010-08-24 06:29:42 +00001923ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001924ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1925 IdentifierInfo &propertyName,
1926 SourceLocation receiverNameLoc,
1927 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001928
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001929 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001930 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1931 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001932
Douglas Gregore83b9562015-07-07 03:57:53 +00001933 QualType SuperType;
Craig Topperc3ec1492014-05-26 06:22:03 +00001934 if (!IFace) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001935 // If the "receiver" is 'super' in a method, handle it as an expression-like
1936 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001937 if (receiverNamePtr->isStr("super")) {
Eli Friedman24af8502012-02-03 22:47:37 +00001938 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Douglas Gregore83b9562015-07-07 03:57:53 +00001939 if (auto classDecl = CurMethod->getClassInterface()) {
1940 SuperType = QualType(classDecl->getSuperClassType(), 0);
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001941 if (CurMethod->isInstanceMethod()) {
Douglas Gregore83b9562015-07-07 03:57:53 +00001942 if (SuperType.isNull()) {
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001943 // The current class does not have a superclass.
1944 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
Douglas Gregore83b9562015-07-07 03:57:53 +00001945 << CurMethod->getClassInterface()->getIdentifier();
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001946 return ExprError();
1947 }
Douglas Gregore83b9562015-07-07 03:57:53 +00001948 QualType T = Context.getObjCObjectPointerType(SuperType);
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001949
Douglas Gregore83b9562015-07-07 03:57:53 +00001950 return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(),
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001951 /*BaseExpr*/nullptr,
1952 SourceLocation()/*OpLoc*/,
1953 &propertyName,
1954 propertyNameLoc,
1955 receiverNameLoc, T, true);
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00001956 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001957
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001958 // Otherwise, if this is a class method, try dispatching to our
1959 // superclass.
Douglas Gregore83b9562015-07-07 03:57:53 +00001960 IFace = CurMethod->getClassInterface()->getSuperClass();
Chris Lattnera36ec422010-04-11 08:28:14 +00001961 }
Chris Lattnera36ec422010-04-11 08:28:14 +00001962 }
John McCall5f2d5562011-02-03 09:00:02 +00001963 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001964
1965 if (!IFace) {
Alp Tokerec543272013-12-24 09:48:30 +00001966 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1967 << tok::l_paren;
Chris Lattnera36ec422010-04-11 08:28:14 +00001968 return ExprError();
1969 }
1970 }
1971
1972 // Search for a declared property first.
Steve Naroff9527bbf2009-03-09 21:12:44 +00001973 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001974 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001975
1976 // If this reference is in an @implementation, check for 'private' methods.
1977 if (!Getter)
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001978 Getter = IFace->lookupPrivateClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001979
1980 if (Getter) {
1981 // FIXME: refactor/share with ActOnMemberReference().
1982 // Check if we can reference this property.
1983 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1984 return ExprError();
1985 }
Mike Stump11289f42009-09-09 15:08:12 +00001986
Steve Naroff9527bbf2009-03-09 21:12:44 +00001987 // Look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00001988 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001989 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
Douglas Gregore83b9562015-07-07 03:57:53 +00001990 PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001991 &propertyName);
Mike Stump11289f42009-09-09 15:08:12 +00001992
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001993 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001994 if (!Setter) {
1995 // If this reference is in an @implementation, also check for 'private'
1996 // methods.
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001997 Setter = IFace->lookupPrivateClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001998 }
1999 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002000 if (!Setter)
2001 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002002
2003 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
2004 return ExprError();
2005
2006 if (Getter || Setter) {
Douglas Gregore83b9562015-07-07 03:57:53 +00002007 if (!SuperType.isNull())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002008 return new (Context)
2009 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2010 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
Douglas Gregore83b9562015-07-07 03:57:53 +00002011 SuperType);
Douglas Gregor33823722011-06-11 01:09:30 +00002012
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002013 return new (Context) ObjCPropertyRefExpr(
2014 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
2015 propertyNameLoc, receiverNameLoc, IFace);
Steve Naroff9527bbf2009-03-09 21:12:44 +00002016 }
2017 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
2018 << &propertyName << Context.getObjCInterfaceType(IFace));
2019}
2020
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002021namespace {
2022
2023class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
2024 public:
2025 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
2026 // Determine whether "super" is acceptable in the current context.
2027 if (Method && Method->getClassInterface())
2028 WantObjCSuper = Method->getClassInterface()->getSuperClass();
2029 }
2030
Craig Toppere14c0f82014-03-12 04:55:44 +00002031 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002032 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
2033 candidate.isKeyword("super");
2034 }
2035};
2036
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002037}
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002038
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002039Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00002040 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002041 SourceLocation NameLoc,
2042 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00002043 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00002044 ParsedType &ReceiverType) {
2045 ReceiverType = ParsedType();
Douglas Gregore5798dc2010-04-21 20:38:13 +00002046
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002047 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00002048 // messaging super. If the identifier is "super" and there is a
2049 // trailing dot, it's an instance message.
2050 if (IsSuper && S->isInObjcMethodScope())
2051 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002052
2053 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
2054 LookupName(Result, S);
2055
2056 switch (Result.getResultKind()) {
2057 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00002058 // Normal name lookup didn't find anything. If we're in an
2059 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00002060 // FIXME: This is a hack. Ivar lookup should be part of normal
2061 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00002062 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00002063 if (!Method->getClassInterface()) {
2064 // Fall back: let the parser try to parse it as an instance message.
2065 return ObjCInstanceMessage;
2066 }
2067
Douglas Gregorca7136b2010-04-19 20:09:36 +00002068 ObjCInterfaceDecl *ClassDeclared;
2069 if (Method->getClassInterface()->lookupInstanceVariable(Name,
2070 ClassDeclared))
2071 return ObjCInstanceMessage;
2072 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00002073
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002074 // Break out; we'll perform typo correction below.
2075 break;
2076
2077 case LookupResult::NotFoundInCurrentInstantiation:
2078 case LookupResult::FoundOverloaded:
2079 case LookupResult::FoundUnresolvedValue:
2080 case LookupResult::Ambiguous:
2081 Result.suppressDiagnostics();
2082 return ObjCInstanceMessage;
2083
2084 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00002085 // If the identifier is a class or not, and there is a trailing dot,
2086 // it's an instance message.
2087 if (HasTrailingDot)
2088 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002089 // We found something. If it's a type, then we have a class
2090 // message. Otherwise, it's an instance message.
2091 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00002092 QualType T;
2093 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
2094 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00002095 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00002096 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00002097 DiagnoseUseOfDecl(Type, NameLoc);
2098 }
2099 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00002100 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002101
Douglas Gregore5798dc2010-04-21 20:38:13 +00002102 // We have a class message, and T is the type we're
2103 // messaging. Build source-location information for it.
2104 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00002105 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00002106 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002107 }
2108 }
2109
Kaelyn Takata89c881b2014-10-27 18:07:29 +00002110 if (TypoCorrection Corrected = CorrectTypo(
2111 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr,
2112 llvm::make_unique<ObjCInterfaceOrSuperCCC>(getCurMethodDecl()),
2113 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002114 if (Corrected.isKeyword()) {
2115 // If we've found the keyword "super" (the only keyword that would be
2116 // returned by CorrectTypo), this is a send to super.
Richard Smithf9b15102013-08-17 00:46:16 +00002117 diagnoseTypo(Corrected,
2118 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00002119 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002120 } else if (ObjCInterfaceDecl *Class =
Richard Smithf9b15102013-08-17 00:46:16 +00002121 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002122 // If we found a declaration, correct when it refers to an Objective-C
2123 // class.
Richard Smithf9b15102013-08-17 00:46:16 +00002124 diagnoseTypo(Corrected,
2125 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00002126 QualType T = Context.getObjCInterfaceType(Class);
2127 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2128 ReceiverType = CreateParsedType(T, TSInfo);
2129 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002130 }
2131 }
Richard Smithf9b15102013-08-17 00:46:16 +00002132
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00002133 // Fall back: let the parser try to parse it as an instance message.
2134 return ObjCInstanceMessage;
2135}
Steve Naroff9527bbf2009-03-09 21:12:44 +00002136
John McCalldadc5752010-08-24 06:29:42 +00002137ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002138 SourceLocation SuperLoc,
2139 Selector Sel,
2140 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002141 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002142 SourceLocation RBracLoc,
2143 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002144 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00002145 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00002146 if (!Method) {
2147 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
2148 return ExprError();
2149 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002150
Douglas Gregor4fdba132010-04-21 20:01:04 +00002151 ObjCInterfaceDecl *Class = Method->getClassInterface();
2152 if (!Class) {
2153 Diag(SuperLoc, diag::error_no_super_class_message)
2154 << Method->getDeclName();
2155 return ExprError();
2156 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002157
Douglas Gregore83b9562015-07-07 03:57:53 +00002158 QualType SuperTy(Class->getSuperClassType(), 0);
2159 if (SuperTy.isNull()) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002160 // The current class does not have a superclass.
Ted Kremenek499897b2011-01-23 17:21:34 +00002161 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
2162 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002163 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002164 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002165
Douglas Gregor4fdba132010-04-21 20:01:04 +00002166 // We are in a method whose class has a superclass, so 'super'
2167 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00002168 if (Method->getSelector() == Sel)
2169 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00002170
Jordan Rose2afd6612012-10-19 16:05:26 +00002171 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00002172 // Since we are in an instance method, this is an instance
2173 // message to the superclass instance.
Douglas Gregor4fdba132010-04-21 20:01:04 +00002174 SuperTy = Context.getObjCObjectPointerType(SuperTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00002175 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2176 Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002177 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002178 }
Douglas Gregor4fdba132010-04-21 20:01:04 +00002179
2180 // Since we are in a class method, this is a class message to
2181 // the superclass.
Craig Topperc3ec1492014-05-26 06:22:03 +00002182 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
Douglas Gregore83b9562015-07-07 03:57:53 +00002183 SuperTy,
Craig Topperc3ec1492014-05-26 06:22:03 +00002184 SuperLoc, Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002185 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002186}
2187
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002188
2189ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2190 bool isSuperReceiver,
2191 SourceLocation Loc,
2192 Selector Sel,
2193 ObjCMethodDecl *Method,
2194 MultiExprArg Args) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002195 TypeSourceInfo *receiverTypeInfo = nullptr;
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002196 if (!ReceiverType.isNull())
2197 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2198
2199 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2200 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2201 Sel, Method, Loc, Loc, Loc, Args,
2202 /*isImplicit=*/true);
2203
2204}
2205
Ted Kremeneke65b0862012-03-06 20:05:56 +00002206static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2207 unsigned DiagID,
2208 bool (*refactor)(const ObjCMessageExpr *,
2209 const NSAPI &, edit::Commit &)) {
2210 SourceLocation MsgLoc = Msg->getExprLoc();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002211 if (S.Diags.isIgnored(DiagID, MsgLoc))
Ted Kremeneke65b0862012-03-06 20:05:56 +00002212 return;
2213
2214 SourceManager &SM = S.SourceMgr;
2215 edit::Commit ECommit(SM, S.LangOpts);
2216 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2217 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2218 << Msg->getSelector() << Msg->getSourceRange();
2219 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2220 if (!ECommit.isCommitable())
2221 return;
2222 for (edit::Commit::edit_iterator
2223 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2224 const edit::Commit::Edit &Edit = *I;
2225 switch (Edit.Kind) {
2226 case edit::Commit::Act_Insert:
2227 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2228 Edit.Text,
2229 Edit.BeforePrev));
2230 break;
2231 case edit::Commit::Act_InsertFromRange:
2232 Builder.AddFixItHint(
2233 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2234 Edit.getInsertFromRange(SM),
2235 Edit.BeforePrev));
2236 break;
2237 case edit::Commit::Act_Remove:
2238 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2239 break;
2240 }
2241 }
2242 }
2243}
2244
2245static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2246 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2247 edit::rewriteObjCRedundantCallWithLiteral);
2248}
2249
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002250/// \brief Diagnose use of %s directive in an NSString which is being passed
2251/// as formatting string to formatting method.
2252static void
2253DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2254 ObjCMethodDecl *Method,
2255 Selector Sel,
2256 Expr **Args, unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002257 unsigned Idx = 0;
2258 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002259 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2260 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002261 Idx = 0;
2262 Format = true;
2263 }
2264 else if (Method) {
2265 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2266 if (S.GetFormatNSStringIdx(I, Idx)) {
2267 Format = true;
2268 break;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002269 }
2270 }
2271 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002272 if (!Format || NumArgs <= Idx)
2273 return;
2274
2275 Expr *FormatExpr = Args[Idx];
2276 if (ObjCStringLiteral *OSL =
2277 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2278 StringLiteral *FormatString = OSL->getString();
2279 if (S.FormatStringHasSArg(FormatString)) {
2280 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2281 << "%s" << 0 << 0;
2282 if (Method)
2283 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2284 << Method->getDeclName();
2285 }
2286 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002287}
2288
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002289/// \brief Build an Objective-C class message expression.
2290///
2291/// This routine takes care of both normal class messages and
2292/// class messages to the superclass.
2293///
2294/// \param ReceiverTypeInfo Type source information that describes the
2295/// receiver of this message. This may be NULL, in which case we are
2296/// sending to the superclass and \p SuperLoc must be a valid source
2297/// location.
2298
2299/// \param ReceiverType The type of the object receiving the
2300/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2301/// type as that refers to. For a superclass send, this is the type of
2302/// the superclass.
2303///
2304/// \param SuperLoc The location of the "super" keyword in a
2305/// superclass message.
2306///
2307/// \param Sel The selector to which the message is being sent.
2308///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002309/// \param Method The method that this class message is invoking, if
2310/// already known.
2311///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002312/// \param LBracLoc The location of the opening square bracket ']'.
2313///
James Dennettffad8b72012-06-22 08:10:18 +00002314/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002315///
James Dennettffad8b72012-06-22 08:10:18 +00002316/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002317ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002318 QualType ReceiverType,
2319 SourceLocation SuperLoc,
2320 Selector Sel,
2321 ObjCMethodDecl *Method,
2322 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002323 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002324 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002325 MultiExprArg ArgsIn,
2326 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002327 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002328 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002329 if (LBracLoc.isInvalid()) {
2330 Diag(Loc, diag::err_missing_open_square_message_send)
2331 << FixItHint::CreateInsertion(Loc, "[");
2332 LBracLoc = Loc;
2333 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002334 SourceLocation SelLoc;
2335 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2336 SelLoc = SelectorLocs.front();
2337 else
2338 SelLoc = Loc;
2339
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002340 if (ReceiverType->isDependentType()) {
2341 // If the receiver type is dependent, we can't type-check anything
2342 // at this point. Build a dependent expression.
2343 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002344 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002345 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002346 return ObjCMessageExpr::Create(
2347 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2348 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2349 isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002350 }
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002351
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002352 // Find the class to which we are sending this message.
Craig Topperc3ec1492014-05-26 06:22:03 +00002353 ObjCInterfaceDecl *Class = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00002354 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2355 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002356 Diag(Loc, diag::err_invalid_receiver_class_message)
2357 << ReceiverType;
2358 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002359 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002360 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002361 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002362 if (!getLangOpts().CPlusPlus)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002363 (void)DiagnoseUseOfDecl(Class, SelLoc);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002364 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002365 if (!Method) {
Douglas Gregor4123a862011-11-14 22:10:01 +00002366 SourceRange TypeRange
2367 = SuperLoc.isValid()? SourceRange(SuperLoc)
2368 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002369 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002370 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002371 ? diag::err_arc_receiver_forward_class
2372 : diag::warn_receiver_forward_class),
2373 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002374 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorb5186b12010-04-22 17:01:48 +00002375 Method = LookupFactoryMethodInGlobalPool(Sel,
2376 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002377 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002378 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2379 << Method->getDeclName();
2380 }
2381 if (!Method)
2382 Method = Class->lookupClassMethod(Sel);
2383
2384 // If we have an implementation in scope, check "private" methods.
2385 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002386 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002387
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002388 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002389 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002390 }
Mike Stump11289f42009-09-09 15:08:12 +00002391
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002392 // Check the argument types and determine the result type.
2393 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002394 ExprValueKind VK = VK_RValue;
2395
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002396 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002397 Expr **Args = ArgsIn.data();
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002398 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2399 Sel, SelectorLocs,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00002400 Method, true,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002401 SuperLoc.isValid(), LBracLoc, RBracLoc,
2402 SourceRange(),
Douglas Gregor33823722011-06-11 01:09:30 +00002403 ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002404 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002405
Alp Toker314cc812014-01-25 16:55:45 +00002406 if (Method && !Method->getReturnType()->isVoidType() &&
2407 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002408 diag::err_illegal_message_expr_incomplete_type))
2409 return ExprError();
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002410
Fariborz Jahaniane8b45502014-08-22 19:52:49 +00002411 // Warn about explicit call of +initialize on its own class. But not on 'super'.
Fariborz Jahanian42292282014-08-25 21:27:38 +00002412 if (Method && Method->getMethodFamily() == OMF_initialize) {
2413 if (!SuperLoc.isValid()) {
2414 const ObjCInterfaceDecl *ID =
2415 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2416 if (ID == Class) {
2417 Diag(Loc, diag::warn_direct_initialize_call);
2418 Diag(Method->getLocation(), diag::note_method_declared_at)
2419 << Method->getDeclName();
2420 }
2421 }
2422 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2423 // [super initialize] is allowed only within an +initialize implementation
2424 if (CurMeth->getMethodFamily() != OMF_initialize) {
2425 Diag(Loc, diag::warn_direct_super_initialize_call);
2426 Diag(Method->getLocation(), diag::note_method_declared_at)
2427 << Method->getDeclName();
2428 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2429 << CurMeth->getDeclName();
2430 }
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002431 }
2432 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002433
2434 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2435
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002436 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002437 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002438 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002439 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002440 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002441 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002442 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002443 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002444 else {
John McCall7decc9e2010-11-18 06:31:45 +00002445 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002446 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002447 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002448 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002449 if (!isImplicit)
2450 checkCocoaAPI(*this, Result);
2451 }
Douglas Gregoraae38d62010-05-22 05:17:18 +00002452 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002453}
2454
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002455// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002456// ArgExprs is optional - if it is present, the number of expressions
2457// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002458ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002459 ParsedType Receiver,
2460 Selector Sel,
2461 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002462 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002463 SourceLocation RBracLoc,
2464 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002465 TypeSourceInfo *ReceiverTypeInfo;
2466 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2467 if (ReceiverType.isNull())
2468 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002469
Mike Stump11289f42009-09-09 15:08:12 +00002470
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002471 if (!ReceiverTypeInfo)
2472 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2473
2474 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002475 /*SuperLoc=*/SourceLocation(), Sel,
2476 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2477 Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002478}
2479
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002480ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2481 QualType ReceiverType,
2482 SourceLocation Loc,
2483 Selector Sel,
2484 ObjCMethodDecl *Method,
2485 MultiExprArg Args) {
2486 return BuildInstanceMessage(Receiver, ReceiverType,
2487 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2488 Sel, Method, Loc, Loc, Loc, Args,
2489 /*isImplicit=*/true);
2490}
2491
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002492/// \brief Build an Objective-C instance message expression.
2493///
2494/// This routine takes care of both normal instance messages and
2495/// instance messages to the superclass instance.
2496///
2497/// \param Receiver The expression that computes the object that will
2498/// receive this message. This may be empty, in which case we are
2499/// sending to the superclass instance and \p SuperLoc must be a valid
2500/// source location.
2501///
2502/// \param ReceiverType The (static) type of the object receiving the
2503/// message. When a \p Receiver expression is provided, this is the
2504/// same type as that expression. For a superclass instance send, this
2505/// is a pointer to the type of the superclass.
2506///
2507/// \param SuperLoc The location of the "super" keyword in a
2508/// superclass instance message.
2509///
2510/// \param Sel The selector to which the message is being sent.
2511///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002512/// \param Method The method that this instance message is invoking, if
2513/// already known.
2514///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002515/// \param LBracLoc The location of the opening square bracket ']'.
2516///
James Dennettffad8b72012-06-22 08:10:18 +00002517/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002518///
James Dennettffad8b72012-06-22 08:10:18 +00002519/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002520ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002521 QualType ReceiverType,
2522 SourceLocation SuperLoc,
2523 Selector Sel,
2524 ObjCMethodDecl *Method,
2525 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002526 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002527 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002528 MultiExprArg ArgsIn,
2529 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002530 // The location of the receiver.
2531 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002532 SourceRange RecRange =
2533 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2534 SourceLocation SelLoc;
2535 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2536 SelLoc = SelectorLocs.front();
2537 else
2538 SelLoc = Loc;
2539
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002540 if (LBracLoc.isInvalid()) {
2541 Diag(Loc, diag::err_missing_open_square_message_send)
2542 << FixItHint::CreateInsertion(Loc, "[");
2543 LBracLoc = Loc;
2544 }
2545
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002546 // If we have a receiver expression, perform appropriate promotions
2547 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002548 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002549 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002550 ExprResult Result;
2551 if (Receiver->getType() == Context.UnknownAnyTy)
2552 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2553 else
2554 Result = CheckPlaceholderExpr(Receiver);
2555 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002556 Receiver = Result.get();
John McCall4124c492011-10-17 18:40:02 +00002557 }
2558
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002559 if (Receiver->isTypeDependent()) {
2560 // If the receiver is type-dependent, we can't type-check anything
2561 // at this point. Build a dependent expression.
2562 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002563 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002564 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002565 return ObjCMessageExpr::Create(
2566 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2567 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2568 RBracLoc, isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002569 }
2570
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002571 // If necessary, apply function/array conversion to the receiver.
2572 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002573 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2574 if (Result.isInvalid())
2575 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002576 Receiver = Result.get();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002577 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002578
2579 // If the receiver is an ObjC pointer, a block pointer, or an
2580 // __attribute__((NSObject)) pointer, we don't need to do any
2581 // special conversion in order to look up a receiver.
2582 if (ReceiverType->isObjCRetainableType()) {
2583 // do nothing
2584 } else if (!getLangOpts().ObjCAutoRefCount &&
2585 !Context.getObjCIdType().isNull() &&
2586 (ReceiverType->isPointerType() ||
2587 ReceiverType->isIntegerType())) {
2588 // Implicitly convert integers and pointers to 'id' but emit a warning.
2589 // But not in ARC.
2590 Diag(Loc, diag::warn_bad_receiver_type)
2591 << ReceiverType
2592 << Receiver->getSourceRange();
2593 if (ReceiverType->isPointerType()) {
2594 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002595 CK_CPointerToObjCPointerCast).get();
John McCall80c93a02013-03-01 09:20:14 +00002596 } else {
2597 // TODO: specialized warning on null receivers?
2598 bool IsNull = Receiver->isNullPointerConstant(Context,
2599 Expr::NPC_ValueDependentIsNull);
2600 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2601 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002602 Kind).get();
John McCall80c93a02013-03-01 09:20:14 +00002603 }
2604 ReceiverType = Receiver->getType();
2605 } else if (getLangOpts().CPlusPlus) {
Douglas Gregor4b60a152013-11-07 22:34:54 +00002606 // The receiver must be a complete type.
2607 if (RequireCompleteType(Loc, Receiver->getType(),
2608 diag::err_incomplete_receiver_type))
2609 return ExprError();
2610
John McCall80c93a02013-03-01 09:20:14 +00002611 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2612 if (result.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002613 Receiver = result.get();
John McCall80c93a02013-03-01 09:20:14 +00002614 ReceiverType = Receiver->getType();
2615 }
2616 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002617 }
2618
John McCall80c93a02013-03-01 09:20:14 +00002619 // There's a somewhat weird interaction here where we assume that we
2620 // won't actually have a method unless we also don't need to do some
2621 // of the more detailed type-checking on the receiver.
2622
Douglas Gregorb5186b12010-04-22 17:01:48 +00002623 if (!Method) {
Douglas Gregorab209d82015-07-07 03:58:42 +00002624 // Handle messages to id and __kindof types (where we use the
2625 // global method pool).
2626 // FIXME: The type bound is currently ignored by lookup in the
2627 // global pool.
2628 const ObjCObjectType *typeBound = nullptr;
2629 bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
2630 typeBound);
2631 if (receiverIsIdLike || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002632 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2633 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002634 SourceRange(LBracLoc, RBracLoc),
Douglas Gregorab209d82015-07-07 03:58:42 +00002635 receiverIsIdLike);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002636 if (!Method)
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002637 Method = LookupFactoryMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002638 SourceRange(LBracLoc,RBracLoc),
Douglas Gregorab209d82015-07-07 03:58:42 +00002639 receiverIsIdLike);
Fariborz Jahanian05e77f82014-11-07 23:51:15 +00002640 if (Method) {
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002641 if (ObjCMethodDecl *BestMethod =
Fariborz Jahaniand288fad2014-08-13 23:38:04 +00002642 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002643 Method = BestMethod;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002644 if (!AreMultipleMethodsInGlobalPool(Sel, Method,
2645 SourceRange(LBracLoc, RBracLoc),
Douglas Gregorab209d82015-07-07 03:58:42 +00002646 receiverIsIdLike)) {
Sylvestre Ledru30f17082014-11-17 18:26:39 +00002647 DiagnoseUseOfDecl(Method, SelLoc);
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002648 }
Fariborz Jahanian05e77f82014-11-07 23:51:15 +00002649 }
Douglas Gregorab209d82015-07-07 03:58:42 +00002650 } else if (ReceiverType->isObjCClassOrClassKindOfType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002651 ReceiverType->isObjCQualifiedClassType()) {
2652 // Handle messages to Class.
Nico Weber2e0c8f72014-12-27 03:58:08 +00002653 // We allow sending a message to a qualified Class ("Class<foo>"), which
2654 // is ok as long as one of the protocols implements the selector (if not,
2655 // warn).
Douglas Gregorab209d82015-07-07 03:58:42 +00002656 if (!ReceiverType->isObjCClassOrClassKindOfType()) {
2657 const ObjCObjectPointerType *QClassTy
2658 = ReceiverType->getAsObjCQualifiedClassType();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002659 // Search protocols for class methods.
2660 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2661 if (!Method) {
2662 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2663 // warn if instance method found for a Class message.
2664 if (Method) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002665 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002666 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002667 Diag(Method->getLocation(), diag::note_method_declared_at)
2668 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002669 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002670 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002671 } else {
2672 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2673 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2674 // First check the public methods in the class interface.
2675 Method = ClassDecl->lookupClassMethod(Sel);
2676
2677 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002678 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002679 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002680 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002681 return ExprError();
2682 }
2683 if (!Method) {
2684 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002685 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002686 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002687 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002688 if (!Method) {
2689 // If no class (factory) method was found, check if an _instance_
2690 // method of the same name exists in the root class only.
2691 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002692 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002693 if (Method)
2694 if (const ObjCInterfaceDecl *ID =
2695 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2696 if (ID->getSuperClass())
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002697 Diag(SelLoc, diag::warn_root_inst_method_not_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002698 << Sel << SourceRange(LBracLoc, RBracLoc);
2699 }
2700 }
Fariborz Jahaniand288fad2014-08-13 23:38:04 +00002701 if (Method)
2702 if (ObjCMethodDecl *BestMethod =
2703 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
2704 Method = BestMethod;
Douglas Gregor9a129192010-04-21 00:45:42 +00002705 }
2706 }
2707 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002708 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002709 ObjCInterfaceDecl *ClassDecl = nullptr;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002710
2711 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2712 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002713 // And as long as message is not deprecated/unavailable (warn if it is).
Douglas Gregorb5186b12010-04-22 17:01:48 +00002714 if (const ObjCObjectPointerType *QIdTy
2715 = ReceiverType->getAsObjCQualifiedIdType()) {
2716 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002717 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2718 if (!Method)
2719 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002720 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002721 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002722 } else if (const ObjCObjectPointerType *OCIType
2723 = ReceiverType->getAsObjCInterfacePointerType()) {
2724 // We allow sending a message to a pointer to an interface (an object).
2725 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002726
Douglas Gregor4123a862011-11-14 22:10:01 +00002727 // Try to complete the type. Under ARC, this is a hard error from which
2728 // we don't try to recover.
Craig Topperc3ec1492014-05-26 06:22:03 +00002729 const ObjCInterfaceDecl *forwardClass = nullptr;
Douglas Gregor4123a862011-11-14 22:10:01 +00002730 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002731 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002732 ? diag::err_arc_receiver_forward_instance
2733 : diag::warn_receiver_forward_instance,
2734 Receiver? Receiver->getSourceRange()
2735 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002736 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002737 return ExprError();
2738
2739 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanianc934de62012-02-03 01:02:44 +00002740 Diag(Receiver ? Receiver->getLocStart()
2741 : SuperLoc, diag::note_receiver_is_id);
Craig Topperc3ec1492014-05-26 06:22:03 +00002742 Method = nullptr;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002743 } else {
2744 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002745 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002746
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002747 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002748 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002749 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2750
Douglas Gregorb5186b12010-04-22 17:01:48 +00002751 if (!Method) {
2752 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002753 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002754
David Blaikiebbafb8a2012-03-11 07:00:24 +00002755 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002756 Diag(SelLoc, diag::err_arc_may_not_respond)
2757 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002758 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002759 return ExprError();
2760 }
2761
Douglas Gregor486b74e2011-09-27 16:10:05 +00002762 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002763 // If we still haven't found a method, look in the global pool. This
2764 // behavior isn't very desirable, however we need it for GCC
2765 // compatibility. FIXME: should we deviate??
2766 if (OCIType->qual_empty()) {
2767 Method = LookupInstanceMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002768 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian890803f2015-04-15 17:26:21 +00002769 if (Method) {
2770 if (auto BestMethod =
2771 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
2772 Method = BestMethod;
2773 AreMultipleMethodsInGlobalPool(Sel, Method,
2774 SourceRange(LBracLoc, RBracLoc),
2775 true);
2776 }
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002777 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002778 Diag(SelLoc, diag::warn_maynot_respond)
2779 << OCIType->getInterfaceDecl()->getIdentifier()
2780 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002781 }
2782 }
2783 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002784 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002785 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002786 } else {
John McCall80c93a02013-03-01 09:20:14 +00002787 // Reject other random receiver types (e.g. structs).
2788 Diag(Loc, diag::err_bad_receiver_type)
2789 << ReceiverType << Receiver->getSourceRange();
2790 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002791 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002792 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002793 }
Mike Stump11289f42009-09-09 15:08:12 +00002794
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002795 FunctionScopeInfo *DIFunctionScopeInfo =
2796 (Method && Method->getMethodFamily() == OMF_init)
Craig Topperc3ec1492014-05-26 06:22:03 +00002797 ? getEnclosingFunction() : nullptr;
2798
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002799 if (DIFunctionScopeInfo &&
2800 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002801 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2802 bool isDesignatedInitChain = false;
2803 if (SuperLoc.isValid()) {
2804 if (const ObjCObjectPointerType *
2805 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2806 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
Argyrios Kyrtzidisd664a342013-12-13 03:48:17 +00002807 // Either we know this is a designated initializer or we
2808 // conservatively assume it because we don't know for sure.
2809 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2810 ID->isDesignatedInitializer(Sel)) {
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002811 isDesignatedInitChain = true;
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002812 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002813 }
2814 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002815 }
2816 }
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002817 if (!isDesignatedInitChain) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002818 const ObjCMethodDecl *InitMethod = nullptr;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002819 bool isDesignated =
2820 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2821 assert(isDesignated && InitMethod);
2822 (void)isDesignated;
2823 Diag(SelLoc, SuperLoc.isValid() ?
2824 diag::warn_objc_designated_init_non_designated_init_call :
2825 diag::warn_objc_designated_init_non_super_designated_init_call);
2826 Diag(InitMethod->getLocation(),
2827 diag::note_objc_designated_init_marked_here);
2828 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002829 }
2830
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002831 if (DIFunctionScopeInfo &&
2832 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002833 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2834 if (SuperLoc.isValid()) {
2835 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2836 } else {
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002837 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002838 }
2839 }
2840
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002841 // Check the message arguments.
2842 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002843 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002844 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002845 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00002846 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2847 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002848 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2849 Sel, SelectorLocs, Method,
Douglas Gregor33823722011-06-11 01:09:30 +00002850 ClassMessage, SuperLoc.isValid(),
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002851 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002852 return ExprError();
Alp Toker314cc812014-01-25 16:55:45 +00002853
2854 if (Method && !Method->getReturnType()->isVoidType() &&
2855 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002856 diag::err_illegal_message_expr_incomplete_type))
2857 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00002858
John McCall31168b02011-06-15 23:02:42 +00002859 // In ARC, forbid the user from sending messages to
2860 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002861 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002862 ObjCMethodFamily family =
2863 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2864 switch (family) {
2865 case OMF_init:
2866 if (Method)
2867 checkInitMethod(Method, ReceiverType);
2868
2869 case OMF_None:
2870 case OMF_alloc:
2871 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00002872 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002873 case OMF_mutableCopy:
2874 case OMF_new:
2875 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002876 case OMF_initialize:
John McCall31168b02011-06-15 23:02:42 +00002877 break;
2878
2879 case OMF_dealloc:
2880 case OMF_retain:
2881 case OMF_release:
2882 case OMF_autorelease:
2883 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002884 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2885 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00002886 break;
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002887
2888 case OMF_performSelector:
2889 if (Method && NumArgs >= 1) {
2890 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2891 Selector ArgSel = SelExp->getSelector();
2892 ObjCMethodDecl *SelMethod =
2893 LookupInstanceMethodInGlobalPool(ArgSel,
2894 SelExp->getSourceRange());
2895 if (!SelMethod)
2896 SelMethod =
2897 LookupFactoryMethodInGlobalPool(ArgSel,
2898 SelExp->getSourceRange());
2899 if (SelMethod) {
2900 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2901 switch (SelFamily) {
2902 case OMF_alloc:
2903 case OMF_copy:
2904 case OMF_mutableCopy:
2905 case OMF_new:
2906 case OMF_self:
2907 case OMF_init:
2908 // Issue error, unless ns_returns_not_retained.
2909 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2910 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002911 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002912 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002913 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2914 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002915 }
2916 break;
2917 default:
2918 // +0 call. OK. unless ns_returns_retained.
2919 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2920 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002921 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002922 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002923 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2924 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002925 }
2926 break;
2927 }
2928 }
2929 } else {
2930 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002931 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002932 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2933 }
2934 }
2935 break;
John McCall31168b02011-06-15 23:02:42 +00002936 }
2937 }
2938
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002939 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2940
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002941 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00002942 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002943 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002944 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002945 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002946 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002947 makeArrayRef(Args, NumArgs), RBracLoc,
2948 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002949 else {
John McCall7decc9e2010-11-18 06:31:45 +00002950 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002951 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002952 makeArrayRef(Args, NumArgs), RBracLoc,
2953 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002954 if (!isImplicit)
2955 checkCocoaAPI(*this, Result);
2956 }
John McCall31168b02011-06-15 23:02:42 +00002957
David Blaikiebbafb8a2012-03-11 07:00:24 +00002958 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002959 // In ARC, annotate delegate init calls.
2960 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00002961 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00002962 // Only consider init calls *directly* in init implementations,
2963 // not within blocks.
2964 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2965 if (method && method->getMethodFamily() == OMF_init) {
2966 // The implicit assignment to self means we also don't want to
2967 // consume the result.
2968 Result->setDelegateInitCall(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002969 return Result;
John McCall31168b02011-06-15 23:02:42 +00002970 }
2971 }
2972
2973 // In ARC, check for message sends which are likely to introduce
2974 // retain cycles.
2975 checkRetainCycles(Result);
Jordan Rose22487652012-10-11 16:06:21 +00002976
2977 if (!isImplicit && Method) {
2978 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2979 bool IsWeak =
2980 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2981 if (!IsWeak && Sel.isUnarySelector())
2982 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002983 if (IsWeak &&
2984 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
2985 getCurFunction()->recordUseOfWeak(Result, Prop);
Jordan Rose22487652012-10-11 16:06:21 +00002986 }
2987 }
John McCall31168b02011-06-15 23:02:42 +00002988 }
Alex Denisove1d882c2015-03-04 17:55:52 +00002989
2990 CheckObjCCircularContainer(Result);
2991
Douglas Gregoraae38d62010-05-22 05:17:18 +00002992 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002993}
2994
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002995static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2996 if (ObjCSelectorExpr *OSE =
2997 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2998 Selector Sel = OSE->getSelector();
2999 SourceLocation Loc = OSE->getAtLoc();
Chandler Carruth12c8f652015-03-27 00:55:05 +00003000 auto Pos = S.ReferencedSelectors.find(Sel);
Fariborz Jahanian02447d82013-01-22 18:35:43 +00003001 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
3002 S.ReferencedSelectors.erase(Pos);
3003 }
3004}
3005
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003006// ActOnInstanceMessage - used for both unary and keyword messages.
3007// ArgExprs is optional - if it is present, the number of expressions
3008// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00003009ExprResult Sema::ActOnInstanceMessage(Scope *S,
3010 Expr *Receiver,
3011 Selector Sel,
3012 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00003013 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00003014 SourceLocation RBracLoc,
3015 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00003016 if (!Receiver)
3017 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00003018
3019 // A ParenListExpr can show up while doing error recovery with invalid code.
3020 if (isa<ParenListExpr>(Receiver)) {
3021 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
3022 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003023 Receiver = Result.get();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00003024 }
Fariborz Jahanian17748062013-01-22 19:05:17 +00003025
3026 if (RespondsToSelectorSel.isNull()) {
3027 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
3028 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
3029 }
3030 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00003031 RemoveSelectorFromWarningCache(*this, Args[0]);
Craig Topperc3ec1492014-05-26 06:22:03 +00003032
John McCallb268a282010-08-23 23:25:46 +00003033 return BuildInstanceMessage(Receiver, Receiver->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00003034 /*SuperLoc=*/SourceLocation(), Sel,
3035 /*Method=*/nullptr, LBracLoc, SelectorLocs,
3036 RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00003037}
Chris Lattner2a3569b2008-04-07 05:30:13 +00003038
John McCall31168b02011-06-15 23:02:42 +00003039enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00003040 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00003041 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00003042
3043 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00003044 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00003045
3046 /// id*, id***, void (^*)(),
3047 ACTC_indirectRetainable,
3048
3049 /// void* might be a normal C type, or it might a CF type.
3050 ACTC_voidPtr,
3051
3052 /// struct A*
3053 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00003054};
John McCalle4fe2452011-10-01 01:01:08 +00003055static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
3056 return (ACTC == ACTC_retainable ||
3057 ACTC == ACTC_coreFoundation ||
3058 ACTC == ACTC_voidPtr);
3059}
3060static bool isAnyCLike(ARCConversionTypeClass ACTC) {
3061 return ACTC == ACTC_none ||
3062 ACTC == ACTC_voidPtr ||
3063 ACTC == ACTC_coreFoundation;
3064}
3065
John McCall31168b02011-06-15 23:02:42 +00003066static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00003067 bool isIndirect = false;
John McCall31168b02011-06-15 23:02:42 +00003068
3069 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00003070 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00003071 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00003072 isIndirect = true;
3073 }
John McCall31168b02011-06-15 23:02:42 +00003074
3075 // Drill through pointers and arrays recursively.
3076 while (true) {
3077 if (const PointerType *ptr = type->getAs<PointerType>()) {
3078 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00003079
3080 // The first level of pointer may be the innermost pointer on a CF type.
3081 if (!isIndirect) {
3082 if (type->isVoidType()) return ACTC_voidPtr;
3083 if (type->isRecordType()) return ACTC_coreFoundation;
3084 }
John McCall31168b02011-06-15 23:02:42 +00003085 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
3086 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
3087 } else {
3088 break;
3089 }
John McCalle4fe2452011-10-01 01:01:08 +00003090 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00003091 }
3092
John McCalle4fe2452011-10-01 01:01:08 +00003093 if (isIndirect) {
3094 if (type->isObjCARCBridgableType())
3095 return ACTC_indirectRetainable;
3096 return ACTC_none;
3097 }
3098
3099 if (type->isObjCARCBridgableType())
3100 return ACTC_retainable;
3101
3102 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00003103}
3104
3105namespace {
John McCalle4fe2452011-10-01 01:01:08 +00003106 /// A result from the cast checker.
3107 enum ACCResult {
3108 /// Cannot be casted.
3109 ACC_invalid,
3110
3111 /// Can be safely retained or not retained.
3112 ACC_bottom,
3113
3114 /// Can be casted at +0.
3115 ACC_plusZero,
3116
3117 /// Can be casted at +1.
3118 ACC_plusOne
3119 };
3120 ACCResult merge(ACCResult left, ACCResult right) {
3121 if (left == right) return left;
3122 if (left == ACC_bottom) return right;
3123 if (right == ACC_bottom) return left;
3124 return ACC_invalid;
3125 }
3126
3127 /// A checker which white-lists certain expressions whose conversion
3128 /// to or from retainable type would otherwise be forbidden in ARC.
3129 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
3130 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
3131
John McCall31168b02011-06-15 23:02:42 +00003132 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00003133 ARCConversionTypeClass SourceClass;
3134 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003135 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00003136
3137 static bool isCFType(QualType type) {
3138 // Someday this can use ns_bridged. For now, it has to do this.
3139 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00003140 }
John McCalle4fe2452011-10-01 01:01:08 +00003141
3142 public:
3143 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003144 ARCConversionTypeClass target, bool diagnose)
3145 : Context(Context), SourceClass(source), TargetClass(target),
3146 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00003147
3148 using super::Visit;
3149 ACCResult Visit(Expr *e) {
3150 return super::Visit(e->IgnoreParens());
3151 }
3152
3153 ACCResult VisitStmt(Stmt *s) {
3154 return ACC_invalid;
3155 }
3156
3157 /// Null pointer constants can be casted however you please.
3158 ACCResult VisitExpr(Expr *e) {
3159 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
3160 return ACC_bottom;
3161 return ACC_invalid;
3162 }
3163
3164 /// Objective-C string literals can be safely casted.
3165 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3166 // If we're casting to any retainable type, go ahead. Global
3167 // strings are immune to retains, so this is bottom.
3168 if (isAnyRetainable(TargetClass)) return ACC_bottom;
3169
3170 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00003171 }
3172
John McCalle4fe2452011-10-01 01:01:08 +00003173 /// Look through certain implicit and explicit casts.
3174 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003175 switch (e->getCastKind()) {
3176 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00003177 return ACC_bottom;
3178
John McCall31168b02011-06-15 23:02:42 +00003179 case CK_NoOp:
3180 case CK_LValueToRValue:
3181 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00003182 case CK_CPointerToObjCPointerCast:
3183 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00003184 case CK_AnyPointerToBlockPointerCast:
3185 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00003186
John McCall31168b02011-06-15 23:02:42 +00003187 default:
John McCalle4fe2452011-10-01 01:01:08 +00003188 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00003189 }
3190 }
John McCalle4fe2452011-10-01 01:01:08 +00003191
3192 /// Look through unary extension.
3193 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003194 return Visit(e->getSubExpr());
3195 }
John McCalle4fe2452011-10-01 01:01:08 +00003196
3197 /// Ignore the LHS of a comma operator.
3198 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003199 return Visit(e->getRHS());
3200 }
John McCalle4fe2452011-10-01 01:01:08 +00003201
3202 /// Conditional operators are okay if both sides are okay.
3203 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3204 ACCResult left = Visit(e->getTrueExpr());
3205 if (left == ACC_invalid) return ACC_invalid;
3206 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00003207 }
John McCalle4fe2452011-10-01 01:01:08 +00003208
John McCallfe96e0b2011-11-06 09:01:30 +00003209 /// Look through pseudo-objects.
3210 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3211 // If we're getting here, we should always have a result.
3212 return Visit(e->getResultExpr());
3213 }
3214
John McCalle4fe2452011-10-01 01:01:08 +00003215 /// Statement expressions are okay if their result expression is okay.
3216 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003217 return Visit(e->getSubStmt()->body_back());
3218 }
John McCall31168b02011-06-15 23:02:42 +00003219
John McCalle4fe2452011-10-01 01:01:08 +00003220 /// Some declaration references are okay.
3221 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
John McCalle4fe2452011-10-01 01:01:08 +00003222 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
Ben Langmuir443aa4b2015-02-25 20:09:06 +00003223 // References to global constants are okay.
John McCalle4fe2452011-10-01 01:01:08 +00003224 if (isAnyRetainable(TargetClass) &&
3225 isAnyRetainable(SourceClass) &&
3226 var &&
3227 var->getStorageClass() == SC_Extern &&
Ben Langmuir443aa4b2015-02-25 20:09:06 +00003228 var->getType().isConstQualified()) {
3229
3230 // In system headers, they can also be assumed to be immune to retains.
3231 // These are things like 'kCFStringTransformToLatin'.
3232 if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
3233 return ACC_bottom;
3234
3235 return ACC_plusZero;
John McCalle4fe2452011-10-01 01:01:08 +00003236 }
3237
3238 // Nothing else.
3239 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00003240 }
John McCalle4fe2452011-10-01 01:01:08 +00003241
3242 /// Some calls are okay.
3243 ACCResult VisitCallExpr(CallExpr *e) {
3244 if (FunctionDecl *fn = e->getDirectCallee())
3245 if (ACCResult result = checkCallToFunction(fn))
3246 return result;
3247
3248 return super::VisitCallExpr(e);
3249 }
3250
3251 ACCResult checkCallToFunction(FunctionDecl *fn) {
3252 // Require a CF*Ref return type.
Alp Toker314cc812014-01-25 16:55:45 +00003253 if (!isCFType(fn->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003254 return ACC_invalid;
3255
3256 if (!isAnyRetainable(TargetClass))
3257 return ACC_invalid;
3258
3259 // Honor an explicit 'not retained' attribute.
3260 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3261 return ACC_plusZero;
3262
3263 // Honor an explicit 'retained' attribute, except that for
3264 // now we're not going to permit implicit handling of +1 results,
3265 // because it's a bit frightening.
3266 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003267 return Diagnose ? ACC_plusOne
3268 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003269
3270 // Recognize this specific builtin function, which is used by CFSTR.
3271 unsigned builtinID = fn->getBuiltinID();
3272 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3273 return ACC_bottom;
3274
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003275 // Otherwise, don't do anything implicit with an unaudited function.
3276 if (!fn->hasAttr<CFAuditedTransferAttr>())
3277 return ACC_invalid;
3278
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003279 // Otherwise, it's +0 unless it follows the create convention.
3280 if (ento::coreFoundation::followsCreateRule(fn))
3281 return Diagnose ? ACC_plusOne
3282 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003283
John McCalle4fe2452011-10-01 01:01:08 +00003284 return ACC_plusZero;
3285 }
3286
3287 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3288 return checkCallToMethod(e->getMethodDecl());
3289 }
3290
3291 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3292 ObjCMethodDecl *method;
3293 if (e->isExplicitProperty())
3294 method = e->getExplicitProperty()->getGetterMethodDecl();
3295 else
3296 method = e->getImplicitPropertyGetter();
3297 return checkCallToMethod(method);
3298 }
3299
3300 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3301 if (!method) return ACC_invalid;
3302
3303 // Check for message sends to functions returning CF types. We
3304 // just obey the Cocoa conventions with these, even though the
3305 // return type is CF.
Alp Toker314cc812014-01-25 16:55:45 +00003306 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003307 return ACC_invalid;
3308
3309 // If the method is explicitly marked not-retained, it's +0.
3310 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3311 return ACC_plusZero;
3312
3313 // If the method is explicitly marked as returning retained, or its
3314 // selector follows a +1 Cocoa convention, treat it as +1.
3315 if (method->hasAttr<CFReturnsRetainedAttr>())
3316 return ACC_plusOne;
3317
3318 switch (method->getSelector().getMethodFamily()) {
3319 case OMF_alloc:
3320 case OMF_copy:
3321 case OMF_mutableCopy:
3322 case OMF_new:
3323 return ACC_plusOne;
3324
3325 default:
3326 // Otherwise, treat it as +0.
3327 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00003328 }
3329 }
John McCalle4fe2452011-10-01 01:01:08 +00003330 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003331}
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00003332
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003333bool Sema::isKnownName(StringRef name) {
3334 if (name.empty())
3335 return false;
3336 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003337 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003338 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003339}
3340
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003341static void addFixitForObjCARCConversion(Sema &S,
3342 DiagnosticBuilder &DiagB,
3343 Sema::CheckedConversionKind CCK,
3344 SourceLocation afterLParen,
3345 QualType castType,
3346 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003347 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003348 const char *bridgeKeyword,
3349 const char *CFBridgeName) {
3350 // We handle C-style and implicit casts here.
3351 switch (CCK) {
3352 case Sema::CCK_ImplicitConversion:
3353 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003354 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003355 break;
3356 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003357 return;
3358 }
3359
3360 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003361 if (CCK == Sema::CCK_OtherCast) {
3362 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3363 SourceRange range(NCE->getOperatorLoc(),
3364 NCE->getAngleBrackets().getEnd());
3365 SmallString<32> BridgeCall;
3366
3367 SourceManager &SM = S.getSourceManager();
3368 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3369 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3370 BridgeCall += ' ';
3371
3372 BridgeCall += CFBridgeName;
3373 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3374 }
3375 return;
3376 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003377 Expr *castedE = castExpr;
3378 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3379 castedE = CCE->getSubExpr();
3380 castedE = castedE->IgnoreImpCasts();
3381 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00003382
3383 SmallString<32> BridgeCall;
3384
3385 SourceManager &SM = S.getSourceManager();
3386 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3387 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3388 BridgeCall += ' ';
3389
3390 BridgeCall += CFBridgeName;
3391
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003392 if (isa<ParenExpr>(castedE)) {
3393 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003394 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003395 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00003396 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003397 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003398 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003399 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3400 S.PP.getLocForEndOfToken(range.getEnd()),
3401 ")"));
3402 }
3403 return;
3404 }
3405
3406 if (CCK == Sema::CCK_CStyleCast) {
3407 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003408 } else if (CCK == Sema::CCK_OtherCast) {
3409 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3410 std::string castCode = "(";
3411 castCode += bridgeKeyword;
3412 castCode += castType.getAsString();
3413 castCode += ")";
3414 SourceRange Range(NCE->getOperatorLoc(),
3415 NCE->getAngleBrackets().getEnd());
3416 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3417 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003418 } else {
3419 std::string castCode = "(";
3420 castCode += bridgeKeyword;
3421 castCode += castType.getAsString();
3422 castCode += ")";
3423 Expr *castedE = castExpr->IgnoreImpCasts();
3424 SourceRange range = castedE->getSourceRange();
3425 if (isa<ParenExpr>(castedE)) {
3426 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3427 castCode));
3428 } else {
3429 castCode += "(";
3430 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3431 castCode));
3432 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3433 S.PP.getLocForEndOfToken(range.getEnd()),
3434 ")"));
3435 }
3436 }
3437}
3438
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003439template <typename T>
3440static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3441 TypedefNameDecl *TDNDecl = TD->getDecl();
3442 QualType QT = TDNDecl->getUnderlyingType();
3443 if (QT->isPointerType()) {
3444 QT = QT->getPointeeType();
3445 if (const RecordType *RT = QT->getAs<RecordType>())
Fariborz Jahanian9af6a782014-06-11 19:10:46 +00003446 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
Aaron Ballman2084f8f2013-12-19 13:20:36 +00003447 return RD->getAttr<T>();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003448 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003449 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003450}
3451
3452static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3453 TypedefNameDecl *&TDNDecl) {
3454 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3455 TDNDecl = TD->getDecl();
3456 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3457 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3458 return ObjCBAttr;
3459 T = TDNDecl->getUnderlyingType();
3460 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003461 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003462}
3463
John McCall4124c492011-10-17 18:40:02 +00003464static void
3465diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3466 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003467 Expr *castExpr, Expr *realCast,
3468 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003469 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003470 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003471 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00003472
John McCall4124c492011-10-17 18:40:02 +00003473 if (S.makeUnavailableInSystemHeader(loc,
John McCallc6af8c62015-10-28 05:03:19 +00003474 UnavailableAttr::IR_ARCForbiddenConversion))
John McCall31168b02011-06-15 23:02:42 +00003475 return;
John McCall4124c492011-10-17 18:40:02 +00003476
3477 QualType castExprType = castExpr->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003478 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003479 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3480 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3481 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
Fariborz Jahanian1ad83a32014-06-18 23:22:38 +00003482 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003483 return;
John McCall31168b02011-06-15 23:02:42 +00003484
John McCall640767f2011-06-17 06:50:50 +00003485 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003486 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003487 case ACTC_none:
3488 case ACTC_coreFoundation:
3489 case ACTC_voidPtr:
3490 srcKind = (castExprType->isPointerType() ? 1 : 0);
3491 break;
3492 case ACTC_retainable:
3493 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3494 break;
3495 case ACTC_indirectRetainable:
3496 srcKind = 4;
3497 break;
John McCall31168b02011-06-15 23:02:42 +00003498 }
3499
John McCall4124c492011-10-17 18:40:02 +00003500 // Check whether this could be fixed with a bridge cast.
3501 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3502 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003503
John McCall4124c492011-10-17 18:40:02 +00003504 // Bridge from an ARC type to a CF type.
3505 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003506
John McCall4124c492011-10-17 18:40:02 +00003507 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3508 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3509 << 2 // of C pointer type
3510 << castExprType
3511 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3512 << castType
3513 << castRange
3514 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003515 bool br = S.isKnownName("CFBridgingRelease");
Jordan Rose4502b532012-07-31 01:07:43 +00003516 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003517 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003518 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003519 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003520 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003521 DiagnosticBuilder DiagB =
3522 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3523 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Craig Topperc3ec1492014-05-26 06:22:03 +00003524
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003525 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003526 castType, castExpr, realCast, "__bridge ",
3527 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003528 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003529 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003530 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003531 DiagnosticBuilder DiagB =
3532 (CCK == Sema::CCK_OtherCast && !br) ?
3533 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3534 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3535 diag::note_arc_bridge_transfer)
3536 << castExprType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003537
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003538 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003539 castType, castExpr, realCast, "__bridge_transfer ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003540 br ? "CFBridgingRelease" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003541 }
John McCall4124c492011-10-17 18:40:02 +00003542
3543 return;
3544 }
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003545
John McCall4124c492011-10-17 18:40:02 +00003546 // Bridge from a CF type to an ARC type.
3547 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003548 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003549 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3550 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3551 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3552 << castExprType
3553 << 2 // to C pointer type
3554 << castType
3555 << castRange
3556 << castExpr->getSourceRange();
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003557 ACCResult CreateRule =
3558 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003559 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003560 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003561 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003562 DiagnosticBuilder DiagB =
3563 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3564 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003565 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003566 castType, castExpr, realCast, "__bridge ",
3567 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003568 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003569 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003570 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003571 DiagnosticBuilder DiagB =
3572 (CCK == Sema::CCK_OtherCast && !br) ?
3573 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3574 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3575 diag::note_arc_bridge_retained)
3576 << castType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003577
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003578 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003579 castType, castExpr, realCast, "__bridge_retained ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003580 br ? "CFBridgingRetain" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003581 }
John McCall4124c492011-10-17 18:40:02 +00003582
3583 return;
John McCall31168b02011-06-15 23:02:42 +00003584 }
3585
John McCall4124c492011-10-17 18:40:02 +00003586 S.Diag(loc, diag::err_arc_mismatched_cast)
3587 << (CCK != Sema::CCK_ImplicitConversion)
3588 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003589 << castRange << castExpr->getSourceRange();
3590}
3591
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003592template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003593static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3594 bool &HadTheAttribute, bool warn) {
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003595 QualType T = castExpr->getType();
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003596 HadTheAttribute = false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003597 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3598 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003599 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003600 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003601 HadTheAttribute = true;
Fariborz Jahanianc9e266b2014-12-11 22:56:26 +00003602 if (Parm->isStr("id"))
3603 return true;
3604
Craig Topperc3ec1492014-05-26 06:22:03 +00003605 NamedDecl *Target = nullptr;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003606 // Check for an existing type with this name.
3607 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3608 Sema::LookupOrdinaryName);
3609 if (S.LookupName(R, S.TUScope)) {
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003610 Target = R.getFoundDecl();
3611 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3612 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3613 if (const ObjCObjectPointerType *InterfacePointerType =
3614 castType->getAsObjCInterfacePointerType()) {
3615 ObjCInterfaceDecl *CastClass
3616 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003617 if ((CastClass == ExprClass) ||
Fariborz Jahanian27aa9b42015-04-10 22:07:47 +00003618 (CastClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003619 return true;
3620 if (warn)
3621 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3622 << T << Target->getName() << castType->getPointeeType();
3623 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003624 } else if (castType->isObjCIdType() ||
3625 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3626 castType, ExprClass)))
3627 // ok to cast to 'id'.
3628 // casting to id<p-list> is ok if bridge type adopts all of
3629 // p-list protocols.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003630 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003631 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003632 if (warn) {
3633 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3634 << T << Target->getName() << castType;
3635 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3636 S.Diag(Target->getLocStart(), diag::note_declared_at);
3637 }
3638 return false;
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003639 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003640 }
Fariborz Jahanian696c8872015-04-09 23:39:53 +00003641 } else if (!castType->isObjCIdType()) {
3642 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
3643 << castExpr->getType() << Parm;
3644 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3645 if (Target)
3646 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003647 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003648 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003649 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003650 return false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003651 }
3652 T = TDNDecl->getUnderlyingType();
3653 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003654 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003655}
3656
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003657template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003658static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3659 bool &HadTheAttribute, bool warn) {
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003660 QualType T = castType;
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003661 HadTheAttribute = false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003662 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3663 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003664 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003665 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003666 HadTheAttribute = true;
John McCallaf6b3f82015-03-10 18:41:23 +00003667 if (Parm->isStr("id"))
3668 return true;
3669
Craig Topperc3ec1492014-05-26 06:22:03 +00003670 NamedDecl *Target = nullptr;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003671 // Check for an existing type with this name.
3672 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3673 Sema::LookupOrdinaryName);
3674 if (S.LookupName(R, S.TUScope)) {
3675 Target = R.getFoundDecl();
3676 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3677 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3678 if (const ObjCObjectPointerType *InterfacePointerType =
3679 castExpr->getType()->getAsObjCInterfacePointerType()) {
3680 ObjCInterfaceDecl *ExprClass
3681 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003682 if ((CastClass == ExprClass) ||
3683 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003684 return true;
3685 if (warn) {
3686 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3687 << castExpr->getType()->getPointeeType() << T;
3688 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3689 }
3690 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003691 } else if (castExpr->getType()->isObjCIdType() ||
3692 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3693 castExpr->getType(), CastClass)))
3694 // ok to cast an 'id' expression to a CFtype.
3695 // ok to cast an 'id<plist>' expression to CFtype provided plist
3696 // adopts all of CFtype's ObjetiveC's class plist.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003697 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003698 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003699 if (warn) {
3700 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3701 << castExpr->getType() << castType;
3702 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3703 S.Diag(Target->getLocStart(), diag::note_declared_at);
3704 }
3705 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003706 }
3707 }
3708 }
3709 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3710 << castExpr->getType() << castType;
3711 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3712 if (Target)
3713 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003714 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003715 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003716 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003717 }
3718 T = TDNDecl->getUnderlyingType();
3719 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003720 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003721}
3722
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003723void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003724 if (!getLangOpts().ObjC1)
3725 return;
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003726 // warn in presence of __bridge casting to or from a toll free bridge cast.
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003727 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3728 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003729 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003730 bool HasObjCBridgeAttr;
3731 bool ObjCBridgeAttrWillNotWarn =
3732 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3733 false);
3734 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3735 return;
3736 bool HasObjCBridgeMutableAttr;
3737 bool ObjCBridgeMutableAttrWillNotWarn =
3738 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3739 HasObjCBridgeMutableAttr, false);
3740 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3741 return;
3742
3743 if (HasObjCBridgeAttr)
3744 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3745 true);
3746 else if (HasObjCBridgeMutableAttr)
3747 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3748 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003749 }
3750 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003751 bool HasObjCBridgeAttr;
3752 bool ObjCBridgeAttrWillNotWarn =
3753 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3754 false);
3755 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3756 return;
3757 bool HasObjCBridgeMutableAttr;
3758 bool ObjCBridgeMutableAttrWillNotWarn =
3759 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3760 HasObjCBridgeMutableAttr, false);
3761 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3762 return;
3763
3764 if (HasObjCBridgeAttr)
3765 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3766 true);
3767 else if (HasObjCBridgeMutableAttr)
3768 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3769 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003770 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003771}
3772
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003773void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3774 QualType SrcType = castExpr->getType();
3775 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3776 if (PRE->isExplicitProperty()) {
3777 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3778 SrcType = PDecl->getType();
3779 }
3780 else if (PRE->isImplicitProperty()) {
3781 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3782 SrcType = Getter->getReturnType();
3783
3784 }
3785 }
3786
3787 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3788 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3789 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3790 return;
3791 CheckObjCBridgeRelatedConversions(castExpr->getLocStart(),
3792 castType, SrcType, castExpr);
3793 return;
3794}
3795
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00003796bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3797 CastKind &Kind) {
3798 if (!getLangOpts().ObjC1)
3799 return false;
3800 ARCConversionTypeClass exprACTC =
3801 classifyTypeForARCConversion(castExpr->getType());
3802 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3803 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3804 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3805 CheckTollFreeBridgeCast(castType, castExpr);
3806 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3807 : CK_CPointerToObjCPointerCast;
3808 return true;
3809 }
3810 return false;
3811}
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003812
3813bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3814 QualType DestType, QualType SrcType,
3815 ObjCInterfaceDecl *&RelatedClass,
3816 ObjCMethodDecl *&ClassMethod,
3817 ObjCMethodDecl *&InstanceMethod,
3818 TypedefNameDecl *&TDNDecl,
3819 bool CfToNs) {
3820 QualType T = CfToNs ? SrcType : DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003821 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3822 if (!ObjCBAttr)
3823 return false;
3824
3825 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3826 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3827 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3828 if (!RCId)
3829 return false;
Craig Topperc3ec1492014-05-26 06:22:03 +00003830 NamedDecl *Target = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003831 // Check for an existing type with this name.
3832 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3833 Sema::LookupOrdinaryName);
3834 if (!LookupName(R, TUScope)) {
3835 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003836 << SrcType << DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003837 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3838 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003839 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003840 Target = R.getFoundDecl();
3841 if (Target && isa<ObjCInterfaceDecl>(Target))
3842 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3843 else {
3844 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3845 << SrcType << DestType;
3846 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3847 if (Target)
3848 Diag(Target->getLocStart(), diag::note_declared_at);
3849 return false;
3850 }
3851
3852 // Check for an existing class method with the given selector name.
3853 if (CfToNs && CMId) {
3854 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3855 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3856 if (!ClassMethod) {
3857 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003858 << SrcType << DestType << Sel << false;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003859 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3860 return false;
3861 }
3862 }
3863
3864 // Check for an existing instance method with the given selector name.
3865 if (!CfToNs && IMId) {
3866 Selector Sel = Context.Selectors.getNullarySelector(IMId);
3867 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3868 if (!InstanceMethod) {
3869 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003870 << SrcType << DestType << Sel << true;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003871 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3872 return false;
3873 }
3874 }
3875 return true;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003876}
3877
3878bool
3879Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003880 QualType DestType, QualType SrcType,
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003881 Expr *&SrcExpr) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003882 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3883 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3884 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3885 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3886 if (!CfToNs && !NsToCf)
3887 return false;
3888
3889 ObjCInterfaceDecl *RelatedClass;
Craig Topperc3ec1492014-05-26 06:22:03 +00003890 ObjCMethodDecl *ClassMethod = nullptr;
3891 ObjCMethodDecl *InstanceMethod = nullptr;
3892 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003893 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
3894 ClassMethod, InstanceMethod, TDNDecl, CfToNs))
3895 return false;
3896
3897 if (CfToNs) {
3898 // Implicit conversion from CF to ObjC object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003899 if (ClassMethod) {
3900 std::string ExpressionString = "[";
3901 ExpressionString += RelatedClass->getNameAsString();
3902 ExpressionString += " ";
3903 ExpressionString += ClassMethod->getSelector().getAsString();
3904 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3905 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003906 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003907 << SrcType << DestType << ClassMethod->getSelector() << false
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003908 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3909 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003910 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3911 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3912
3913 QualType receiverType =
3914 Context.getObjCInterfaceType(RelatedClass);
3915 // Argument.
3916 Expr *args[] = { SrcExpr };
3917 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
3918 ClassMethod->getLocation(),
3919 ClassMethod->getSelector(), ClassMethod,
3920 MultiExprArg(args, 1));
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003921 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003922 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003923 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003924 }
3925 else {
3926 // Implicit conversion from ObjC type to CF object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003927 if (InstanceMethod) {
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003928 std::string ExpressionString;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003929 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003930 if (InstanceMethod->isPropertyAccessor())
3931 if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
3932 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
3933 ExpressionString = ".";
3934 ExpressionString += PDecl->getNameAsString();
3935 Diag(Loc, diag::err_objc_bridged_related_known_method)
3936 << SrcType << DestType << InstanceMethod->getSelector() << true
3937 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3938 }
3939 if (ExpressionString.empty()) {
3940 // Provide a fixit: [ObjectExpr InstanceMethod]
3941 ExpressionString = " ";
3942 ExpressionString += InstanceMethod->getSelector().getAsString();
3943 ExpressionString += "]";
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003944
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003945 Diag(Loc, diag::err_objc_bridged_related_known_method)
3946 << SrcType << DestType << InstanceMethod->getSelector() << true
3947 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3948 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3949 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003950 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3951 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3952
3953 ExprResult msg =
3954 BuildInstanceMessageImplicit(SrcExpr, SrcType,
3955 InstanceMethod->getLocation(),
3956 InstanceMethod->getSelector(),
3957 InstanceMethod, None);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003958 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003959 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003960 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003961 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003962 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003963}
3964
John McCall4124c492011-10-17 18:40:02 +00003965Sema::ARCConversionResult
3966Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003967 Expr *&castExpr, CheckedConversionKind CCK,
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00003968 bool DiagnoseCFAudited,
3969 BinaryOperatorKind Opc) {
John McCall4124c492011-10-17 18:40:02 +00003970 QualType castExprType = castExpr->getType();
3971
3972 // For the purposes of the classification, we assume reference types
3973 // will bind to temporaries.
3974 QualType effCastType = castType;
3975 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3976 effCastType = ref->getPointeeType();
3977
3978 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3979 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003980 if (exprACTC == castACTC) {
3981 // check for viablity and report error if casting an rvalue to a
3982 // life-time qualifier.
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003983 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003984 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003985 (castType != castExprType)) {
3986 const Type *DT = castType.getTypePtr();
3987 QualType QDT = castType;
3988 // We desugar some types but not others. We ignore those
3989 // that cannot happen in a cast; i.e. auto, and those which
3990 // should not be de-sugared; i.e typedef.
3991 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3992 QDT = PT->desugar();
3993 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3994 QDT = TP->desugar();
3995 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3996 QDT = AT->desugar();
3997 if (QDT != castType &&
3998 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3999 SourceLocation loc =
4000 (castRange.isValid() ? castRange.getBegin()
4001 : castExpr->getExprLoc());
4002 Diag(loc, diag::err_arc_nolifetime_behavior);
4003 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00004004 }
4005 return ACR_okay;
4006 }
4007
John McCall4124c492011-10-17 18:40:02 +00004008 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
4009
4010 // Allow all of these types to be cast to integer types (but not
4011 // vice-versa).
4012 if (castACTC == ACTC_none && castType->isIntegralType(Context))
4013 return ACR_okay;
4014
4015 // Allow casts between pointers to lifetime types (e.g., __strong id*)
4016 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
4017 // must be explicit.
4018 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
4019 return ACR_okay;
4020 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
4021 CCK != CCK_ImplicitConversion)
4022 return ACR_okay;
4023
Fariborz Jahanian36986c62012-07-27 22:37:07 +00004024 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00004025 // For invalid casts, fall through.
4026 case ACC_invalid:
4027 break;
4028
4029 // Do nothing for both bottom and +0.
4030 case ACC_bottom:
4031 case ACC_plusZero:
4032 return ACR_okay;
4033
4034 // If the result is +1, consume it here.
4035 case ACC_plusOne:
4036 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
4037 CK_ARCConsumeObject, castExpr,
Craig Topperc3ec1492014-05-26 06:22:03 +00004038 nullptr, VK_RValue);
John McCall4124c492011-10-17 18:40:02 +00004039 ExprNeedsCleanups = true;
4040 return ACR_okay;
4041 }
4042
4043 // If this is a non-implicit cast from id or block type to a
4044 // CoreFoundation type, delay complaining in case the cast is used
4045 // in an acceptable context.
4046 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
4047 CCK != CCK_ImplicitConversion)
4048 return ACR_unbridged;
4049
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00004050 // Do not issue bridge cast" diagnostic when implicit casting a cstring
4051 // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
4052 // suitable fix-it.
Fariborz Jahanian283bf892013-12-18 21:04:43 +00004053 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
4054 ConversionToObjCStringLiteralCheck(castType, castExpr))
4055 return ACR_okay;
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00004056
Fariborz Jahanian25eef192013-07-31 21:40:51 +00004057 // Do not issue "bridge cast" diagnostic when implicit casting
4058 // a retainable object to a CF type parameter belonging to an audited
4059 // CF API function. Let caller issue a normal type mismatched diagnostic
4060 // instead.
4061 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
4062 castACTC != ACTC_coreFoundation)
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00004063 if (!(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
4064 (Opc == BO_NE || Opc == BO_EQ)))
4065 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
4066 castExpr, castExpr, exprACTC, CCK);
John McCall4124c492011-10-17 18:40:02 +00004067 return ACR_okay;
4068}
4069
4070/// Given that we saw an expression with the ARCUnbridgedCastTy
4071/// placeholder type, complain bitterly.
4072void Sema::diagnoseARCUnbridgedCast(Expr *e) {
4073 // We expect the spurious ImplicitCastExpr to already have been stripped.
4074 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4075 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
4076
4077 SourceRange castRange;
4078 QualType castType;
4079 CheckedConversionKind CCK;
4080
4081 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
4082 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
4083 castType = cast->getTypeAsWritten();
4084 CCK = CCK_CStyleCast;
4085 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
4086 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
4087 castType = cast->getTypeAsWritten();
4088 CCK = CCK_OtherCast;
4089 } else {
4090 castType = cast->getType();
4091 CCK = CCK_ImplicitConversion;
4092 }
4093
4094 ARCConversionTypeClass castACTC =
4095 classifyTypeForARCConversion(castType.getNonReferenceType());
4096
4097 Expr *castExpr = realCast->getSubExpr();
4098 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
4099
4100 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00004101 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00004102}
4103
4104/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
4105/// type, remove the placeholder cast.
4106Expr *Sema::stripARCUnbridgedCast(Expr *e) {
4107 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4108
4109 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
4110 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
4111 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
4112 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
4113 assert(uo->getOpcode() == UO_Extension);
4114 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
4115 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
4116 sub->getValueKind(), sub->getObjectKind(),
4117 uo->getOperatorLoc());
4118 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
4119 assert(!gse->isResultDependent());
4120
4121 unsigned n = gse->getNumAssocs();
4122 SmallVector<Expr*, 4> subExprs(n);
4123 SmallVector<TypeSourceInfo*, 4> subTypes(n);
4124 for (unsigned i = 0; i != n; ++i) {
4125 subTypes[i] = gse->getAssocTypeSourceInfo(i);
4126 Expr *sub = gse->getAssocExpr(i);
4127 if (i == gse->getResultIndex())
4128 sub = stripARCUnbridgedCast(sub);
4129 subExprs[i] = sub;
4130 }
4131
4132 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
4133 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00004134 subTypes, subExprs,
4135 gse->getDefaultLoc(),
John McCall4124c492011-10-17 18:40:02 +00004136 gse->getRParenLoc(),
4137 gse->containsUnexpandedParameterPack(),
4138 gse->getResultIndex());
4139 } else {
4140 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
4141 return cast<ImplicitCastExpr>(e)->getSubExpr();
4142 }
4143}
4144
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004145bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
4146 QualType exprType) {
4147 QualType canCastType =
4148 Context.getCanonicalType(castType).getUnqualifiedType();
4149 QualType canExprType =
4150 Context.getCanonicalType(exprType).getUnqualifiedType();
4151 if (isa<ObjCObjectPointerType>(canCastType) &&
4152 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
4153 canExprType->isObjCObjectPointerType()) {
4154 if (const ObjCObjectPointerType *ObjT =
4155 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00004156 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4157 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004158 }
4159 return true;
4160}
4161
John McCall4db5c3c2011-07-07 06:58:02 +00004162/// Look for an ObjCReclaimReturnedObject cast and destroy it.
4163static Expr *maybeUndoReclaimObject(Expr *e) {
4164 // For now, we just undo operands that are *immediately* reclaim
4165 // expressions, which prevents the vast majority of potential
4166 // problems here. To catch them all, we'd need to rebuild arbitrary
4167 // value-propagating subexpressions --- we can't reliably rebuild
4168 // in-place because of expression sharing.
4169 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall2d637d22011-09-10 06:18:15 +00004170 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall4db5c3c2011-07-07 06:58:02 +00004171 return ice->getSubExpr();
4172
4173 return e;
4174}
4175
John McCall31168b02011-06-15 23:02:42 +00004176ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
4177 ObjCBridgeCastKind Kind,
4178 SourceLocation BridgeKeywordLoc,
4179 TypeSourceInfo *TSInfo,
4180 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00004181 ExprResult SubResult = UsualUnaryConversions(SubExpr);
4182 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004183 SubExpr = SubResult.get();
John McCalleb075542011-08-26 00:48:42 +00004184
John McCall31168b02011-06-15 23:02:42 +00004185 QualType T = TSInfo->getType();
4186 QualType FromType = SubExpr->getType();
4187
John McCall9320b872011-09-09 05:25:32 +00004188 CastKind CK;
4189
John McCall31168b02011-06-15 23:02:42 +00004190 bool MustConsume = false;
4191 if (T->isDependentType() || SubExpr->isTypeDependent()) {
4192 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00004193 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00004194 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
4195 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00004196 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4197 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00004198 switch (Kind) {
4199 case OBC_Bridge:
4200 break;
4201
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004202 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004203 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00004204 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4205 << 2
4206 << FromType
4207 << (T->isBlockPointerType()? 1 : 0)
4208 << T
4209 << SubExpr->getSourceRange()
4210 << Kind;
4211 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4212 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4213 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004214 << FromType << br
John McCall31168b02011-06-15 23:02:42 +00004215 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004216 br ? "CFBridgingRelease "
4217 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00004218
4219 Kind = OBC_Bridge;
4220 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004221 }
John McCall31168b02011-06-15 23:02:42 +00004222
4223 case OBC_BridgeTransfer:
4224 // We must consume the Objective-C object produced by the cast.
4225 MustConsume = true;
4226 break;
4227 }
4228 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4229 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00004230 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00004231 switch (Kind) {
Fariborz Jahanian214567c2014-10-28 17:26:21 +00004232 case OBC_Bridge:
4233 // Reclaiming a value that's going to be __bridge-casted to CF
4234 // is very dangerous, so we don't do it.
4235 SubExpr = maybeUndoReclaimObject(SubExpr);
4236 break;
John McCall31168b02011-06-15 23:02:42 +00004237
4238 case OBC_BridgeRetained:
4239 // Produce the object before casting it.
4240 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00004241 CK_ARCProduceObject,
Craig Topperc3ec1492014-05-26 06:22:03 +00004242 SubExpr, nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004243 break;
4244
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004245 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004246 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00004247 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4248 << (FromType->isBlockPointerType()? 1 : 0)
4249 << FromType
4250 << 2
4251 << T
4252 << SubExpr->getSourceRange()
4253 << Kind;
4254
4255 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4256 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4257 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004258 << T << br
4259 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4260 br ? "CFBridgingRetain " : "__bridge_retained");
John McCall31168b02011-06-15 23:02:42 +00004261
4262 Kind = OBC_Bridge;
4263 break;
4264 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004265 }
John McCall31168b02011-06-15 23:02:42 +00004266 } else {
4267 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4268 << FromType << T << Kind
4269 << SubExpr->getSourceRange()
4270 << TSInfo->getTypeLoc().getSourceRange();
4271 return ExprError();
4272 }
4273
John McCall9320b872011-09-09 05:25:32 +00004274 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00004275 BridgeKeywordLoc,
4276 TSInfo, SubExpr);
4277
4278 if (MustConsume) {
4279 ExprNeedsCleanups = true;
John McCall2d637d22011-09-10 06:18:15 +00004280 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
Craig Topperc3ec1492014-05-26 06:22:03 +00004281 nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004282 }
4283
4284 return Result;
4285}
4286
4287ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4288 SourceLocation LParenLoc,
4289 ObjCBridgeCastKind Kind,
4290 SourceLocation BridgeKeywordLoc,
4291 ParsedType Type,
4292 SourceLocation RParenLoc,
4293 Expr *SubExpr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004294 TypeSourceInfo *TSInfo = nullptr;
John McCall31168b02011-06-15 23:02:42 +00004295 QualType T = GetTypeFromParser(Type, &TSInfo);
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00004296 if (Kind == OBC_Bridge)
4297 CheckTollFreeBridgeCast(T, SubExpr);
John McCall31168b02011-06-15 23:02:42 +00004298 if (!TSInfo)
4299 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4300 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
4301 SubExpr);
4302}