blob: 786637c205e61831609141ff535e29c9cd5907ab [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,
Craig Topperc3ec1492014-05-26 06:22:03 +0000136 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
Ted Kremeneke65b0862012-03-06 20:05:56 +0000171/// \brief Retrieve the NSNumber factory method that should be used to create
172/// an Objective-C literal for the given type.
173static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
Patrick Beard0caa3942012-04-19 00:25:12 +0000174 QualType NumberType,
175 bool isLiteral = false,
176 SourceRange R = SourceRange()) {
David Blaikie05785d12013-02-20 22:23:23 +0000177 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
178 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
179
Ted Kremeneke65b0862012-03-06 20:05:56 +0000180 if (!Kind) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000181 if (isLiteral) {
182 S.Diag(Loc, diag::err_invalid_nsnumber_type)
183 << NumberType << R;
184 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000185 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000186 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000187
Ted Kremeneke65b0862012-03-06 20:05:56 +0000188 // If we already looked up this method, we're done.
189 if (S.NSNumberLiteralMethods[*Kind])
190 return S.NSNumberLiteralMethods[*Kind];
191
192 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
193 /*Instance=*/false);
194
Patrick Beard0caa3942012-04-19 00:25:12 +0000195 ASTContext &CX = S.Context;
196
197 // Look up the NSNumber class, if we haven't done so already. It's cached
198 // in the Sema instance.
199 if (!S.NSNumberDecl) {
Jordy Roseaca01f92012-05-12 17:32:52 +0000200 IdentifierInfo *NSNumberId =
201 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber);
Patrick Beard0caa3942012-04-19 00:25:12 +0000202 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId,
203 Loc, Sema::LookupOrdinaryName);
204 S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
205 if (!S.NSNumberDecl) {
206 if (S.getLangOpts().DebuggerObjCLiteral) {
207 // Create a stub definition of NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000208 S.NSNumberDecl = ObjCInterfaceDecl::Create(CX,
209 CX.getTranslationUnitDecl(),
210 SourceLocation(), NSNumberId,
Craig Topperc3ec1492014-05-26 06:22:03 +0000211 nullptr, SourceLocation());
Patrick Beard0caa3942012-04-19 00:25:12 +0000212 } else {
213 // Otherwise, require a declaration of NSNumber.
214 S.Diag(Loc, diag::err_undeclared_nsnumber);
Craig Topperc3ec1492014-05-26 06:22:03 +0000215 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000216 }
217 } else if (!S.NSNumberDecl->hasDefinition()) {
218 S.Diag(Loc, diag::err_undeclared_nsnumber);
Craig Topperc3ec1492014-05-26 06:22:03 +0000219 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000220 }
221
222 // generate the pointer to NSNumber type.
Jordy Roseaca01f92012-05-12 17:32:52 +0000223 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
224 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000225 }
226
Ted Kremeneke65b0862012-03-06 20:05:56 +0000227 // Look for the appropriate method within NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000228 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000229 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000230 // create a stub definition this NSNumber factory method.
Craig Topperc3ec1492014-05-26 06:22:03 +0000231 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000232 Method =
233 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
234 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
235 /*isInstance=*/false, /*isVariadic=*/false,
236 /*isPropertyAccessor=*/false,
237 /*isImplicitlyDeclared=*/true,
238 /*isDefined=*/false, ObjCMethodDecl::Required,
239 /*HasRelatedResultType=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000240 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
241 SourceLocation(), SourceLocation(),
Patrick Beard0caa3942012-04-19 00:25:12 +0000242 &CX.Idents.get("value"),
Craig Topperc3ec1492014-05-26 06:22:03 +0000243 NumberType, /*TInfo=*/nullptr,
244 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000245 Method->setMethodParams(S.Context, value, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000246 }
247
Jordy Rose08e500c2012-05-12 17:32:44 +0000248 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
Craig Topperc3ec1492014-05-26 06:22:03 +0000249 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000250
251 // Note: if the parameter type is out-of-line, we'll catch it later in the
252 // implicit conversion.
253
254 S.NSNumberLiteralMethods[*Kind] = Method;
255 return Method;
256}
257
Patrick Beard0caa3942012-04-19 00:25:12 +0000258/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
259/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremeneke65b0862012-03-06 20:05:56 +0000260ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000261 // Determine the type of the literal.
262 QualType NumberType = Number->getType();
263 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
264 // In C, character literals have type 'int'. That's not the type we want
265 // to use to determine the Objective-c literal kind.
266 switch (Char->getKind()) {
267 case CharacterLiteral::Ascii:
268 NumberType = Context.CharTy;
269 break;
270
271 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000272 NumberType = Context.getWideCharType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000273 break;
274
275 case CharacterLiteral::UTF16:
276 NumberType = Context.Char16Ty;
277 break;
278
279 case CharacterLiteral::UTF32:
280 NumberType = Context.Char32Ty;
281 break;
282 }
283 }
284
Ted Kremeneke65b0862012-03-06 20:05:56 +0000285 // Look for the appropriate method within NSNumber.
286 // Construct the literal.
Patrick Beard2565c592012-05-01 21:47:19 +0000287 SourceRange NR(Number->getSourceRange());
Patrick Beard0caa3942012-04-19 00:25:12 +0000288 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
Patrick Beard2565c592012-05-01 21:47:19 +0000289 true, NR);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000290 if (!Method)
291 return ExprError();
292
293 // Convert the number to the type that the parameter expects.
Alp Toker03376dc2014-07-07 09:02:20 +0000294 ParmVarDecl *ParamDecl = Method->parameters()[0];
Patrick Beard2565c592012-05-01 21:47:19 +0000295 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
296 ParamDecl);
297 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
298 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000299 Number);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000300 if (ConvertedNumber.isInvalid())
301 return ExprError();
302 Number = ConvertedNumber.get();
303
Patrick Beard2565c592012-05-01 21:47:19 +0000304 // Use the effective source range of the literal, including the leading '@'.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000305 return MaybeBindToTemporary(
Patrick Beard2565c592012-05-01 21:47:19 +0000306 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
307 SourceRange(AtLoc, NR.getEnd())));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000308}
309
310ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
311 SourceLocation ValueLoc,
312 bool Value) {
313 ExprResult Inner;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000314 if (getLangOpts().CPlusPlus) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000315 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
316 } else {
317 // C doesn't actually have a way to represent literal values of type
318 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
319 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
320 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
321 CK_IntegralToBoolean);
322 }
323
324 return BuildObjCNumericLiteral(AtLoc, Inner.get());
325}
326
327/// \brief Check that the given expression is a valid element of an Objective-C
328/// collection literal.
329static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000330 QualType T,
331 bool ArrayLiteral = false) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000332 // If the expression is type-dependent, there's nothing for us to do.
333 if (Element->isTypeDependent())
334 return Element;
335
336 ExprResult Result = S.CheckPlaceholderExpr(Element);
337 if (Result.isInvalid())
338 return ExprError();
339 Element = Result.get();
340
341 // In C++, check for an implicit conversion to an Objective-C object pointer
342 // type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000343 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000344 InitializedEntity Entity
Jordy Roseaca01f92012-05-12 17:32:52 +0000345 = InitializedEntity::InitializeParameter(S.Context, T,
346 /*Consumed=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000347 InitializationKind Kind
Jordy Roseaca01f92012-05-12 17:32:52 +0000348 = InitializationKind::CreateCopy(Element->getLocStart(),
349 SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000350 InitializationSequence Seq(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000351 if (!Seq.Failed())
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000352 return Seq.Perform(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000353 }
354
355 Expr *OrigElement = Element;
356
357 // Perform lvalue-to-rvalue conversion.
358 Result = S.DefaultLvalueConversion(Element);
359 if (Result.isInvalid())
360 return ExprError();
361 Element = Result.get();
362
363 // Make sure that we have an Objective-C pointer type or block.
364 if (!Element->getType()->isObjCObjectPointerType() &&
365 !Element->getType()->isBlockPointerType()) {
366 bool Recovered = false;
367
368 // If this is potentially an Objective-C numeric literal, add the '@'.
369 if (isa<IntegerLiteral>(OrigElement) ||
370 isa<CharacterLiteral>(OrigElement) ||
371 isa<FloatingLiteral>(OrigElement) ||
372 isa<ObjCBoolLiteralExpr>(OrigElement) ||
373 isa<CXXBoolLiteralExpr>(OrigElement)) {
374 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
375 int Which = isa<CharacterLiteral>(OrigElement) ? 1
376 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
377 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
378 : 3;
379
380 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
381 << Which << OrigElement->getSourceRange()
382 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
383
384 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
385 OrigElement);
386 if (Result.isInvalid())
387 return ExprError();
388
389 Element = Result.get();
390 Recovered = true;
391 }
392 }
393 // If this is potentially an Objective-C string literal, add the '@'.
394 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
395 if (String->isAscii()) {
396 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
397 << 0 << OrigElement->getSourceRange()
398 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
399
400 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
401 if (Result.isInvalid())
402 return ExprError();
403
404 Element = Result.get();
405 Recovered = true;
406 }
407 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000408
Ted Kremeneke65b0862012-03-06 20:05:56 +0000409 if (!Recovered) {
410 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
411 << Element->getType();
412 return ExprError();
413 }
414 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000415 if (ArrayLiteral)
Ted Kremenek197fee42013-10-09 22:34:33 +0000416 if (ObjCStringLiteral *getString =
417 dyn_cast<ObjCStringLiteral>(OrigElement)) {
418 if (StringLiteral *SL = getString->getString()) {
419 unsigned numConcat = SL->getNumConcatenated();
420 if (numConcat > 1) {
421 // Only warn if the concatenated string doesn't come from a macro.
422 bool hasMacro = false;
423 for (unsigned i = 0; i < numConcat ; ++i)
424 if (SL->getStrTokenLoc(i).isMacroID()) {
425 hasMacro = true;
426 break;
427 }
428 if (!hasMacro)
429 S.Diag(Element->getLocStart(),
430 diag::warn_concatenated_nsarray_literal)
431 << Element->getType();
432 }
433 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000434 }
435
Ted Kremeneke65b0862012-03-06 20:05:56 +0000436 // Make sure that the element has the type that the container factory
437 // function expects.
438 return S.PerformCopyInitialization(
439 InitializedEntity::InitializeParameter(S.Context, T,
440 /*Consumed=*/false),
441 Element->getLocStart(), Element);
442}
443
Patrick Beard0caa3942012-04-19 00:25:12 +0000444ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
445 if (ValueExpr->isTypeDependent()) {
446 ObjCBoxedExpr *BoxedExpr =
Craig Topperc3ec1492014-05-26 06:22:03 +0000447 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000448 return BoxedExpr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000449 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000450 ObjCMethodDecl *BoxingMethod = nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000451 QualType BoxedType;
452 // Convert the expression to an RValue, so we can check for pointer types...
453 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
454 if (RValue.isInvalid()) {
455 return ExprError();
456 }
457 ValueExpr = RValue.get();
Patrick Beard2565c592012-05-01 21:47:19 +0000458 QualType ValueType(ValueExpr->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +0000459 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
460 QualType PointeeType = PT->getPointeeType();
461 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
462
463 if (!NSStringDecl) {
464 IdentifierInfo *NSStringId =
465 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
466 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
467 SR.getBegin(), LookupOrdinaryName);
468 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
469 if (!NSStringDecl) {
470 if (getLangOpts().DebuggerObjCLiteral) {
471 // Support boxed expressions in the debugger w/o NSString declaration.
Jordy Roseaca01f92012-05-12 17:32:52 +0000472 DeclContext *TU = Context.getTranslationUnitDecl();
473 NSStringDecl = ObjCInterfaceDecl::Create(Context, TU,
474 SourceLocation(),
475 NSStringId,
Craig Topperc3ec1492014-05-26 06:22:03 +0000476 nullptr, SourceLocation());
Patrick Beard0caa3942012-04-19 00:25:12 +0000477 } else {
478 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
479 return ExprError();
480 }
481 } else if (!NSStringDecl->hasDefinition()) {
482 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
483 return ExprError();
484 }
485 assert(NSStringDecl && "NSStringDecl should not be NULL");
Jordy Roseaca01f92012-05-12 17:32:52 +0000486 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
487 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000488 }
489
490 if (!StringWithUTF8StringMethod) {
491 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
492 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
493
494 // Look for the appropriate method within NSString.
Jordy Rose08e500c2012-05-12 17:32:44 +0000495 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
496 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000497 // Debugger needs to work even if NSString hasn't been defined.
Craig Topperc3ec1492014-05-26 06:22:03 +0000498 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000499 ObjCMethodDecl *M = ObjCMethodDecl::Create(
500 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
501 NSStringPointer, ReturnTInfo, NSStringDecl,
502 /*isInstance=*/false, /*isVariadic=*/false,
503 /*isPropertyAccessor=*/false,
504 /*isImplicitlyDeclared=*/true,
505 /*isDefined=*/false, ObjCMethodDecl::Required,
506 /*HasRelatedResultType=*/false);
Jordy Roseaca01f92012-05-12 17:32:52 +0000507 QualType ConstCharType = Context.CharTy.withConst();
Patrick Beard0caa3942012-04-19 00:25:12 +0000508 ParmVarDecl *value =
509 ParmVarDecl::Create(Context, M,
510 SourceLocation(), SourceLocation(),
511 &Context.Idents.get("value"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000512 Context.getPointerType(ConstCharType),
Craig Topperc3ec1492014-05-26 06:22:03 +0000513 /*TInfo=*/nullptr,
514 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000515 M->setMethodParams(Context, value, None);
Jordy Rose08e500c2012-05-12 17:32:44 +0000516 BoxingMethod = M;
Patrick Beard0caa3942012-04-19 00:25:12 +0000517 }
Jordy Rose890f4572012-05-12 15:53:41 +0000518
Jordy Rose08e500c2012-05-12 17:32:44 +0000519 if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
520 stringWithUTF8String, BoxingMethod))
521 return ExprError();
522
523 StringWithUTF8StringMethod = BoxingMethod;
Patrick Beard0caa3942012-04-19 00:25:12 +0000524 }
525
526 BoxingMethod = StringWithUTF8StringMethod;
527 BoxedType = NSStringPointer;
528 }
Patrick Beard2565c592012-05-01 21:47:19 +0000529 } else if (ValueType->isBuiltinType()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000530 // The other types we support are numeric, char and BOOL/bool. We could also
531 // provide limited support for structure types, such as NSRange, NSRect, and
532 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
533 // for more details.
534
535 // Check for a top-level character literal.
536 if (const CharacterLiteral *Char =
537 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
538 // In C, character literals have type 'int'. That's not the type we want
539 // to use to determine the Objective-c literal kind.
540 switch (Char->getKind()) {
541 case CharacterLiteral::Ascii:
542 ValueType = Context.CharTy;
543 break;
544
545 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000546 ValueType = Context.getWideCharType();
Patrick Beard0caa3942012-04-19 00:25:12 +0000547 break;
548
549 case CharacterLiteral::UTF16:
550 ValueType = Context.Char16Ty;
551 break;
552
553 case CharacterLiteral::UTF32:
554 ValueType = Context.Char32Ty;
555 break;
556 }
557 }
Fariborz Jahanian5d64abb2014-06-18 20:49:02 +0000558 CheckForIntOverflow(ValueExpr);
Patrick Beard0caa3942012-04-19 00:25:12 +0000559 // FIXME: Do I need to do anything special with BoolTy expressions?
560
561 // Look for the appropriate method within NSNumber.
562 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
563 BoxedType = NSNumberPointer;
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000564
565 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
566 if (!ET->getDecl()->isComplete()) {
567 Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type)
568 << ValueType << ValueExpr->getSourceRange();
569 return ExprError();
570 }
571
572 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(),
573 ET->getDecl()->getIntegerType());
574 BoxedType = NSNumberPointer;
Patrick Beard0caa3942012-04-19 00:25:12 +0000575 }
576
577 if (!BoxingMethod) {
578 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
579 << ValueType << ValueExpr->getSourceRange();
580 return ExprError();
581 }
582
583 // Convert the expression to the type that the parameter requires.
Alp Toker03376dc2014-07-07 09:02:20 +0000584 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
Patrick Beard2565c592012-05-01 21:47:19 +0000585 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
586 ParamDecl);
587 ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
588 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000589 ValueExpr);
Patrick Beard0caa3942012-04-19 00:25:12 +0000590 if (ConvertedValueExpr.isInvalid())
591 return ExprError();
592 ValueExpr = ConvertedValueExpr.get();
593
594 ObjCBoxedExpr *BoxedExpr =
595 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
596 BoxingMethod, SR);
597 return MaybeBindToTemporary(BoxedExpr);
598}
599
John McCallf2538342012-07-31 05:14:30 +0000600/// Build an ObjC subscript pseudo-object expression, given that
601/// that's supported by the runtime.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000602ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
603 Expr *IndexExpr,
604 ObjCMethodDecl *getterMethod,
605 ObjCMethodDecl *setterMethod) {
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +0000606 assert(!LangOpts.isSubscriptPointerArithmetic());
John McCall5fb5df92012-06-20 06:18:46 +0000607
John McCallf2538342012-07-31 05:14:30 +0000608 // We can't get dependent types here; our callers should have
609 // filtered them out.
610 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
611 "base or index cannot have dependent type here");
612
613 // Filter out placeholders in the index. In theory, overloads could
614 // be preserved here, although that might not actually work correctly.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000615 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
616 if (Result.isInvalid())
617 return ExprError();
618 IndexExpr = Result.get();
619
John McCallf2538342012-07-31 05:14:30 +0000620 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000621 Result = DefaultLvalueConversion(BaseExpr);
622 if (Result.isInvalid())
623 return ExprError();
624 BaseExpr = Result.get();
John McCallf2538342012-07-31 05:14:30 +0000625
626 // Build the pseudo-object expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000627 return ObjCSubscriptRefExpr::Create(Context, BaseExpr, IndexExpr,
628 Context.PseudoObjectTy, getterMethod,
629 setterMethod, RB);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000630}
631
632ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000633 bool Arc = getLangOpts().ObjCAutoRefCount;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000634 // Look up the NSArray class, if we haven't done so already.
635 if (!NSArrayDecl) {
636 NamedDecl *IF = LookupSingleName(TUScope,
637 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
638 SR.getBegin(),
639 LookupOrdinaryName);
640 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000641 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000642 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
643 Context.getTranslationUnitDecl(),
644 SourceLocation(),
645 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
Craig Topperc3ec1492014-05-26 06:22:03 +0000646 nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000647
648 if (!NSArrayDecl) {
649 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
650 return ExprError();
651 }
652 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000653 QualType IdT = Context.getObjCIdType();
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000654 if (Arc && !ArrayAllocObjectsMethod) {
655 // Find +[NSArray alloc] method.
656 IdentifierInfo *II = &Context.Idents.get("alloc");
657 Selector AllocSel = Context.Selectors.getSelector(0, &II);
658 ArrayAllocObjectsMethod = NSArrayDecl->lookupClassMethod(AllocSel);
659 if (!ArrayAllocObjectsMethod && getLangOpts().DebuggerObjCLiteral) {
660 ArrayAllocObjectsMethod = ObjCMethodDecl::Create(Context,
661 SourceLocation(), SourceLocation(), AllocSel,
662 IdT,
663 nullptr /*TypeSourceInfo */,
664 Context.getTranslationUnitDecl(),
665 false /*Instance*/, false/*isVariadic*/,
666 /*isPropertyAccessor=*/false,
667 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
668 ObjCMethodDecl::Required,
669 false);
670 SmallVector<ParmVarDecl *, 1> Params;
671 ArrayAllocObjectsMethod->setMethodParams(Context, Params, None);
672 }
673 if (!ArrayAllocObjectsMethod) {
674 Diag(SR.getBegin(), diag::err_undeclared_alloc);
675 return ExprError();
676 }
677 }
678 // Find the arrayWithObjects:count: method, if we haven't done so already.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000679 if (!ArrayWithObjectsMethod) {
680 Selector
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000681 Sel = NSAPIObj->getNSArraySelector(
682 Arc? NSAPI::NSArr_initWithObjectsCount : NSAPI::NSArr_arrayWithObjectsCount);
683 ObjCMethodDecl *Method =
684 Arc? NSArrayDecl->lookupInstanceMethod(Sel)
685 : NSArrayDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000686 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000687 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000688 Method = ObjCMethodDecl::Create(
689 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000690 Context.getTranslationUnitDecl(),
691 Arc /*Instance for Arc, Class for MRR*/,
Alp Toker314cc812014-01-25 16:55:45 +0000692 false /*isVariadic*/,
693 /*isPropertyAccessor=*/false,
694 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
695 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000696 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000697 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000698 SourceLocation(),
699 SourceLocation(),
700 &Context.Idents.get("objects"),
701 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000702 /*TInfo=*/nullptr,
703 SC_None, nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000704 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000705 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000706 SourceLocation(),
707 SourceLocation(),
708 &Context.Idents.get("cnt"),
709 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000710 /*TInfo=*/nullptr, SC_None,
711 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000712 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000713 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000714 }
715
Jordy Rose08e500c2012-05-12 17:32:44 +0000716 if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000717 return ExprError();
Jordy Rose08e500c2012-05-12 17:32:44 +0000718
Jordy Rose4af44872012-05-12 17:32:56 +0000719 // Dig out the type that all elements should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000720 QualType T = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000721 const PointerType *PtrT = T->getAs<PointerType>();
722 if (!PtrT ||
723 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
724 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
725 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000726 Diag(Method->parameters()[0]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000727 diag::note_objc_literal_method_param)
728 << 0 << T
729 << Context.getPointerType(IdT.withConst());
730 return ExprError();
731 }
732
733 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000734 if (!Method->parameters()[1]->getType()->isIntegerType()) {
Jordy Rose4af44872012-05-12 17:32:56 +0000735 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
736 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000737 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000738 diag::note_objc_literal_method_param)
739 << 1
Alp Toker03376dc2014-07-07 09:02:20 +0000740 << Method->parameters()[1]->getType()
Jordy Rose4af44872012-05-12 17:32:56 +0000741 << "integral";
742 return ExprError();
743 }
744
745 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rose08e500c2012-05-12 17:32:44 +0000746 ArrayWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000747 }
748
Alp Toker03376dc2014-07-07 09:02:20 +0000749 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000750 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000751
752 // Check that each of the elements provided is valid in a collection literal,
753 // performing conversions as necessary.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000754 Expr **ElementsBuffer = Elements.data();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000755 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
756 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
757 ElementsBuffer[I],
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000758 RequiredType, true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000759 if (Converted.isInvalid())
760 return ExprError();
761
762 ElementsBuffer[I] = Converted.get();
763 }
764
765 QualType Ty
766 = Context.getObjCObjectPointerType(
767 Context.getObjCInterfaceType(NSArrayDecl));
768
769 return MaybeBindToTemporary(
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000770 ObjCArrayLiteral::Create(Context, Elements, Ty,
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000771 ArrayWithObjectsMethod,
772 ArrayAllocObjectsMethod, SR));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000773}
774
775ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
776 ObjCDictionaryElement *Elements,
777 unsigned NumElements) {
Fariborz Jahanian2a25dba2014-08-06 23:40:31 +0000778 bool Arc = getLangOpts().ObjCAutoRefCount;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000779 // Look up the NSDictionary class, if we haven't done so already.
780 if (!NSDictionaryDecl) {
781 NamedDecl *IF = LookupSingleName(TUScope,
782 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
783 SR.getBegin(), LookupOrdinaryName);
784 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000785 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000786 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
787 Context.getTranslationUnitDecl(),
788 SourceLocation(),
789 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
Craig Topperc3ec1492014-05-26 06:22:03 +0000790 nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000791
792 if (!NSDictionaryDecl) {
793 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
794 return ExprError();
795 }
796 }
797
Fariborz Jahanian2a25dba2014-08-06 23:40:31 +0000798 QualType IdT = Context.getObjCIdType();
799 if (Arc && !DictAllocObjectsMethod) {
800 // Find +[NSDictionary alloc] method.
801 IdentifierInfo *II = &Context.Idents.get("alloc");
802 Selector AllocSel = Context.Selectors.getSelector(0, &II);
803 DictAllocObjectsMethod = NSDictionaryDecl->lookupClassMethod(AllocSel);
804 if (!DictAllocObjectsMethod && getLangOpts().DebuggerObjCLiteral) {
805 DictAllocObjectsMethod = ObjCMethodDecl::Create(Context,
806 SourceLocation(), SourceLocation(), AllocSel,
807 IdT,
808 nullptr /*TypeSourceInfo */,
809 Context.getTranslationUnitDecl(),
810 false /*Instance*/, false/*isVariadic*/,
811 /*isPropertyAccessor=*/false,
812 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
813 ObjCMethodDecl::Required,
814 false);
815 SmallVector<ParmVarDecl *, 1> Params;
816 DictAllocObjectsMethod->setMethodParams(Context, Params, None);
817 }
818 if (!DictAllocObjectsMethod) {
819 Diag(SR.getBegin(), diag::err_undeclared_alloc);
820 return ExprError();
821 }
822 }
823
Fariborz Jahaniand45e7ce2014-08-07 20:57:35 +0000824 // Find the dictionaryWithObjects:forKeys:count: or initWithObjects:forKeys:count:
825 // (for arc) method, if we haven't done so already.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000826 if (!DictionaryWithObjectsMethod) {
Fariborz Jahaniand45e7ce2014-08-07 20:57:35 +0000827 Selector Sel =
828 NSAPIObj->getNSDictionarySelector(Arc? NSAPI::NSDict_initWithObjectsForKeysCount
829 : NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
830 ObjCMethodDecl *Method =
831 Arc ? NSDictionaryDecl->lookupInstanceMethod(Sel)
832 : NSDictionaryDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000833 if (!Method && getLangOpts().DebuggerObjCLiteral) {
834 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000835 SourceLocation(), SourceLocation(), Sel,
836 IdT,
Craig Topperc3ec1492014-05-26 06:22:03 +0000837 nullptr /*TypeSourceInfo */,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000838 Context.getTranslationUnitDecl(),
Fariborz Jahaniand45e7ce2014-08-07 20:57:35 +0000839 Arc /*Instance for Arc, Class for MRR*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000840 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000841 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
842 ObjCMethodDecl::Required,
843 false);
844 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000845 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000846 SourceLocation(),
847 SourceLocation(),
848 &Context.Idents.get("objects"),
849 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000850 /*TInfo=*/nullptr, SC_None,
851 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000852 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000853 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000854 SourceLocation(),
855 SourceLocation(),
856 &Context.Idents.get("keys"),
857 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000858 /*TInfo=*/nullptr, SC_None,
859 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000860 Params.push_back(keys);
Jordy Rose08e500c2012-05-12 17:32:44 +0000861 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000862 SourceLocation(),
863 SourceLocation(),
864 &Context.Idents.get("cnt"),
865 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000866 /*TInfo=*/nullptr, SC_None,
867 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000868 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000869 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000870 }
871
Jordy Rose08e500c2012-05-12 17:32:44 +0000872 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
873 Method))
874 return ExprError();
875
Jordy Rose4af44872012-05-12 17:32:56 +0000876 // Dig out the type that all values should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000877 QualType ValueT = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000878 const PointerType *PtrValue = ValueT->getAs<PointerType>();
879 if (!PtrValue ||
880 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000881 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000882 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000883 Diag(Method->parameters()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000884 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000885 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000886 << Context.getPointerType(IdT.withConst());
887 return ExprError();
888 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000889
Jordy Rose4af44872012-05-12 17:32:56 +0000890 // Dig out the type that all keys should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000891 QualType KeyT = Method->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000892 const PointerType *PtrKey = KeyT->getAs<PointerType>();
893 if (!PtrKey ||
894 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
895 IdT)) {
896 bool err = true;
897 if (PtrKey) {
898 if (QIDNSCopying.isNull()) {
899 // key argument of selector is id<NSCopying>?
900 if (ObjCProtocolDecl *NSCopyingPDecl =
901 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
902 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
903 QIDNSCopying =
904 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
905 (ObjCProtocolDecl**) PQ,1);
906 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
907 }
908 }
909 if (!QIDNSCopying.isNull())
910 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
911 QIDNSCopying);
912 }
913
914 if (err) {
915 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
916 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000917 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000918 diag::note_objc_literal_method_param)
919 << 1 << KeyT
920 << Context.getPointerType(IdT.withConst());
921 return ExprError();
922 }
923 }
924
925 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000926 QualType CountType = Method->parameters()[2]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000927 if (!CountType->isIntegerType()) {
928 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
929 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000930 Diag(Method->parameters()[2]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000931 diag::note_objc_literal_method_param)
932 << 2 << CountType
933 << "integral";
934 return ExprError();
935 }
936
937 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
938 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000939 }
940
Alp Toker03376dc2014-07-07 09:02:20 +0000941 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000942 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
Alp Toker03376dc2014-07-07 09:02:20 +0000943 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000944 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
945
Ted Kremeneke65b0862012-03-06 20:05:56 +0000946 // Check that each of the keys and values provided is valid in a collection
947 // literal, performing conversions as necessary.
948 bool HasPackExpansions = false;
949 for (unsigned I = 0, N = NumElements; I != N; ++I) {
950 // Check the key.
951 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
952 KeyT);
953 if (Key.isInvalid())
954 return ExprError();
955
956 // Check the value.
957 ExprResult Value
958 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
959 if (Value.isInvalid())
960 return ExprError();
961
962 Elements[I].Key = Key.get();
963 Elements[I].Value = Value.get();
964
965 if (Elements[I].EllipsisLoc.isInvalid())
966 continue;
967
968 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
969 !Elements[I].Value->containsUnexpandedParameterPack()) {
970 Diag(Elements[I].EllipsisLoc,
971 diag::err_pack_expansion_without_parameter_packs)
972 << SourceRange(Elements[I].Key->getLocStart(),
973 Elements[I].Value->getLocEnd());
974 return ExprError();
975 }
976
977 HasPackExpansions = true;
978 }
979
980
981 QualType Ty
982 = Context.getObjCObjectPointerType(
Robert Wilhelm88e02492013-08-19 07:57:02 +0000983 Context.getObjCInterfaceType(NSDictionaryDecl));
984 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
985 Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty,
Fariborz Jahanian2a25dba2014-08-06 23:40:31 +0000986 DictionaryWithObjectsMethod, DictAllocObjectsMethod, SR));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000987}
988
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000989ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregorabd9e962010-04-20 15:39:42 +0000990 TypeSourceInfo *EncodedTypeInfo,
Anders Carlsson315d2292009-06-07 18:45:35 +0000991 SourceLocation RParenLoc) {
Douglas Gregorabd9e962010-04-20 15:39:42 +0000992 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlsson315d2292009-06-07 18:45:35 +0000993 QualType StrTy;
Mike Stump11289f42009-09-09 15:08:12 +0000994 if (EncodedType->isDependentType())
Anders Carlsson315d2292009-06-07 18:45:35 +0000995 StrTy = Context.DependentTy;
996 else {
Fariborz Jahaniand9bc6c32011-06-16 22:34:44 +0000997 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
998 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000999 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001000 diag::err_incomplete_type_objc_at_encode,
1001 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +00001002 return ExprError();
1003
Anders Carlsson315d2292009-06-07 18:45:35 +00001004 std::string Str;
1005 Context.getObjCEncodingForType(EncodedType, Str);
1006
1007 // The type of @encode is the same as the type of the corresponding string,
1008 // which is an array type.
1009 StrTy = Context.CharTy;
1010 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001011 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlsson315d2292009-06-07 18:45:35 +00001012 StrTy.addConst();
1013 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
1014 ArrayType::Normal, 0);
1015 }
Mike Stump11289f42009-09-09 15:08:12 +00001016
Douglas Gregorabd9e962010-04-20 15:39:42 +00001017 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlsson315d2292009-06-07 18:45:35 +00001018}
1019
John McCallfaf5fb42010-08-26 23:41:50 +00001020ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1021 SourceLocation EncodeLoc,
1022 SourceLocation LParenLoc,
1023 ParsedType ty,
1024 SourceLocation RParenLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001025 // FIXME: Preserve type source info ?
Douglas Gregorabd9e962010-04-20 15:39:42 +00001026 TypeSourceInfo *TInfo;
1027 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1028 if (!TInfo)
1029 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
1030 PP.getLocForEndOfToken(LParenLoc));
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001031
Douglas Gregorabd9e962010-04-20 15:39:42 +00001032 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001033}
1034
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001035static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1036 SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001037 SourceLocation LParenLoc,
1038 SourceLocation RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001039 ObjCMethodDecl *Method,
1040 ObjCMethodList &MethList) {
1041 ObjCMethodList *M = &MethList;
1042 bool Warned = false;
1043 for (M = M->getNext(); M; M=M->getNext()) {
1044 ObjCMethodDecl *MatchingMethodDecl = M->Method;
1045 if (MatchingMethodDecl == Method ||
1046 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1047 MatchingMethodDecl->getSelector() != Method->getSelector())
1048 continue;
1049 if (!S.MatchTwoMethodDeclarations(Method,
1050 MatchingMethodDecl, Sema::MMS_loose)) {
1051 if (!Warned) {
1052 Warned = true;
1053 S.Diag(AtLoc, diag::warning_multiple_selectors)
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001054 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1055 << FixItHint::CreateInsertion(RParenLoc, ")");
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001056 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1057 << Method->getDeclName();
1058 }
1059 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1060 << MatchingMethodDecl->getDeclName();
1061 }
1062 }
1063 return Warned;
1064}
1065
1066static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001067 ObjCMethodDecl *Method,
1068 SourceLocation LParenLoc,
1069 SourceLocation RParenLoc,
1070 bool WarnMultipleSelectors) {
1071 if (!WarnMultipleSelectors ||
1072 S.Diags.isIgnored(diag::warning_multiple_selectors, SourceLocation()))
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001073 return;
1074 bool Warned = false;
1075 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1076 e = S.MethodPool.end(); b != e; b++) {
1077 // first, instance methods
1078 ObjCMethodList &InstMethList = b->second.first;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001079 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001080 Method, InstMethList))
1081 Warned = true;
1082
1083 // second, class methods
1084 ObjCMethodList &ClsMethList = b->second.second;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001085 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1086 Method, ClsMethList) || Warned)
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001087 return;
1088 }
1089}
1090
John McCallfaf5fb42010-08-26 23:41:50 +00001091ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1092 SourceLocation AtLoc,
1093 SourceLocation SelLoc,
1094 SourceLocation LParenLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001095 SourceLocation RParenLoc,
1096 bool WarnMultipleSelectors) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001097 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1098 SourceRange(LParenLoc, RParenLoc), false, false);
1099 if (!Method)
1100 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian0571d9b2009-06-16 16:25:00 +00001101 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00001102 if (!Method) {
1103 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1104 Selector MatchedSel = OM->getSelector();
1105 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1106 RParenLoc.getLocWithOffset(-1));
1107 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1108 << Sel << MatchedSel
1109 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1110
1111 } else
1112 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001113 } else
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001114 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1115 WarnMultipleSelectors);
Fariborz Jahanian9a881012011-07-13 19:05:43 +00001116
Fariborz Jahanian65a78b52014-05-09 19:51:39 +00001117 if (Method &&
1118 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
1119 !getSourceManager().isInSystemHeader(Method->getLocation())) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001120 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
1121 = ReferencedSelectors.find(Sel);
1122 if (Pos == ReferencedSelectors.end())
1123 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian9a881012011-07-13 19:05:43 +00001124 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001125
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001126 // In ARC, forbid the user from using @selector for
John McCall31168b02011-06-15 23:02:42 +00001127 // retain/release/autorelease/dealloc/retainCount.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001128 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001129 switch (Sel.getMethodFamily()) {
1130 case OMF_retain:
1131 case OMF_release:
1132 case OMF_autorelease:
1133 case OMF_retainCount:
1134 case OMF_dealloc:
1135 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1136 Sel << SourceRange(LParenLoc, RParenLoc);
1137 break;
1138
1139 case OMF_None:
1140 case OMF_alloc:
1141 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00001142 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00001143 case OMF_init:
1144 case OMF_mutableCopy:
1145 case OMF_new:
1146 case OMF_self:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001147 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001148 break;
1149 }
1150 }
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001151 QualType Ty = Context.getObjCSelType();
Daniel Dunbar45858d22010-02-03 20:11:42 +00001152 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001153}
1154
John McCallfaf5fb42010-08-26 23:41:50 +00001155ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1156 SourceLocation AtLoc,
1157 SourceLocation ProtoLoc,
1158 SourceLocation LParenLoc,
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001159 SourceLocation ProtoIdLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00001160 SourceLocation RParenLoc) {
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001161 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001162 if (!PDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001163 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001164 return true;
1165 }
Fariborz Jahaniana57d91c22014-07-25 19:45:01 +00001166 if (PDecl->hasDefinition())
1167 PDecl = PDecl->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00001168
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001169 QualType Ty = Context.getObjCProtoType();
1170 if (Ty.isNull())
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001171 return true;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001172 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001173 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001174}
1175
John McCall5f2d5562011-02-03 09:00:02 +00001176/// Try to capture an implicit reference to 'self'.
Eli Friedman24af8502012-02-03 22:47:37 +00001177ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1178 DeclContext *DC = getFunctionLevelDeclContext();
John McCall5f2d5562011-02-03 09:00:02 +00001179
1180 // If we're not in an ObjC method, error out. Note that, unlike the
1181 // C++ case, we don't require an instance method --- class methods
1182 // still have a 'self', and we really do still need to capture it!
1183 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1184 if (!method)
Craig Topperc3ec1492014-05-26 06:22:03 +00001185 return nullptr;
John McCall5f2d5562011-02-03 09:00:02 +00001186
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001187 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall5f2d5562011-02-03 09:00:02 +00001188
1189 return method;
1190}
1191
Douglas Gregor64910ca2011-09-09 20:05:21 +00001192static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1193 if (T == Context.getObjCInstanceType())
1194 return Context.getObjCIdType();
1195
1196 return T;
1197}
1198
Douglas Gregor33823722011-06-11 01:09:30 +00001199QualType Sema::getMessageSendResultType(QualType ReceiverType,
1200 ObjCMethodDecl *Method,
1201 bool isClassMessage, bool isSuperMessage) {
1202 assert(Method && "Must have a method");
1203 if (!Method->hasRelatedResultType())
1204 return Method->getSendResultType();
1205
1206 // If a method has a related return type:
1207 // - if the method found is an instance method, but the message send
1208 // was a class message send, T is the declared return type of the method
1209 // found
1210 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor64910ca2011-09-09 20:05:21 +00001211 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001212
1213 // - if the receiver is super, T is a pointer to the class of the
1214 // enclosing method definition
1215 if (isSuperMessage) {
1216 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1217 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1218 return Context.getObjCObjectPointerType(
1219 Context.getObjCInterfaceType(Class));
1220 }
1221
1222 // - if the receiver is the name of a class U, T is a pointer to U
1223 if (ReceiverType->getAs<ObjCInterfaceType>() ||
1224 ReceiverType->isObjCQualifiedInterfaceType())
1225 return Context.getObjCObjectPointerType(ReceiverType);
1226 // - if the receiver is of type Class or qualified Class type,
1227 // T is the declared return type of the method.
1228 if (ReceiverType->isObjCClassType() ||
1229 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor64910ca2011-09-09 20:05:21 +00001230 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001231
1232 // - if the receiver is id, qualified id, Class, or qualified Class, T
1233 // is the receiver type, otherwise
1234 // - T is the type of the receiver expression.
1235 return ReceiverType;
1236}
John McCall5f2d5562011-02-03 09:00:02 +00001237
John McCall5ec7e7d2013-03-19 07:04:25 +00001238/// Look for an ObjC method whose result type exactly matches the given type.
1239static const ObjCMethodDecl *
1240findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1241 QualType instancetype) {
Alp Toker314cc812014-01-25 16:55:45 +00001242 if (MD->getReturnType() == instancetype)
1243 return MD;
John McCall5ec7e7d2013-03-19 07:04:25 +00001244
1245 // For these purposes, a method in an @implementation overrides a
1246 // declaration in the @interface.
1247 if (const ObjCImplDecl *impl =
1248 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1249 const ObjCContainerDecl *iface;
1250 if (const ObjCCategoryImplDecl *catImpl =
1251 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1252 iface = catImpl->getCategoryDecl();
1253 } else {
1254 iface = impl->getClassInterface();
1255 }
1256
1257 const ObjCMethodDecl *ifaceMD =
1258 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1259 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1260 }
1261
1262 SmallVector<const ObjCMethodDecl *, 4> overrides;
1263 MD->getOverriddenMethods(overrides);
1264 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1265 if (const ObjCMethodDecl *result =
1266 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1267 return result;
1268 }
1269
Craig Topperc3ec1492014-05-26 06:22:03 +00001270 return nullptr;
John McCall5ec7e7d2013-03-19 07:04:25 +00001271}
1272
1273void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1274 // Only complain if we're in an ObjC method and the required return
1275 // type doesn't match the method's declared return type.
1276 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1277 if (!MD || !MD->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +00001278 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
John McCall5ec7e7d2013-03-19 07:04:25 +00001279 return;
1280
1281 // Look for a method overridden by this method which explicitly uses
1282 // 'instancetype'.
1283 if (const ObjCMethodDecl *overridden =
1284 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +00001285 SourceRange range = overridden->getReturnTypeSourceRange();
1286 SourceLocation loc = range.getBegin();
John McCall5ec7e7d2013-03-19 07:04:25 +00001287 if (loc.isInvalid())
1288 loc = overridden->getLocation();
1289 Diag(loc, diag::note_related_result_type_explicit)
1290 << /*current method*/ 1 << range;
1291 return;
1292 }
1293
1294 // Otherwise, if we have an interesting method family, note that.
1295 // This should always trigger if the above didn't.
1296 if (ObjCMethodFamily family = MD->getMethodFamily())
1297 Diag(MD->getLocation(), diag::note_related_result_type_family)
1298 << /*current method*/ 1
1299 << family;
1300}
1301
Douglas Gregor33823722011-06-11 01:09:30 +00001302void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1303 E = E->IgnoreParenImpCasts();
1304 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1305 if (!MsgSend)
1306 return;
1307
1308 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1309 if (!Method)
1310 return;
1311
1312 if (!Method->hasRelatedResultType())
1313 return;
Alp Toker314cc812014-01-25 16:55:45 +00001314
1315 if (Context.hasSameUnqualifiedType(
1316 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
Douglas Gregor33823722011-06-11 01:09:30 +00001317 return;
Alp Toker314cc812014-01-25 16:55:45 +00001318
1319 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
Douglas Gregorbab8a962011-09-08 01:46:34 +00001320 Context.getObjCInstanceType()))
1321 return;
1322
Douglas Gregor33823722011-06-11 01:09:30 +00001323 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1324 << Method->isInstanceMethod() << Method->getSelector()
1325 << MsgSend->getType();
1326}
1327
1328bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001329 MultiExprArg Args,
1330 Selector Sel,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001331 ArrayRef<SourceLocation> SelectorLocs,
1332 ObjCMethodDecl *Method,
Douglas Gregor33823722011-06-11 01:09:30 +00001333 bool isClassMessage, bool isSuperMessage,
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001334 SourceLocation lbrac, SourceLocation rbrac,
John McCall7decc9e2010-11-18 06:31:45 +00001335 QualType &ReturnType, ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001336 SourceLocation SelLoc;
1337 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1338 SelLoc = SelectorLocs.front();
1339 else
1340 SelLoc = lbrac;
1341
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001342 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001343 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001344 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001345 if (Args[i]->isTypeDependent())
1346 continue;
1347
John McCallcc5788c2013-03-04 07:34:02 +00001348 ExprResult result;
1349 if (getLangOpts().DebuggerSupport) {
1350 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001351 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001352 } else {
1353 result = DefaultArgumentPromotion(Args[i]);
1354 }
1355 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001356 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001357 Args[i] = result.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001358 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001359
John McCall31168b02011-06-15 23:02:42 +00001360 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001361 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001362 DiagID = diag::err_arc_method_not_found;
1363 else
1364 DiagID = isClassMessage ? diag::warn_class_method_not_found
1365 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001366 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001367 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahanian06499232013-06-18 17:10:58 +00001368 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001369 if (getLangOpts().ObjCAutoRefCount)
1370 DiagID = diag::error_method_not_found_with_typo;
1371 else
1372 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1373 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001374 Selector MatchedSel = OMD->getSelector();
1375 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001376 Diag(SelLoc, DiagID)
1377 << Sel<< isClassMessage << MatchedSel
Fariborz Jahanian75481672013-06-17 17:10:54 +00001378 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1379 }
1380 else
1381 Diag(SelLoc, DiagID)
1382 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001383 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001384 // Find the class to which we are sending this message.
1385 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian478536b2013-05-15 15:27:35 +00001386 if (ObjCInterfaceDecl *Class =
1387 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl())
1388 Diag(Class->getLocation(), diag::note_receiver_class_declared);
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001389 }
1390 }
John McCall3f4138c2011-07-13 17:56:40 +00001391
1392 // In debuggers, we want to use __unknown_anytype for these
1393 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001394 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001395 ReturnType = Context.UnknownAnyTy;
1396 } else {
1397 ReturnType = Context.getObjCIdType();
1398 }
John McCall7decc9e2010-11-18 06:31:45 +00001399 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001400 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001401 }
Mike Stump11289f42009-09-09 15:08:12 +00001402
Douglas Gregor33823722011-06-11 01:09:30 +00001403 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1404 isSuperMessage);
Alp Toker314cc812014-01-25 16:55:45 +00001405 VK = Expr::getValueKindForType(Method->getReturnType());
Mike Stump11289f42009-09-09 15:08:12 +00001406
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001407 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001408 // Method might have more arguments than selector indicates. This is due
1409 // to addition of c-style arguments in method.
1410 if (Method->param_size() > Sel.getNumArgs())
1411 NumNamedArgs = Method->param_size();
1412 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001413 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001414 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001415 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001416 return false;
1417 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001418
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001419 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001420 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001421 // We can't do any type-checking on a type-dependent argument.
1422 if (Args[i]->isTypeDependent())
1423 continue;
1424
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001425 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001426
Alp Toker03376dc2014-07-07 09:02:20 +00001427 ParmVarDecl *param = Method->parameters()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001428 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001429
John McCall4124c492011-10-17 18:40:02 +00001430 // Strip the unbridged-cast placeholder expression off unless it's
1431 // a consumed argument.
1432 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1433 !param->hasAttr<CFConsumedAttr>())
1434 argExpr = stripARCUnbridgedCast(argExpr);
1435
John McCallea0a39e2012-11-14 00:49:39 +00001436 // If the parameter is __unknown_anytype, infer its type
1437 // from the argument.
1438 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001439 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001440 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001441 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001442 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001443 } else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001444 Args[i] = argE.get();
John McCallea0a39e2012-11-14 00:49:39 +00001445
John McCallcc5788c2013-03-04 07:34:02 +00001446 // Update the parameter type in-place.
1447 param->setType(paramType);
1448 }
1449 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001450 }
1451
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001452 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall4124c492011-10-17 18:40:02 +00001453 param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001454 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001455 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001456
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001457 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall4124c492011-10-17 18:40:02 +00001458 param);
Fariborz Jahaniana1db7df2014-07-31 17:39:50 +00001459 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001460 if (ArgE.isInvalid())
1461 IsError = true;
1462 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001463 Args[i] = ArgE.getAs<Expr>();
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001464 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001465
1466 // Promote additional arguments to variadic methods.
1467 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001468 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001469 if (Args[i]->isTypeDependent())
1470 continue;
1471
Jordy Roseaca01f92012-05-12 17:32:52 +00001472 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
Craig Topperc3ec1492014-05-26 06:22:03 +00001473 nullptr);
John Wiegley01296292011-04-08 18:41:53 +00001474 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001475 Args[i] = Arg.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001476 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001477 } else {
1478 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001479 if (Args.size() != NumNamedArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00001480 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001481 diag::err_typecheck_call_too_many_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001482 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001483 << Method->getSourceRange()
Chris Lattner3b054132008-11-19 05:08:23 +00001484 << SourceRange(Args[NumNamedArgs]->getLocStart(),
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001485 Args.back()->getLocEnd());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001486 }
1487 }
1488
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001489 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001490
1491 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001492 IsError |= CheckObjCMethodCall(
Robert Wilhelm88e02492013-08-19 07:57:02 +00001493 Method, SelLoc, makeArrayRef<const Expr *>(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001494
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001495 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001496}
1497
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001498bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001499 // 'self' is objc 'self' in an objc method only.
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001500 ObjCMethodDecl *Method =
1501 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1502 return isSelfExpr(RExpr, Method);
1503}
1504
1505bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
John McCallfe96e0b2011-11-06 09:01:30 +00001506 if (!method) return false;
1507
John McCall31168b02011-06-15 23:02:42 +00001508 receiver = receiver->IgnoreParenLValueCasts();
1509 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001510 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001511 return true;
1512 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001513}
1514
John McCall526ab472011-10-25 17:37:35 +00001515/// LookupMethodInType - Look up a method in an ObjCObjectType.
1516ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1517 bool isInstance) {
1518 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1519 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1520 // Look it up in the main interface (and categories, etc.)
1521 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1522 return method;
1523
1524 // Okay, look for "private" methods declared in any
1525 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001526 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1527 return method;
John McCall526ab472011-10-25 17:37:35 +00001528 }
1529
1530 // Check qualifiers.
Aaron Ballman1683f7b2014-03-17 15:55:30 +00001531 for (const auto *I : objType->quals())
1532 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
John McCall526ab472011-10-25 17:37:35 +00001533 return method;
1534
Craig Topperc3ec1492014-05-26 06:22:03 +00001535 return nullptr;
John McCall526ab472011-10-25 17:37:35 +00001536}
1537
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001538/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1539/// list of a qualified objective pointer type.
1540ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1541 const ObjCObjectPointerType *OPT,
1542 bool Instance)
1543{
Craig Topperc3ec1492014-05-26 06:22:03 +00001544 ObjCMethodDecl *MD = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +00001545 for (const auto *PROTO : OPT->quals()) {
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001546 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1547 return MD;
1548 }
1549 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001550 return nullptr;
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001551}
1552
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001553static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1554 if (!Receiver)
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001555 return;
1556
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001557 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver))
1558 Receiver = OVE->getSourceExpr();
1559
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001560 Expr *RExpr = Receiver->IgnoreParenImpCasts();
1561 SourceLocation Loc = RExpr->getLocStart();
1562 QualType T = RExpr->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001563 const ObjCPropertyDecl *PDecl = nullptr;
1564 const ObjCMethodDecl *GDecl = nullptr;
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001565 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1566 RExpr = POE->getSyntacticForm();
1567 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1568 if (PRE->isImplicitProperty()) {
1569 GDecl = PRE->getImplicitPropertyGetter();
1570 if (GDecl) {
Alp Toker314cc812014-01-25 16:55:45 +00001571 T = GDecl->getReturnType();
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001572 }
1573 }
1574 else {
1575 PDecl = PRE->getExplicitProperty();
1576 if (PDecl) {
1577 T = PDecl->getType();
1578 }
1579 }
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001580 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001581 }
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001582 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) {
1583 // See if receiver is a method which envokes a synthesized getter
1584 // backing a 'weak' property.
1585 ObjCMethodDecl *Method = ME->getMethodDecl();
Jordan Rose2bd991a2012-10-10 16:42:54 +00001586 if (Method && Method->getSelector().getNumArgs() == 0) {
1587 PDecl = Method->findPropertyDecl();
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001588 if (PDecl)
1589 T = PDecl->getType();
1590 }
1591 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001592
Jordan Rose13d6b712012-09-28 22:21:42 +00001593 if (T.getObjCLifetime() != Qualifiers::OCL_Weak) {
1594 if (!PDecl)
1595 return;
1596 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak))
1597 return;
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001598 }
Jordan Rose13d6b712012-09-28 22:21:42 +00001599
1600 S.Diag(Loc, diag::warn_receiver_is_weak)
1601 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1602
1603 if (PDecl)
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001604 S.Diag(PDecl->getLocation(), diag::note_property_declare);
Jordan Rose13d6b712012-09-28 22:21:42 +00001605 else if (GDecl)
1606 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
1607
1608 S.Diag(Loc, diag::note_arc_assign_to_strong);
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001609}
1610
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001611/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1612/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001613ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001614HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001615 Expr *BaseExpr, SourceLocation OpLoc,
1616 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001617 SourceLocation MemberLoc,
1618 SourceLocation SuperLoc, QualType SuperType,
1619 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001620 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1621 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001622
Benjamin Kramer365082d2012-05-19 16:34:46 +00001623 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001624 Diag(MemberLoc, diag::err_invalid_property_name)
1625 << MemberName << QualType(OPT, 0);
1626 return ExprError();
1627 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001628
1629 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregord6459312011-04-20 18:19:55 +00001630
Douglas Gregor4123a862011-11-14 22:10:01 +00001631 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1632 : BaseExpr->getSourceRange();
1633 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001634 diag::err_property_not_found_forward_class,
1635 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001636 return ExprError();
Douglas Gregor4123a862011-11-14 22:10:01 +00001637
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001638 // Search for a declared property first.
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001639 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001640 // Check whether we can reference this property.
1641 if (DiagnoseUseOfDecl(PD, MemberLoc))
1642 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001643 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001644 return new (Context)
1645 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1646 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001647 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001648 return new (Context)
1649 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1650 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001651 }
1652 // Check protocols on qualified interfaces.
Aaron Ballman83731462014-03-17 16:14:00 +00001653 for (const auto *I : OPT->quals())
1654 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001655 // Check whether we can reference this property.
1656 if (DiagnoseUseOfDecl(PD, MemberLoc))
1657 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001658
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001659 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001660 return new (Context) ObjCPropertyRefExpr(
1661 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1662 SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001663 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001664 return new (Context)
1665 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1666 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001667 }
1668 // If that failed, look for an "implicit" property by seeing if the nullary
1669 // selector is implemented.
1670
1671 // FIXME: The logic for looking up nullary and unary selectors should be
1672 // shared with the code in ActOnInstanceMessage.
1673
1674 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1675 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001676
1677 // May be founf in property's qualified list.
1678 if (!Getter)
1679 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001680
1681 // If this reference is in an @implementation, check for 'private' methods.
1682 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001683 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001684
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001685 if (Getter) {
1686 // Check if we can reference this property.
1687 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1688 return ExprError();
1689 }
1690 // If we found a getter then this may be a valid dot-reference, we
1691 // will look for the matching setter, in case it is needed.
1692 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001693 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1694 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001695 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001696
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001697 // May be founf in property's qualified list.
1698 if (!Setter)
1699 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1700
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001701 if (!Setter) {
1702 // If this reference is in an @implementation, also check for 'private'
1703 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001704 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001705 }
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001706
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001707 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1708 return ExprError();
1709
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001710 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001711 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001712 return new (Context)
1713 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1714 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001715 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001716 return new (Context)
1717 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1718 OK_ObjCProperty, MemberLoc, BaseExpr);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001719
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001720 }
1721
1722 // Attempt to correct for typos in property names.
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001723 DeclFilterCCC<ObjCPropertyDecl> Validator;
1724 if (TypoCorrection Corrected = CorrectTypo(
Craig Topperc3ec1492014-05-26 06:22:03 +00001725 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName,
1726 nullptr, nullptr, Validator, CTK_ErrorRecovery, IFace, false, OPT)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001727 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1728 << MemberName << QualType(OPT, 0));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001729 DeclarationName TypoResult = Corrected.getCorrection();
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001730 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1731 TypoResult, MemberLoc,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001732 SuperLoc, SuperType, Super);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001733 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001734 ObjCInterfaceDecl *ClassDeclared;
1735 if (ObjCIvarDecl *Ivar =
1736 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1737 QualType T = Ivar->getType();
1738 if (const ObjCObjectPointerType * OBJPT =
1739 T->getAsObjCInterfacePointerType()) {
Douglas Gregor4123a862011-11-14 22:10:01 +00001740 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001741 diag::err_property_not_as_forward_class,
1742 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001743 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001744 }
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001745 Diag(MemberLoc,
1746 diag::err_ivar_access_using_property_syntax_suggest)
1747 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1748 << FixItHint::CreateReplacement(OpLoc, "->");
1749 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001750 }
Chris Lattner90c58fa2010-04-11 07:51:10 +00001751
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001752 Diag(MemberLoc, diag::err_property_not_found)
1753 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001754 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001755 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001756 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001757 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001758}
1759
1760
1761
John McCalldadc5752010-08-24 06:29:42 +00001762ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001763ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1764 IdentifierInfo &propertyName,
1765 SourceLocation receiverNameLoc,
1766 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001767
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001768 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001769 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1770 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001771
1772 bool IsSuper = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00001773 if (!IFace) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001774 // If the "receiver" is 'super' in a method, handle it as an expression-like
1775 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001776 if (receiverNamePtr->isStr("super")) {
Douglas Gregor33823722011-06-11 01:09:30 +00001777 IsSuper = true;
1778
Eli Friedman24af8502012-02-03 22:47:37 +00001779 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001780 if (CurMethod->isInstanceMethod()) {
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00001781 ObjCInterfaceDecl *Super =
1782 CurMethod->getClassInterface()->getSuperClass();
1783 if (!Super) {
1784 // The current class does not have a superclass.
1785 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1786 << CurMethod->getClassInterface()->getIdentifier();
1787 return ExprError();
1788 }
1789 QualType T = Context.getObjCInterfaceType(Super);
Chris Lattnera36ec422010-04-11 08:28:14 +00001790 T = Context.getObjCObjectPointerType(T);
Craig Topperc3ec1492014-05-26 06:22:03 +00001791
Chris Lattnera36ec422010-04-11 08:28:14 +00001792 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001793 /*BaseExpr*/nullptr,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001794 SourceLocation()/*OpLoc*/,
1795 &propertyName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001796 propertyNameLoc,
1797 receiverNameLoc, T, true);
Chris Lattnera36ec422010-04-11 08:28:14 +00001798 }
Mike Stump11289f42009-09-09 15:08:12 +00001799
Chris Lattnera36ec422010-04-11 08:28:14 +00001800 // Otherwise, if this is a class method, try dispatching to our
1801 // superclass.
1802 IFace = CurMethod->getClassInterface()->getSuperClass();
1803 }
John McCall5f2d5562011-02-03 09:00:02 +00001804 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001805
1806 if (!IFace) {
Alp Tokerec543272013-12-24 09:48:30 +00001807 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1808 << tok::l_paren;
Chris Lattnera36ec422010-04-11 08:28:14 +00001809 return ExprError();
1810 }
1811 }
1812
1813 // Search for a declared property first.
Steve Naroff9527bbf2009-03-09 21:12:44 +00001814 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001815 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001816
1817 // If this reference is in an @implementation, check for 'private' methods.
1818 if (!Getter)
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001819 Getter = IFace->lookupPrivateClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001820
1821 if (Getter) {
1822 // FIXME: refactor/share with ActOnMemberReference().
1823 // Check if we can reference this property.
1824 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1825 return ExprError();
1826 }
Mike Stump11289f42009-09-09 15:08:12 +00001827
Steve Naroff9527bbf2009-03-09 21:12:44 +00001828 // Look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00001829 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001830 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1831 PP.getSelectorTable(),
1832 &propertyName);
Mike Stump11289f42009-09-09 15:08:12 +00001833
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001834 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001835 if (!Setter) {
1836 // If this reference is in an @implementation, also check for 'private'
1837 // methods.
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001838 Setter = IFace->lookupPrivateClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001839 }
1840 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00001841 if (!Setter)
1842 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001843
1844 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1845 return ExprError();
1846
1847 if (Getter || Setter) {
Douglas Gregor33823722011-06-11 01:09:30 +00001848 if (IsSuper)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001849 return new (Context)
1850 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1851 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
1852 Context.getObjCInterfaceType(IFace));
Douglas Gregor33823722011-06-11 01:09:30 +00001853
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001854 return new (Context) ObjCPropertyRefExpr(
1855 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
1856 propertyNameLoc, receiverNameLoc, IFace);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001857 }
1858 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1859 << &propertyName << Context.getObjCInterfaceType(IFace));
1860}
1861
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001862namespace {
1863
1864class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1865 public:
1866 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1867 // Determine whether "super" is acceptable in the current context.
1868 if (Method && Method->getClassInterface())
1869 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1870 }
1871
Craig Toppere14c0f82014-03-12 04:55:44 +00001872 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001873 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1874 candidate.isKeyword("super");
1875 }
1876};
1877
1878}
1879
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001880Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001881 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001882 SourceLocation NameLoc,
1883 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001884 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00001885 ParsedType &ReceiverType) {
1886 ReceiverType = ParsedType();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001887
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001888 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00001889 // messaging super. If the identifier is "super" and there is a
1890 // trailing dot, it's an instance message.
1891 if (IsSuper && S->isInObjcMethodScope())
1892 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001893
1894 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1895 LookupName(Result, S);
1896
1897 switch (Result.getResultKind()) {
1898 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00001899 // Normal name lookup didn't find anything. If we're in an
1900 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00001901 // FIXME: This is a hack. Ivar lookup should be part of normal
1902 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00001903 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00001904 if (!Method->getClassInterface()) {
1905 // Fall back: let the parser try to parse it as an instance message.
1906 return ObjCInstanceMessage;
1907 }
1908
Douglas Gregorca7136b2010-04-19 20:09:36 +00001909 ObjCInterfaceDecl *ClassDeclared;
1910 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1911 ClassDeclared))
1912 return ObjCInstanceMessage;
1913 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00001914
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001915 // Break out; we'll perform typo correction below.
1916 break;
1917
1918 case LookupResult::NotFoundInCurrentInstantiation:
1919 case LookupResult::FoundOverloaded:
1920 case LookupResult::FoundUnresolvedValue:
1921 case LookupResult::Ambiguous:
1922 Result.suppressDiagnostics();
1923 return ObjCInstanceMessage;
1924
1925 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00001926 // If the identifier is a class or not, and there is a trailing dot,
1927 // it's an instance message.
1928 if (HasTrailingDot)
1929 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001930 // We found something. If it's a type, then we have a class
1931 // message. Otherwise, it's an instance message.
1932 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001933 QualType T;
1934 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1935 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001936 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00001937 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001938 DiagnoseUseOfDecl(Type, NameLoc);
1939 }
1940 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00001941 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001942
Douglas Gregore5798dc2010-04-21 20:38:13 +00001943 // We have a class message, and T is the type we're
1944 // messaging. Build source-location information for it.
1945 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00001946 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00001947 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001948 }
1949 }
1950
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001951 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00001952 if (TypoCorrection Corrected =
1953 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
Craig Topperc3ec1492014-05-26 06:22:03 +00001954 nullptr, Validator, CTK_ErrorRecovery, nullptr, false,
1955 nullptr, false)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001956 if (Corrected.isKeyword()) {
1957 // If we've found the keyword "super" (the only keyword that would be
1958 // returned by CorrectTypo), this is a send to super.
Richard Smithf9b15102013-08-17 00:46:16 +00001959 diagnoseTypo(Corrected,
1960 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001961 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001962 } else if (ObjCInterfaceDecl *Class =
Richard Smithf9b15102013-08-17 00:46:16 +00001963 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001964 // If we found a declaration, correct when it refers to an Objective-C
1965 // class.
Richard Smithf9b15102013-08-17 00:46:16 +00001966 diagnoseTypo(Corrected,
1967 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001968 QualType T = Context.getObjCInterfaceType(Class);
1969 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1970 ReceiverType = CreateParsedType(T, TSInfo);
1971 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001972 }
1973 }
Richard Smithf9b15102013-08-17 00:46:16 +00001974
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001975 // Fall back: let the parser try to parse it as an instance message.
1976 return ObjCInstanceMessage;
1977}
Steve Naroff9527bbf2009-03-09 21:12:44 +00001978
John McCalldadc5752010-08-24 06:29:42 +00001979ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001980 SourceLocation SuperLoc,
1981 Selector Sel,
1982 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00001983 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001984 SourceLocation RBracLoc,
1985 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001986 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00001987 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00001988 if (!Method) {
1989 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1990 return ExprError();
1991 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001992
Douglas Gregor4fdba132010-04-21 20:01:04 +00001993 ObjCInterfaceDecl *Class = Method->getClassInterface();
1994 if (!Class) {
1995 Diag(SuperLoc, diag::error_no_super_class_message)
1996 << Method->getDeclName();
1997 return ExprError();
1998 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001999
Douglas Gregor4fdba132010-04-21 20:01:04 +00002000 ObjCInterfaceDecl *Super = Class->getSuperClass();
2001 if (!Super) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002002 // The current class does not have a superclass.
Ted Kremenek499897b2011-01-23 17:21:34 +00002003 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
2004 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002005 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002006 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002007
Douglas Gregor4fdba132010-04-21 20:01:04 +00002008 // We are in a method whose class has a superclass, so 'super'
2009 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00002010 if (Method->getSelector() == Sel)
2011 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00002012
Jordan Rose2afd6612012-10-19 16:05:26 +00002013 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00002014 // Since we are in an instance method, this is an instance
2015 // message to the superclass instance.
2016 QualType SuperTy = Context.getObjCInterfaceType(Super);
2017 SuperTy = Context.getObjCObjectPointerType(SuperTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00002018 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2019 Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002020 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002021 }
Douglas Gregor4fdba132010-04-21 20:01:04 +00002022
2023 // Since we are in a class method, this is a class message to
2024 // the superclass.
Craig Topperc3ec1492014-05-26 06:22:03 +00002025 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
Douglas Gregor4fdba132010-04-21 20:01:04 +00002026 Context.getObjCInterfaceType(Super),
Craig Topperc3ec1492014-05-26 06:22:03 +00002027 SuperLoc, Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002028 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002029}
2030
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002031
2032ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2033 bool isSuperReceiver,
2034 SourceLocation Loc,
2035 Selector Sel,
2036 ObjCMethodDecl *Method,
2037 MultiExprArg Args) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002038 TypeSourceInfo *receiverTypeInfo = nullptr;
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002039 if (!ReceiverType.isNull())
2040 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2041
2042 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2043 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2044 Sel, Method, Loc, Loc, Loc, Args,
2045 /*isImplicit=*/true);
2046
2047}
2048
Ted Kremeneke65b0862012-03-06 20:05:56 +00002049static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2050 unsigned DiagID,
2051 bool (*refactor)(const ObjCMessageExpr *,
2052 const NSAPI &, edit::Commit &)) {
2053 SourceLocation MsgLoc = Msg->getExprLoc();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002054 if (S.Diags.isIgnored(DiagID, MsgLoc))
Ted Kremeneke65b0862012-03-06 20:05:56 +00002055 return;
2056
2057 SourceManager &SM = S.SourceMgr;
2058 edit::Commit ECommit(SM, S.LangOpts);
2059 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2060 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2061 << Msg->getSelector() << Msg->getSourceRange();
2062 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2063 if (!ECommit.isCommitable())
2064 return;
2065 for (edit::Commit::edit_iterator
2066 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2067 const edit::Commit::Edit &Edit = *I;
2068 switch (Edit.Kind) {
2069 case edit::Commit::Act_Insert:
2070 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2071 Edit.Text,
2072 Edit.BeforePrev));
2073 break;
2074 case edit::Commit::Act_InsertFromRange:
2075 Builder.AddFixItHint(
2076 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2077 Edit.getInsertFromRange(SM),
2078 Edit.BeforePrev));
2079 break;
2080 case edit::Commit::Act_Remove:
2081 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2082 break;
2083 }
2084 }
2085 }
2086}
2087
2088static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2089 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2090 edit::rewriteObjCRedundantCallWithLiteral);
2091}
2092
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002093/// \brief Build an Objective-C class message expression.
2094///
2095/// This routine takes care of both normal class messages and
2096/// class messages to the superclass.
2097///
2098/// \param ReceiverTypeInfo Type source information that describes the
2099/// receiver of this message. This may be NULL, in which case we are
2100/// sending to the superclass and \p SuperLoc must be a valid source
2101/// location.
2102
2103/// \param ReceiverType The type of the object receiving the
2104/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2105/// type as that refers to. For a superclass send, this is the type of
2106/// the superclass.
2107///
2108/// \param SuperLoc The location of the "super" keyword in a
2109/// superclass message.
2110///
2111/// \param Sel The selector to which the message is being sent.
2112///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002113/// \param Method The method that this class message is invoking, if
2114/// already known.
2115///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002116/// \param LBracLoc The location of the opening square bracket ']'.
2117///
James Dennettffad8b72012-06-22 08:10:18 +00002118/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002119///
James Dennettffad8b72012-06-22 08:10:18 +00002120/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002121ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002122 QualType ReceiverType,
2123 SourceLocation SuperLoc,
2124 Selector Sel,
2125 ObjCMethodDecl *Method,
2126 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002127 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002128 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002129 MultiExprArg ArgsIn,
2130 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002131 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002132 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002133 if (LBracLoc.isInvalid()) {
2134 Diag(Loc, diag::err_missing_open_square_message_send)
2135 << FixItHint::CreateInsertion(Loc, "[");
2136 LBracLoc = Loc;
2137 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002138 SourceLocation SelLoc;
2139 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2140 SelLoc = SelectorLocs.front();
2141 else
2142 SelLoc = Loc;
2143
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002144 if (ReceiverType->isDependentType()) {
2145 // If the receiver type is dependent, we can't type-check anything
2146 // at this point. Build a dependent expression.
2147 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002148 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002149 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002150 return ObjCMessageExpr::Create(
2151 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2152 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2153 isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002154 }
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002155
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002156 // Find the class to which we are sending this message.
Craig Topperc3ec1492014-05-26 06:22:03 +00002157 ObjCInterfaceDecl *Class = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00002158 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2159 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002160 Diag(Loc, diag::err_invalid_receiver_class_message)
2161 << ReceiverType;
2162 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002163 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002164 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002165 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002166 if (!getLangOpts().CPlusPlus)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002167 (void)DiagnoseUseOfDecl(Class, SelLoc);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002168 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002169 if (!Method) {
Douglas Gregor4123a862011-11-14 22:10:01 +00002170 SourceRange TypeRange
2171 = SuperLoc.isValid()? SourceRange(SuperLoc)
2172 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002173 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002174 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002175 ? diag::err_arc_receiver_forward_class
2176 : diag::warn_receiver_forward_class),
2177 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002178 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorb5186b12010-04-22 17:01:48 +00002179 Method = LookupFactoryMethodInGlobalPool(Sel,
2180 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002181 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002182 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2183 << Method->getDeclName();
2184 }
2185 if (!Method)
2186 Method = Class->lookupClassMethod(Sel);
2187
2188 // If we have an implementation in scope, check "private" methods.
2189 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002190 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002191
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002192 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002193 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002194 }
Mike Stump11289f42009-09-09 15:08:12 +00002195
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002196 // Check the argument types and determine the result type.
2197 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002198 ExprValueKind VK = VK_RValue;
2199
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002200 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002201 Expr **Args = ArgsIn.data();
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002202 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2203 Sel, SelectorLocs,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00002204 Method, true,
Douglas Gregor33823722011-06-11 01:09:30 +00002205 SuperLoc.isValid(), LBracLoc, RBracLoc,
2206 ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002207 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002208
Alp Toker314cc812014-01-25 16:55:45 +00002209 if (Method && !Method->getReturnType()->isVoidType() &&
2210 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002211 diag::err_illegal_message_expr_incomplete_type))
2212 return ExprError();
2213
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002214 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002215 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002216 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002217 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002218 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002219 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002220 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002221 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002222 else {
John McCall7decc9e2010-11-18 06:31:45 +00002223 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002224 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002225 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002226 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002227 if (!isImplicit)
2228 checkCocoaAPI(*this, Result);
2229 }
Douglas Gregoraae38d62010-05-22 05:17:18 +00002230 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002231}
2232
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002233// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002234// ArgExprs is optional - if it is present, the number of expressions
2235// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002236ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002237 ParsedType Receiver,
2238 Selector Sel,
2239 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002240 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002241 SourceLocation RBracLoc,
2242 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002243 TypeSourceInfo *ReceiverTypeInfo;
2244 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2245 if (ReceiverType.isNull())
2246 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002247
Mike Stump11289f42009-09-09 15:08:12 +00002248
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002249 if (!ReceiverTypeInfo)
2250 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2251
2252 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002253 /*SuperLoc=*/SourceLocation(), Sel,
2254 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2255 Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002256}
2257
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002258ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2259 QualType ReceiverType,
2260 SourceLocation Loc,
2261 Selector Sel,
2262 ObjCMethodDecl *Method,
2263 MultiExprArg Args) {
2264 return BuildInstanceMessage(Receiver, ReceiverType,
2265 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2266 Sel, Method, Loc, Loc, Loc, Args,
2267 /*isImplicit=*/true);
2268}
2269
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002270/// \brief Build an Objective-C instance message expression.
2271///
2272/// This routine takes care of both normal instance messages and
2273/// instance messages to the superclass instance.
2274///
2275/// \param Receiver The expression that computes the object that will
2276/// receive this message. This may be empty, in which case we are
2277/// sending to the superclass instance and \p SuperLoc must be a valid
2278/// source location.
2279///
2280/// \param ReceiverType The (static) type of the object receiving the
2281/// message. When a \p Receiver expression is provided, this is the
2282/// same type as that expression. For a superclass instance send, this
2283/// is a pointer to the type of the superclass.
2284///
2285/// \param SuperLoc The location of the "super" keyword in a
2286/// superclass instance message.
2287///
2288/// \param Sel The selector to which the message is being sent.
2289///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002290/// \param Method The method that this instance message is invoking, if
2291/// already known.
2292///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002293/// \param LBracLoc The location of the opening square bracket ']'.
2294///
James Dennettffad8b72012-06-22 08:10:18 +00002295/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002296///
James Dennettffad8b72012-06-22 08:10:18 +00002297/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002298ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002299 QualType ReceiverType,
2300 SourceLocation SuperLoc,
2301 Selector Sel,
2302 ObjCMethodDecl *Method,
2303 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002304 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002305 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002306 MultiExprArg ArgsIn,
2307 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002308 // The location of the receiver.
2309 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002310 SourceRange RecRange =
2311 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2312 SourceLocation SelLoc;
2313 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2314 SelLoc = SelectorLocs.front();
2315 else
2316 SelLoc = Loc;
2317
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002318 if (LBracLoc.isInvalid()) {
2319 Diag(Loc, diag::err_missing_open_square_message_send)
2320 << FixItHint::CreateInsertion(Loc, "[");
2321 LBracLoc = Loc;
2322 }
2323
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002324 // If we have a receiver expression, perform appropriate promotions
2325 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002326 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002327 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002328 ExprResult Result;
2329 if (Receiver->getType() == Context.UnknownAnyTy)
2330 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2331 else
2332 Result = CheckPlaceholderExpr(Receiver);
2333 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002334 Receiver = Result.get();
John McCall4124c492011-10-17 18:40:02 +00002335 }
2336
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002337 if (Receiver->isTypeDependent()) {
2338 // If the receiver is type-dependent, we can't type-check anything
2339 // at this point. Build a dependent expression.
2340 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002341 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002342 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002343 return ObjCMessageExpr::Create(
2344 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2345 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2346 RBracLoc, isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002347 }
2348
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002349 // If necessary, apply function/array conversion to the receiver.
2350 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002351 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2352 if (Result.isInvalid())
2353 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002354 Receiver = Result.get();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002355 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002356
2357 // If the receiver is an ObjC pointer, a block pointer, or an
2358 // __attribute__((NSObject)) pointer, we don't need to do any
2359 // special conversion in order to look up a receiver.
2360 if (ReceiverType->isObjCRetainableType()) {
2361 // do nothing
2362 } else if (!getLangOpts().ObjCAutoRefCount &&
2363 !Context.getObjCIdType().isNull() &&
2364 (ReceiverType->isPointerType() ||
2365 ReceiverType->isIntegerType())) {
2366 // Implicitly convert integers and pointers to 'id' but emit a warning.
2367 // But not in ARC.
2368 Diag(Loc, diag::warn_bad_receiver_type)
2369 << ReceiverType
2370 << Receiver->getSourceRange();
2371 if (ReceiverType->isPointerType()) {
2372 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002373 CK_CPointerToObjCPointerCast).get();
John McCall80c93a02013-03-01 09:20:14 +00002374 } else {
2375 // TODO: specialized warning on null receivers?
2376 bool IsNull = Receiver->isNullPointerConstant(Context,
2377 Expr::NPC_ValueDependentIsNull);
2378 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2379 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002380 Kind).get();
John McCall80c93a02013-03-01 09:20:14 +00002381 }
2382 ReceiverType = Receiver->getType();
2383 } else if (getLangOpts().CPlusPlus) {
Douglas Gregor4b60a152013-11-07 22:34:54 +00002384 // The receiver must be a complete type.
2385 if (RequireCompleteType(Loc, Receiver->getType(),
2386 diag::err_incomplete_receiver_type))
2387 return ExprError();
2388
John McCall80c93a02013-03-01 09:20:14 +00002389 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2390 if (result.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002391 Receiver = result.get();
John McCall80c93a02013-03-01 09:20:14 +00002392 ReceiverType = Receiver->getType();
2393 }
2394 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002395 }
2396
John McCall80c93a02013-03-01 09:20:14 +00002397 // There's a somewhat weird interaction here where we assume that we
2398 // won't actually have a method unless we also don't need to do some
2399 // of the more detailed type-checking on the receiver.
2400
Douglas Gregorb5186b12010-04-22 17:01:48 +00002401 if (!Method) {
2402 // Handle messages to id.
Fariborz Jahanian32e59ba2010-08-10 18:10:50 +00002403 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002404 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002405 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2406 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002407 SourceRange(LBracLoc, RBracLoc),
2408 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002409 if (!Method)
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002410 Method = LookupFactoryMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002411 SourceRange(LBracLoc,RBracLoc),
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002412 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002413 } else if (ReceiverType->isObjCClassType() ||
2414 ReceiverType->isObjCQualifiedClassType()) {
2415 // Handle messages to Class.
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002416 // We allow sending a message to a qualified Class ("Class<foo>"), which
2417 // is ok as long as one of the protocols implements the selector (if not, warn).
2418 if (const ObjCObjectPointerType *QClassTy
2419 = ReceiverType->getAsObjCQualifiedClassType()) {
2420 // Search protocols for class methods.
2421 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2422 if (!Method) {
2423 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2424 // warn if instance method found for a Class message.
2425 if (Method) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002426 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002427 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002428 Diag(Method->getLocation(), diag::note_method_declared_at)
2429 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002430 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002431 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002432 } else {
2433 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2434 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2435 // First check the public methods in the class interface.
2436 Method = ClassDecl->lookupClassMethod(Sel);
2437
2438 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002439 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002440 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002441 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002442 return ExprError();
2443 }
2444 if (!Method) {
2445 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002446 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002447 Method = LookupFactoryMethodInGlobalPool(Sel,
2448 SourceRange(LBracLoc, RBracLoc),
2449 true);
2450 if (!Method) {
2451 // If no class (factory) method was found, check if an _instance_
2452 // method of the same name exists in the root class only.
2453 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002454 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002455 true);
2456 if (Method)
2457 if (const ObjCInterfaceDecl *ID =
2458 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2459 if (ID->getSuperClass())
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002460 Diag(SelLoc, diag::warn_root_inst_method_not_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002461 << Sel << SourceRange(LBracLoc, RBracLoc);
2462 }
2463 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002464 }
2465 }
2466 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002467 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002468 ObjCInterfaceDecl *ClassDecl = nullptr;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002469
2470 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2471 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002472 // And as long as message is not deprecated/unavailable (warn if it is).
Douglas Gregorb5186b12010-04-22 17:01:48 +00002473 if (const ObjCObjectPointerType *QIdTy
2474 = ReceiverType->getAsObjCQualifiedIdType()) {
2475 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002476 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2477 if (!Method)
2478 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002479 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002480 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002481 } else if (const ObjCObjectPointerType *OCIType
2482 = ReceiverType->getAsObjCInterfacePointerType()) {
2483 // We allow sending a message to a pointer to an interface (an object).
2484 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002485
Douglas Gregor4123a862011-11-14 22:10:01 +00002486 // Try to complete the type. Under ARC, this is a hard error from which
2487 // we don't try to recover.
Craig Topperc3ec1492014-05-26 06:22:03 +00002488 const ObjCInterfaceDecl *forwardClass = nullptr;
Douglas Gregor4123a862011-11-14 22:10:01 +00002489 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002490 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002491 ? diag::err_arc_receiver_forward_instance
2492 : diag::warn_receiver_forward_instance,
2493 Receiver? Receiver->getSourceRange()
2494 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002495 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002496 return ExprError();
2497
2498 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanianc934de62012-02-03 01:02:44 +00002499 Diag(Receiver ? Receiver->getLocStart()
2500 : SuperLoc, diag::note_receiver_is_id);
Craig Topperc3ec1492014-05-26 06:22:03 +00002501 Method = nullptr;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002502 } else {
2503 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002504 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002505
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002506 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002507 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002508 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2509
Douglas Gregorb5186b12010-04-22 17:01:48 +00002510 if (!Method) {
2511 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002512 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002513
David Blaikiebbafb8a2012-03-11 07:00:24 +00002514 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002515 Diag(SelLoc, diag::err_arc_may_not_respond)
2516 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002517 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002518 return ExprError();
2519 }
2520
Douglas Gregor486b74e2011-09-27 16:10:05 +00002521 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002522 // If we still haven't found a method, look in the global pool. This
2523 // behavior isn't very desirable, however we need it for GCC
2524 // compatibility. FIXME: should we deviate??
2525 if (OCIType->qual_empty()) {
2526 Method = LookupInstanceMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002527 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002528 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002529 Diag(SelLoc, diag::warn_maynot_respond)
2530 << OCIType->getInterfaceDecl()->getIdentifier()
2531 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002532 }
2533 }
2534 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002535 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002536 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002537 } else {
John McCall80c93a02013-03-01 09:20:14 +00002538 // Reject other random receiver types (e.g. structs).
2539 Diag(Loc, diag::err_bad_receiver_type)
2540 << ReceiverType << Receiver->getSourceRange();
2541 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002542 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002543 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002544 }
Mike Stump11289f42009-09-09 15:08:12 +00002545
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002546 FunctionScopeInfo *DIFunctionScopeInfo =
2547 (Method && Method->getMethodFamily() == OMF_init)
Craig Topperc3ec1492014-05-26 06:22:03 +00002548 ? getEnclosingFunction() : nullptr;
2549
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002550 if (DIFunctionScopeInfo &&
2551 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002552 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2553 bool isDesignatedInitChain = false;
2554 if (SuperLoc.isValid()) {
2555 if (const ObjCObjectPointerType *
2556 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2557 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
Argyrios Kyrtzidisd664a342013-12-13 03:48:17 +00002558 // Either we know this is a designated initializer or we
2559 // conservatively assume it because we don't know for sure.
2560 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2561 ID->isDesignatedInitializer(Sel)) {
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002562 isDesignatedInitChain = true;
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002563 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002564 }
2565 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002566 }
2567 }
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002568 if (!isDesignatedInitChain) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002569 const ObjCMethodDecl *InitMethod = nullptr;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002570 bool isDesignated =
2571 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2572 assert(isDesignated && InitMethod);
2573 (void)isDesignated;
2574 Diag(SelLoc, SuperLoc.isValid() ?
2575 diag::warn_objc_designated_init_non_designated_init_call :
2576 diag::warn_objc_designated_init_non_super_designated_init_call);
2577 Diag(InitMethod->getLocation(),
2578 diag::note_objc_designated_init_marked_here);
2579 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002580 }
2581
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002582 if (DIFunctionScopeInfo &&
2583 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002584 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2585 if (SuperLoc.isValid()) {
2586 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2587 } else {
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002588 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002589 }
2590 }
2591
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002592 // Check the message arguments.
2593 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002594 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002595 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002596 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00002597 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2598 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002599 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2600 Sel, SelectorLocs, Method,
Douglas Gregor33823722011-06-11 01:09:30 +00002601 ClassMessage, SuperLoc.isValid(),
John McCall7decc9e2010-11-18 06:31:45 +00002602 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002603 return ExprError();
Alp Toker314cc812014-01-25 16:55:45 +00002604
2605 if (Method && !Method->getReturnType()->isVoidType() &&
2606 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002607 diag::err_illegal_message_expr_incomplete_type))
2608 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00002609
John McCall31168b02011-06-15 23:02:42 +00002610 // In ARC, forbid the user from sending messages to
2611 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002612 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002613 ObjCMethodFamily family =
2614 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2615 switch (family) {
2616 case OMF_init:
2617 if (Method)
2618 checkInitMethod(Method, ReceiverType);
2619
2620 case OMF_None:
2621 case OMF_alloc:
2622 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00002623 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002624 case OMF_mutableCopy:
2625 case OMF_new:
2626 case OMF_self:
2627 break;
2628
2629 case OMF_dealloc:
2630 case OMF_retain:
2631 case OMF_release:
2632 case OMF_autorelease:
2633 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002634 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2635 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00002636 break;
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002637
2638 case OMF_performSelector:
2639 if (Method && NumArgs >= 1) {
2640 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2641 Selector ArgSel = SelExp->getSelector();
2642 ObjCMethodDecl *SelMethod =
2643 LookupInstanceMethodInGlobalPool(ArgSel,
2644 SelExp->getSourceRange());
2645 if (!SelMethod)
2646 SelMethod =
2647 LookupFactoryMethodInGlobalPool(ArgSel,
2648 SelExp->getSourceRange());
2649 if (SelMethod) {
2650 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2651 switch (SelFamily) {
2652 case OMF_alloc:
2653 case OMF_copy:
2654 case OMF_mutableCopy:
2655 case OMF_new:
2656 case OMF_self:
2657 case OMF_init:
2658 // Issue error, unless ns_returns_not_retained.
2659 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2660 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002661 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002662 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002663 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2664 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002665 }
2666 break;
2667 default:
2668 // +0 call. OK. unless ns_returns_retained.
2669 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2670 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002671 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002672 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002673 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2674 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002675 }
2676 break;
2677 }
2678 }
2679 } else {
2680 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002681 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002682 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2683 }
2684 }
2685 break;
John McCall31168b02011-06-15 23:02:42 +00002686 }
2687 }
2688
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002689 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00002690 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002691 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002692 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002693 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002694 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002695 makeArrayRef(Args, NumArgs), RBracLoc,
2696 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002697 else {
John McCall7decc9e2010-11-18 06:31:45 +00002698 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002699 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002700 makeArrayRef(Args, NumArgs), RBracLoc,
2701 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002702 if (!isImplicit)
2703 checkCocoaAPI(*this, Result);
2704 }
John McCall31168b02011-06-15 23:02:42 +00002705
David Blaikiebbafb8a2012-03-11 07:00:24 +00002706 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahanian9277ff42014-06-17 23:35:13 +00002707 // Do not warn about IBOutlet weak property receivers being set to null
2708 // as this cannot asynchronously happen.
2709 bool WarnWeakReceiver = true;
2710 if (isImplicit && Method)
2711 if (const ObjCPropertyDecl *PropertyDecl = Method->findPropertyDecl())
2712 WarnWeakReceiver = !PropertyDecl->hasAttr<IBOutletAttr>();
2713 if (WarnWeakReceiver)
2714 DiagnoseARCUseOfWeakReceiver(*this, Receiver);
Fariborz Jahanian6bd22262012-04-04 20:05:25 +00002715
John McCall31168b02011-06-15 23:02:42 +00002716 // In ARC, annotate delegate init calls.
2717 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00002718 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00002719 // Only consider init calls *directly* in init implementations,
2720 // not within blocks.
2721 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2722 if (method && method->getMethodFamily() == OMF_init) {
2723 // The implicit assignment to self means we also don't want to
2724 // consume the result.
2725 Result->setDelegateInitCall(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002726 return Result;
John McCall31168b02011-06-15 23:02:42 +00002727 }
2728 }
2729
2730 // In ARC, check for message sends which are likely to introduce
2731 // retain cycles.
2732 checkRetainCycles(Result);
Jordan Rose22487652012-10-11 16:06:21 +00002733
2734 if (!isImplicit && Method) {
2735 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2736 bool IsWeak =
2737 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2738 if (!IsWeak && Sel.isUnarySelector())
2739 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002740 if (IsWeak &&
2741 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
2742 getCurFunction()->recordUseOfWeak(Result, Prop);
Jordan Rose22487652012-10-11 16:06:21 +00002743 }
2744 }
John McCall31168b02011-06-15 23:02:42 +00002745 }
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00002746
Douglas Gregoraae38d62010-05-22 05:17:18 +00002747 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002748}
2749
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002750static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2751 if (ObjCSelectorExpr *OSE =
2752 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2753 Selector Sel = OSE->getSelector();
2754 SourceLocation Loc = OSE->getAtLoc();
2755 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
2756 = S.ReferencedSelectors.find(Sel);
2757 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
2758 S.ReferencedSelectors.erase(Pos);
2759 }
2760}
2761
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002762// ActOnInstanceMessage - used for both unary and keyword messages.
2763// ArgExprs is optional - if it is present, the number of expressions
2764// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002765ExprResult Sema::ActOnInstanceMessage(Scope *S,
2766 Expr *Receiver,
2767 Selector Sel,
2768 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002769 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00002770 SourceLocation RBracLoc,
2771 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002772 if (!Receiver)
2773 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002774
2775 // A ParenListExpr can show up while doing error recovery with invalid code.
2776 if (isa<ParenListExpr>(Receiver)) {
2777 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
2778 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002779 Receiver = Result.get();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002780 }
Fariborz Jahanian17748062013-01-22 19:05:17 +00002781
2782 if (RespondsToSelectorSel.isNull()) {
2783 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
2784 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
2785 }
2786 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002787 RemoveSelectorFromWarningCache(*this, Args[0]);
Craig Topperc3ec1492014-05-26 06:22:03 +00002788
John McCallb268a282010-08-23 23:25:46 +00002789 return BuildInstanceMessage(Receiver, Receiver->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002790 /*SuperLoc=*/SourceLocation(), Sel,
2791 /*Method=*/nullptr, LBracLoc, SelectorLocs,
2792 RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002793}
Chris Lattner2a3569b2008-04-07 05:30:13 +00002794
John McCall31168b02011-06-15 23:02:42 +00002795enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00002796 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00002797 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00002798
2799 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00002800 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00002801
2802 /// id*, id***, void (^*)(),
2803 ACTC_indirectRetainable,
2804
2805 /// void* might be a normal C type, or it might a CF type.
2806 ACTC_voidPtr,
2807
2808 /// struct A*
2809 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00002810};
John McCalle4fe2452011-10-01 01:01:08 +00002811static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2812 return (ACTC == ACTC_retainable ||
2813 ACTC == ACTC_coreFoundation ||
2814 ACTC == ACTC_voidPtr);
2815}
2816static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2817 return ACTC == ACTC_none ||
2818 ACTC == ACTC_voidPtr ||
2819 ACTC == ACTC_coreFoundation;
2820}
2821
John McCall31168b02011-06-15 23:02:42 +00002822static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00002823 bool isIndirect = false;
John McCall31168b02011-06-15 23:02:42 +00002824
2825 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00002826 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00002827 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002828 isIndirect = true;
2829 }
John McCall31168b02011-06-15 23:02:42 +00002830
2831 // Drill through pointers and arrays recursively.
2832 while (true) {
2833 if (const PointerType *ptr = type->getAs<PointerType>()) {
2834 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002835
2836 // The first level of pointer may be the innermost pointer on a CF type.
2837 if (!isIndirect) {
2838 if (type->isVoidType()) return ACTC_voidPtr;
2839 if (type->isRecordType()) return ACTC_coreFoundation;
2840 }
John McCall31168b02011-06-15 23:02:42 +00002841 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2842 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2843 } else {
2844 break;
2845 }
John McCalle4fe2452011-10-01 01:01:08 +00002846 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00002847 }
2848
John McCalle4fe2452011-10-01 01:01:08 +00002849 if (isIndirect) {
2850 if (type->isObjCARCBridgableType())
2851 return ACTC_indirectRetainable;
2852 return ACTC_none;
2853 }
2854
2855 if (type->isObjCARCBridgableType())
2856 return ACTC_retainable;
2857
2858 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00002859}
2860
2861namespace {
John McCalle4fe2452011-10-01 01:01:08 +00002862 /// A result from the cast checker.
2863 enum ACCResult {
2864 /// Cannot be casted.
2865 ACC_invalid,
2866
2867 /// Can be safely retained or not retained.
2868 ACC_bottom,
2869
2870 /// Can be casted at +0.
2871 ACC_plusZero,
2872
2873 /// Can be casted at +1.
2874 ACC_plusOne
2875 };
2876 ACCResult merge(ACCResult left, ACCResult right) {
2877 if (left == right) return left;
2878 if (left == ACC_bottom) return right;
2879 if (right == ACC_bottom) return left;
2880 return ACC_invalid;
2881 }
2882
2883 /// A checker which white-lists certain expressions whose conversion
2884 /// to or from retainable type would otherwise be forbidden in ARC.
2885 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2886 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2887
John McCall31168b02011-06-15 23:02:42 +00002888 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00002889 ARCConversionTypeClass SourceClass;
2890 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002891 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00002892
2893 static bool isCFType(QualType type) {
2894 // Someday this can use ns_bridged. For now, it has to do this.
2895 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00002896 }
John McCalle4fe2452011-10-01 01:01:08 +00002897
2898 public:
2899 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002900 ARCConversionTypeClass target, bool diagnose)
2901 : Context(Context), SourceClass(source), TargetClass(target),
2902 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00002903
2904 using super::Visit;
2905 ACCResult Visit(Expr *e) {
2906 return super::Visit(e->IgnoreParens());
2907 }
2908
2909 ACCResult VisitStmt(Stmt *s) {
2910 return ACC_invalid;
2911 }
2912
2913 /// Null pointer constants can be casted however you please.
2914 ACCResult VisitExpr(Expr *e) {
2915 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2916 return ACC_bottom;
2917 return ACC_invalid;
2918 }
2919
2920 /// Objective-C string literals can be safely casted.
2921 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2922 // If we're casting to any retainable type, go ahead. Global
2923 // strings are immune to retains, so this is bottom.
2924 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2925
2926 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002927 }
2928
John McCalle4fe2452011-10-01 01:01:08 +00002929 /// Look through certain implicit and explicit casts.
2930 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002931 switch (e->getCastKind()) {
2932 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00002933 return ACC_bottom;
2934
John McCall31168b02011-06-15 23:02:42 +00002935 case CK_NoOp:
2936 case CK_LValueToRValue:
2937 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002938 case CK_CPointerToObjCPointerCast:
2939 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002940 case CK_AnyPointerToBlockPointerCast:
2941 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00002942
John McCall31168b02011-06-15 23:02:42 +00002943 default:
John McCalle4fe2452011-10-01 01:01:08 +00002944 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002945 }
2946 }
John McCalle4fe2452011-10-01 01:01:08 +00002947
2948 /// Look through unary extension.
2949 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002950 return Visit(e->getSubExpr());
2951 }
John McCalle4fe2452011-10-01 01:01:08 +00002952
2953 /// Ignore the LHS of a comma operator.
2954 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002955 return Visit(e->getRHS());
2956 }
John McCalle4fe2452011-10-01 01:01:08 +00002957
2958 /// Conditional operators are okay if both sides are okay.
2959 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2960 ACCResult left = Visit(e->getTrueExpr());
2961 if (left == ACC_invalid) return ACC_invalid;
2962 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00002963 }
John McCalle4fe2452011-10-01 01:01:08 +00002964
John McCallfe96e0b2011-11-06 09:01:30 +00002965 /// Look through pseudo-objects.
2966 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2967 // If we're getting here, we should always have a result.
2968 return Visit(e->getResultExpr());
2969 }
2970
John McCalle4fe2452011-10-01 01:01:08 +00002971 /// Statement expressions are okay if their result expression is okay.
2972 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002973 return Visit(e->getSubStmt()->body_back());
2974 }
John McCall31168b02011-06-15 23:02:42 +00002975
John McCalle4fe2452011-10-01 01:01:08 +00002976 /// Some declaration references are okay.
2977 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2978 // References to global constants from system headers are okay.
2979 // These are things like 'kCFStringTransformToLatin'. They are
2980 // can also be assumed to be immune to retains.
2981 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2982 if (isAnyRetainable(TargetClass) &&
2983 isAnyRetainable(SourceClass) &&
2984 var &&
2985 var->getStorageClass() == SC_Extern &&
2986 var->getType().isConstQualified() &&
2987 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2988 return ACC_bottom;
2989 }
2990
2991 // Nothing else.
2992 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00002993 }
John McCalle4fe2452011-10-01 01:01:08 +00002994
2995 /// Some calls are okay.
2996 ACCResult VisitCallExpr(CallExpr *e) {
2997 if (FunctionDecl *fn = e->getDirectCallee())
2998 if (ACCResult result = checkCallToFunction(fn))
2999 return result;
3000
3001 return super::VisitCallExpr(e);
3002 }
3003
3004 ACCResult checkCallToFunction(FunctionDecl *fn) {
3005 // Require a CF*Ref return type.
Alp Toker314cc812014-01-25 16:55:45 +00003006 if (!isCFType(fn->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003007 return ACC_invalid;
3008
3009 if (!isAnyRetainable(TargetClass))
3010 return ACC_invalid;
3011
3012 // Honor an explicit 'not retained' attribute.
3013 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3014 return ACC_plusZero;
3015
3016 // Honor an explicit 'retained' attribute, except that for
3017 // now we're not going to permit implicit handling of +1 results,
3018 // because it's a bit frightening.
3019 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003020 return Diagnose ? ACC_plusOne
3021 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003022
3023 // Recognize this specific builtin function, which is used by CFSTR.
3024 unsigned builtinID = fn->getBuiltinID();
3025 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3026 return ACC_bottom;
3027
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003028 // Otherwise, don't do anything implicit with an unaudited function.
3029 if (!fn->hasAttr<CFAuditedTransferAttr>())
3030 return ACC_invalid;
3031
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003032 // Otherwise, it's +0 unless it follows the create convention.
3033 if (ento::coreFoundation::followsCreateRule(fn))
3034 return Diagnose ? ACC_plusOne
3035 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003036
John McCalle4fe2452011-10-01 01:01:08 +00003037 return ACC_plusZero;
3038 }
3039
3040 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3041 return checkCallToMethod(e->getMethodDecl());
3042 }
3043
3044 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3045 ObjCMethodDecl *method;
3046 if (e->isExplicitProperty())
3047 method = e->getExplicitProperty()->getGetterMethodDecl();
3048 else
3049 method = e->getImplicitPropertyGetter();
3050 return checkCallToMethod(method);
3051 }
3052
3053 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3054 if (!method) return ACC_invalid;
3055
3056 // Check for message sends to functions returning CF types. We
3057 // just obey the Cocoa conventions with these, even though the
3058 // return type is CF.
Alp Toker314cc812014-01-25 16:55:45 +00003059 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003060 return ACC_invalid;
3061
3062 // If the method is explicitly marked not-retained, it's +0.
3063 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3064 return ACC_plusZero;
3065
3066 // If the method is explicitly marked as returning retained, or its
3067 // selector follows a +1 Cocoa convention, treat it as +1.
3068 if (method->hasAttr<CFReturnsRetainedAttr>())
3069 return ACC_plusOne;
3070
3071 switch (method->getSelector().getMethodFamily()) {
3072 case OMF_alloc:
3073 case OMF_copy:
3074 case OMF_mutableCopy:
3075 case OMF_new:
3076 return ACC_plusOne;
3077
3078 default:
3079 // Otherwise, treat it as +0.
3080 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00003081 }
3082 }
John McCalle4fe2452011-10-01 01:01:08 +00003083 };
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00003084}
3085
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003086bool Sema::isKnownName(StringRef name) {
3087 if (name.empty())
3088 return false;
3089 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003090 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003091 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003092}
3093
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003094static void addFixitForObjCARCConversion(Sema &S,
3095 DiagnosticBuilder &DiagB,
3096 Sema::CheckedConversionKind CCK,
3097 SourceLocation afterLParen,
3098 QualType castType,
3099 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003100 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003101 const char *bridgeKeyword,
3102 const char *CFBridgeName) {
3103 // We handle C-style and implicit casts here.
3104 switch (CCK) {
3105 case Sema::CCK_ImplicitConversion:
3106 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003107 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003108 break;
3109 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003110 return;
3111 }
3112
3113 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003114 if (CCK == Sema::CCK_OtherCast) {
3115 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3116 SourceRange range(NCE->getOperatorLoc(),
3117 NCE->getAngleBrackets().getEnd());
3118 SmallString<32> BridgeCall;
3119
3120 SourceManager &SM = S.getSourceManager();
3121 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3122 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3123 BridgeCall += ' ';
3124
3125 BridgeCall += CFBridgeName;
3126 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3127 }
3128 return;
3129 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003130 Expr *castedE = castExpr;
3131 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3132 castedE = CCE->getSubExpr();
3133 castedE = castedE->IgnoreImpCasts();
3134 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00003135
3136 SmallString<32> BridgeCall;
3137
3138 SourceManager &SM = S.getSourceManager();
3139 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3140 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3141 BridgeCall += ' ';
3142
3143 BridgeCall += CFBridgeName;
3144
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003145 if (isa<ParenExpr>(castedE)) {
3146 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003147 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003148 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00003149 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003150 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003151 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003152 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3153 S.PP.getLocForEndOfToken(range.getEnd()),
3154 ")"));
3155 }
3156 return;
3157 }
3158
3159 if (CCK == Sema::CCK_CStyleCast) {
3160 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003161 } else if (CCK == Sema::CCK_OtherCast) {
3162 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3163 std::string castCode = "(";
3164 castCode += bridgeKeyword;
3165 castCode += castType.getAsString();
3166 castCode += ")";
3167 SourceRange Range(NCE->getOperatorLoc(),
3168 NCE->getAngleBrackets().getEnd());
3169 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3170 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003171 } else {
3172 std::string castCode = "(";
3173 castCode += bridgeKeyword;
3174 castCode += castType.getAsString();
3175 castCode += ")";
3176 Expr *castedE = castExpr->IgnoreImpCasts();
3177 SourceRange range = castedE->getSourceRange();
3178 if (isa<ParenExpr>(castedE)) {
3179 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3180 castCode));
3181 } else {
3182 castCode += "(";
3183 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3184 castCode));
3185 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3186 S.PP.getLocForEndOfToken(range.getEnd()),
3187 ")"));
3188 }
3189 }
3190}
3191
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003192template <typename T>
3193static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3194 TypedefNameDecl *TDNDecl = TD->getDecl();
3195 QualType QT = TDNDecl->getUnderlyingType();
3196 if (QT->isPointerType()) {
3197 QT = QT->getPointeeType();
3198 if (const RecordType *RT = QT->getAs<RecordType>())
Fariborz Jahanian9af6a782014-06-11 19:10:46 +00003199 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
Aaron Ballman2084f8f2013-12-19 13:20:36 +00003200 return RD->getAttr<T>();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003201 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003202 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003203}
3204
3205static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3206 TypedefNameDecl *&TDNDecl) {
3207 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3208 TDNDecl = TD->getDecl();
3209 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3210 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3211 return ObjCBAttr;
3212 T = TDNDecl->getUnderlyingType();
3213 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003214 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003215}
3216
John McCall4124c492011-10-17 18:40:02 +00003217static void
3218diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3219 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003220 Expr *castExpr, Expr *realCast,
3221 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003222 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003223 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003224 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00003225
John McCall4124c492011-10-17 18:40:02 +00003226 if (S.makeUnavailableInSystemHeader(loc,
John McCalle4fe2452011-10-01 01:01:08 +00003227 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCall31168b02011-06-15 23:02:42 +00003228 return;
John McCall4124c492011-10-17 18:40:02 +00003229
3230 QualType castExprType = castExpr->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003231 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003232 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3233 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3234 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
Fariborz Jahanian1ad83a32014-06-18 23:22:38 +00003235 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003236 return;
John McCall31168b02011-06-15 23:02:42 +00003237
John McCall640767f2011-06-17 06:50:50 +00003238 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003239 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003240 case ACTC_none:
3241 case ACTC_coreFoundation:
3242 case ACTC_voidPtr:
3243 srcKind = (castExprType->isPointerType() ? 1 : 0);
3244 break;
3245 case ACTC_retainable:
3246 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3247 break;
3248 case ACTC_indirectRetainable:
3249 srcKind = 4;
3250 break;
John McCall31168b02011-06-15 23:02:42 +00003251 }
3252
John McCall4124c492011-10-17 18:40:02 +00003253 // Check whether this could be fixed with a bridge cast.
3254 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3255 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003256
John McCall4124c492011-10-17 18:40:02 +00003257 // Bridge from an ARC type to a CF type.
3258 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003259
John McCall4124c492011-10-17 18:40:02 +00003260 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3261 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3262 << 2 // of C pointer type
3263 << castExprType
3264 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3265 << castType
3266 << castRange
3267 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003268 bool br = S.isKnownName("CFBridgingRelease");
Jordan Rose4502b532012-07-31 01:07:43 +00003269 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003270 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003271 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003272 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003273 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003274 DiagnosticBuilder DiagB =
3275 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3276 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Craig Topperc3ec1492014-05-26 06:22:03 +00003277
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003278 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003279 castType, castExpr, realCast, "__bridge ",
3280 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003281 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003282 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003283 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003284 DiagnosticBuilder DiagB =
3285 (CCK == Sema::CCK_OtherCast && !br) ?
3286 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3287 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3288 diag::note_arc_bridge_transfer)
3289 << castExprType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003290
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003291 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003292 castType, castExpr, realCast, "__bridge_transfer ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003293 br ? "CFBridgingRelease" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003294 }
John McCall4124c492011-10-17 18:40:02 +00003295
3296 return;
3297 }
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003298
John McCall4124c492011-10-17 18:40:02 +00003299 // Bridge from a CF type to an ARC type.
3300 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003301 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003302 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3303 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3304 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3305 << castExprType
3306 << 2 // to C pointer type
3307 << castType
3308 << castRange
3309 << castExpr->getSourceRange();
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003310 ACCResult CreateRule =
3311 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003312 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003313 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003314 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003315 DiagnosticBuilder DiagB =
3316 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3317 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003318 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003319 castType, castExpr, realCast, "__bridge ",
3320 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003321 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003322 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003323 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003324 DiagnosticBuilder DiagB =
3325 (CCK == Sema::CCK_OtherCast && !br) ?
3326 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3327 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3328 diag::note_arc_bridge_retained)
3329 << castType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003330
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003331 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003332 castType, castExpr, realCast, "__bridge_retained ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003333 br ? "CFBridgingRetain" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003334 }
John McCall4124c492011-10-17 18:40:02 +00003335
3336 return;
John McCall31168b02011-06-15 23:02:42 +00003337 }
3338
John McCall4124c492011-10-17 18:40:02 +00003339 S.Diag(loc, diag::err_arc_mismatched_cast)
3340 << (CCK != Sema::CCK_ImplicitConversion)
3341 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003342 << castRange << castExpr->getSourceRange();
3343}
3344
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003345template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003346static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3347 bool &HadTheAttribute, bool warn) {
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003348 QualType T = castExpr->getType();
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003349 HadTheAttribute = false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003350 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3351 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003352 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003353 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003354 HadTheAttribute = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003355 NamedDecl *Target = nullptr;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003356 // Check for an existing type with this name.
3357 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3358 Sema::LookupOrdinaryName);
3359 if (S.LookupName(R, S.TUScope)) {
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003360 Target = R.getFoundDecl();
3361 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3362 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3363 if (const ObjCObjectPointerType *InterfacePointerType =
3364 castType->getAsObjCInterfacePointerType()) {
3365 ObjCInterfaceDecl *CastClass
3366 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003367 if ((CastClass == ExprClass) ||
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003368 (CastClass && ExprClass->isSuperClassOf(CastClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003369 return true;
3370 if (warn)
3371 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3372 << T << Target->getName() << castType->getPointeeType();
3373 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003374 } else if (castType->isObjCIdType() ||
3375 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3376 castType, ExprClass)))
3377 // ok to cast to 'id'.
3378 // casting to id<p-list> is ok if bridge type adopts all of
3379 // p-list protocols.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003380 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003381 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003382 if (warn) {
3383 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3384 << T << Target->getName() << castType;
3385 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3386 S.Diag(Target->getLocStart(), diag::note_declared_at);
3387 }
3388 return false;
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003389 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003390 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003391 }
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003392 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
Aaron Ballmanc0550742014-01-03 02:07:43 +00003393 << castExpr->getType() << Parm;
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003394 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3395 if (Target)
3396 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003397 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003398 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003399 return false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003400 }
3401 T = TDNDecl->getUnderlyingType();
3402 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003403 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003404}
3405
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003406template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003407static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3408 bool &HadTheAttribute, bool warn) {
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003409 QualType T = castType;
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003410 HadTheAttribute = false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003411 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3412 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003413 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003414 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003415 HadTheAttribute = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003416 NamedDecl *Target = nullptr;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003417 // Check for an existing type with this name.
3418 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3419 Sema::LookupOrdinaryName);
3420 if (S.LookupName(R, S.TUScope)) {
3421 Target = R.getFoundDecl();
3422 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3423 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3424 if (const ObjCObjectPointerType *InterfacePointerType =
3425 castExpr->getType()->getAsObjCInterfacePointerType()) {
3426 ObjCInterfaceDecl *ExprClass
3427 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003428 if ((CastClass == ExprClass) ||
3429 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003430 return true;
3431 if (warn) {
3432 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3433 << castExpr->getType()->getPointeeType() << T;
3434 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3435 }
3436 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003437 } else if (castExpr->getType()->isObjCIdType() ||
3438 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3439 castExpr->getType(), CastClass)))
3440 // ok to cast an 'id' expression to a CFtype.
3441 // ok to cast an 'id<plist>' expression to CFtype provided plist
3442 // adopts all of CFtype's ObjetiveC's class plist.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003443 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003444 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003445 if (warn) {
3446 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3447 << castExpr->getType() << castType;
3448 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3449 S.Diag(Target->getLocStart(), diag::note_declared_at);
3450 }
3451 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003452 }
3453 }
3454 }
3455 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3456 << castExpr->getType() << castType;
3457 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3458 if (Target)
3459 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003460 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003461 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003462 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003463 }
3464 T = TDNDecl->getUnderlyingType();
3465 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003466 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003467}
3468
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003469void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003470 if (!getLangOpts().ObjC1)
3471 return;
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003472 // warn in presence of __bridge casting to or from a toll free bridge cast.
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003473 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3474 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003475 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003476 bool HasObjCBridgeAttr;
3477 bool ObjCBridgeAttrWillNotWarn =
3478 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3479 false);
3480 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3481 return;
3482 bool HasObjCBridgeMutableAttr;
3483 bool ObjCBridgeMutableAttrWillNotWarn =
3484 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3485 HasObjCBridgeMutableAttr, false);
3486 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3487 return;
3488
3489 if (HasObjCBridgeAttr)
3490 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3491 true);
3492 else if (HasObjCBridgeMutableAttr)
3493 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3494 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003495 }
3496 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003497 bool HasObjCBridgeAttr;
3498 bool ObjCBridgeAttrWillNotWarn =
3499 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3500 false);
3501 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3502 return;
3503 bool HasObjCBridgeMutableAttr;
3504 bool ObjCBridgeMutableAttrWillNotWarn =
3505 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3506 HasObjCBridgeMutableAttr, false);
3507 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3508 return;
3509
3510 if (HasObjCBridgeAttr)
3511 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3512 true);
3513 else if (HasObjCBridgeMutableAttr)
3514 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3515 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003516 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003517}
3518
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003519void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3520 QualType SrcType = castExpr->getType();
3521 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3522 if (PRE->isExplicitProperty()) {
3523 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3524 SrcType = PDecl->getType();
3525 }
3526 else if (PRE->isImplicitProperty()) {
3527 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3528 SrcType = Getter->getReturnType();
3529
3530 }
3531 }
3532
3533 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3534 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3535 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3536 return;
3537 CheckObjCBridgeRelatedConversions(castExpr->getLocStart(),
3538 castType, SrcType, castExpr);
3539 return;
3540}
3541
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00003542bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3543 CastKind &Kind) {
3544 if (!getLangOpts().ObjC1)
3545 return false;
3546 ARCConversionTypeClass exprACTC =
3547 classifyTypeForARCConversion(castExpr->getType());
3548 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3549 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3550 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3551 CheckTollFreeBridgeCast(castType, castExpr);
3552 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3553 : CK_CPointerToObjCPointerCast;
3554 return true;
3555 }
3556 return false;
3557}
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003558
3559bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3560 QualType DestType, QualType SrcType,
3561 ObjCInterfaceDecl *&RelatedClass,
3562 ObjCMethodDecl *&ClassMethod,
3563 ObjCMethodDecl *&InstanceMethod,
3564 TypedefNameDecl *&TDNDecl,
3565 bool CfToNs) {
3566 QualType T = CfToNs ? SrcType : DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003567 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3568 if (!ObjCBAttr)
3569 return false;
3570
3571 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3572 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3573 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3574 if (!RCId)
3575 return false;
Craig Topperc3ec1492014-05-26 06:22:03 +00003576 NamedDecl *Target = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003577 // Check for an existing type with this name.
3578 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3579 Sema::LookupOrdinaryName);
3580 if (!LookupName(R, TUScope)) {
3581 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003582 << SrcType << DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003583 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3584 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003585 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003586 Target = R.getFoundDecl();
3587 if (Target && isa<ObjCInterfaceDecl>(Target))
3588 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3589 else {
3590 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3591 << SrcType << DestType;
3592 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3593 if (Target)
3594 Diag(Target->getLocStart(), diag::note_declared_at);
3595 return false;
3596 }
3597
3598 // Check for an existing class method with the given selector name.
3599 if (CfToNs && CMId) {
3600 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3601 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3602 if (!ClassMethod) {
3603 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003604 << SrcType << DestType << Sel << false;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003605 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3606 return false;
3607 }
3608 }
3609
3610 // Check for an existing instance method with the given selector name.
3611 if (!CfToNs && IMId) {
3612 Selector Sel = Context.Selectors.getNullarySelector(IMId);
3613 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3614 if (!InstanceMethod) {
3615 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003616 << SrcType << DestType << Sel << true;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003617 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3618 return false;
3619 }
3620 }
3621 return true;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003622}
3623
3624bool
3625Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003626 QualType DestType, QualType SrcType,
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003627 Expr *&SrcExpr) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003628 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3629 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3630 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3631 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3632 if (!CfToNs && !NsToCf)
3633 return false;
3634
3635 ObjCInterfaceDecl *RelatedClass;
Craig Topperc3ec1492014-05-26 06:22:03 +00003636 ObjCMethodDecl *ClassMethod = nullptr;
3637 ObjCMethodDecl *InstanceMethod = nullptr;
3638 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003639 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
3640 ClassMethod, InstanceMethod, TDNDecl, CfToNs))
3641 return false;
3642
3643 if (CfToNs) {
3644 // Implicit conversion from CF to ObjC object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003645 if (ClassMethod) {
3646 std::string ExpressionString = "[";
3647 ExpressionString += RelatedClass->getNameAsString();
3648 ExpressionString += " ";
3649 ExpressionString += ClassMethod->getSelector().getAsString();
3650 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3651 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003652 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003653 << SrcType << DestType << ClassMethod->getSelector() << false
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003654 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3655 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003656 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3657 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3658
3659 QualType receiverType =
3660 Context.getObjCInterfaceType(RelatedClass);
3661 // Argument.
3662 Expr *args[] = { SrcExpr };
3663 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
3664 ClassMethod->getLocation(),
3665 ClassMethod->getSelector(), ClassMethod,
3666 MultiExprArg(args, 1));
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003667 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003668 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003669 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003670 }
3671 else {
3672 // Implicit conversion from ObjC type to CF object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003673 if (InstanceMethod) {
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003674 std::string ExpressionString;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003675 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003676 if (InstanceMethod->isPropertyAccessor())
3677 if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
3678 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
3679 ExpressionString = ".";
3680 ExpressionString += PDecl->getNameAsString();
3681 Diag(Loc, diag::err_objc_bridged_related_known_method)
3682 << SrcType << DestType << InstanceMethod->getSelector() << true
3683 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3684 }
3685 if (ExpressionString.empty()) {
3686 // Provide a fixit: [ObjectExpr InstanceMethod]
3687 ExpressionString = " ";
3688 ExpressionString += InstanceMethod->getSelector().getAsString();
3689 ExpressionString += "]";
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003690
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003691 Diag(Loc, diag::err_objc_bridged_related_known_method)
3692 << SrcType << DestType << InstanceMethod->getSelector() << true
3693 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3694 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3695 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003696 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3697 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3698
3699 ExprResult msg =
3700 BuildInstanceMessageImplicit(SrcExpr, SrcType,
3701 InstanceMethod->getLocation(),
3702 InstanceMethod->getSelector(),
3703 InstanceMethod, None);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003704 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003705 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003706 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003707 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003708 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003709}
3710
John McCall4124c492011-10-17 18:40:02 +00003711Sema::ARCConversionResult
3712Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003713 Expr *&castExpr, CheckedConversionKind CCK,
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00003714 bool DiagnoseCFAudited,
3715 BinaryOperatorKind Opc) {
John McCall4124c492011-10-17 18:40:02 +00003716 QualType castExprType = castExpr->getType();
3717
3718 // For the purposes of the classification, we assume reference types
3719 // will bind to temporaries.
3720 QualType effCastType = castType;
3721 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3722 effCastType = ref->getPointeeType();
3723
3724 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3725 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003726 if (exprACTC == castACTC) {
3727 // check for viablity and report error if casting an rvalue to a
3728 // life-time qualifier.
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003729 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003730 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003731 (castType != castExprType)) {
3732 const Type *DT = castType.getTypePtr();
3733 QualType QDT = castType;
3734 // We desugar some types but not others. We ignore those
3735 // that cannot happen in a cast; i.e. auto, and those which
3736 // should not be de-sugared; i.e typedef.
3737 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3738 QDT = PT->desugar();
3739 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3740 QDT = TP->desugar();
3741 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3742 QDT = AT->desugar();
3743 if (QDT != castType &&
3744 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3745 SourceLocation loc =
3746 (castRange.isValid() ? castRange.getBegin()
3747 : castExpr->getExprLoc());
3748 Diag(loc, diag::err_arc_nolifetime_behavior);
3749 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003750 }
3751 return ACR_okay;
3752 }
3753
John McCall4124c492011-10-17 18:40:02 +00003754 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
3755
3756 // Allow all of these types to be cast to integer types (but not
3757 // vice-versa).
3758 if (castACTC == ACTC_none && castType->isIntegralType(Context))
3759 return ACR_okay;
3760
3761 // Allow casts between pointers to lifetime types (e.g., __strong id*)
3762 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
3763 // must be explicit.
3764 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
3765 return ACR_okay;
3766 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
3767 CCK != CCK_ImplicitConversion)
3768 return ACR_okay;
3769
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003770 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00003771 // For invalid casts, fall through.
3772 case ACC_invalid:
3773 break;
3774
3775 // Do nothing for both bottom and +0.
3776 case ACC_bottom:
3777 case ACC_plusZero:
3778 return ACR_okay;
3779
3780 // If the result is +1, consume it here.
3781 case ACC_plusOne:
3782 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3783 CK_ARCConsumeObject, castExpr,
Craig Topperc3ec1492014-05-26 06:22:03 +00003784 nullptr, VK_RValue);
John McCall4124c492011-10-17 18:40:02 +00003785 ExprNeedsCleanups = true;
3786 return ACR_okay;
3787 }
3788
3789 // If this is a non-implicit cast from id or block type to a
3790 // CoreFoundation type, delay complaining in case the cast is used
3791 // in an acceptable context.
3792 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3793 CCK != CCK_ImplicitConversion)
3794 return ACR_unbridged;
3795
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003796 // Do not issue bridge cast" diagnostic when implicit casting a cstring
3797 // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
3798 // suitable fix-it.
Fariborz Jahanian283bf892013-12-18 21:04:43 +00003799 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
3800 ConversionToObjCStringLiteralCheck(castType, castExpr))
3801 return ACR_okay;
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003802
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003803 // Do not issue "bridge cast" diagnostic when implicit casting
3804 // a retainable object to a CF type parameter belonging to an audited
3805 // CF API function. Let caller issue a normal type mismatched diagnostic
3806 // instead.
3807 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
3808 castACTC != ACTC_coreFoundation)
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00003809 if (!(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
3810 (Opc == BO_NE || Opc == BO_EQ)))
3811 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3812 castExpr, castExpr, exprACTC, CCK);
John McCall4124c492011-10-17 18:40:02 +00003813 return ACR_okay;
3814}
3815
3816/// Given that we saw an expression with the ARCUnbridgedCastTy
3817/// placeholder type, complain bitterly.
3818void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3819 // We expect the spurious ImplicitCastExpr to already have been stripped.
3820 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3821 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3822
3823 SourceRange castRange;
3824 QualType castType;
3825 CheckedConversionKind CCK;
3826
3827 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3828 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3829 castType = cast->getTypeAsWritten();
3830 CCK = CCK_CStyleCast;
3831 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3832 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3833 castType = cast->getTypeAsWritten();
3834 CCK = CCK_OtherCast;
3835 } else {
3836 castType = cast->getType();
3837 CCK = CCK_ImplicitConversion;
3838 }
3839
3840 ARCConversionTypeClass castACTC =
3841 classifyTypeForARCConversion(castType.getNonReferenceType());
3842
3843 Expr *castExpr = realCast->getSubExpr();
3844 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3845
3846 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003847 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00003848}
3849
3850/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3851/// type, remove the placeholder cast.
3852Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3853 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3854
3855 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3856 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3857 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3858 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3859 assert(uo->getOpcode() == UO_Extension);
3860 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3861 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3862 sub->getValueKind(), sub->getObjectKind(),
3863 uo->getOperatorLoc());
3864 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3865 assert(!gse->isResultDependent());
3866
3867 unsigned n = gse->getNumAssocs();
3868 SmallVector<Expr*, 4> subExprs(n);
3869 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3870 for (unsigned i = 0; i != n; ++i) {
3871 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3872 Expr *sub = gse->getAssocExpr(i);
3873 if (i == gse->getResultIndex())
3874 sub = stripARCUnbridgedCast(sub);
3875 subExprs[i] = sub;
3876 }
3877
3878 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3879 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003880 subTypes, subExprs,
3881 gse->getDefaultLoc(),
John McCall4124c492011-10-17 18:40:02 +00003882 gse->getRParenLoc(),
3883 gse->containsUnexpandedParameterPack(),
3884 gse->getResultIndex());
3885 } else {
3886 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3887 return cast<ImplicitCastExpr>(e)->getSubExpr();
3888 }
3889}
3890
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003891bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3892 QualType exprType) {
3893 QualType canCastType =
3894 Context.getCanonicalType(castType).getUnqualifiedType();
3895 QualType canExprType =
3896 Context.getCanonicalType(exprType).getUnqualifiedType();
3897 if (isa<ObjCObjectPointerType>(canCastType) &&
3898 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3899 canExprType->isObjCObjectPointerType()) {
3900 if (const ObjCObjectPointerType *ObjT =
3901 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00003902 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
3903 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003904 }
3905 return true;
3906}
3907
John McCall4db5c3c2011-07-07 06:58:02 +00003908/// Look for an ObjCReclaimReturnedObject cast and destroy it.
3909static Expr *maybeUndoReclaimObject(Expr *e) {
3910 // For now, we just undo operands that are *immediately* reclaim
3911 // expressions, which prevents the vast majority of potential
3912 // problems here. To catch them all, we'd need to rebuild arbitrary
3913 // value-propagating subexpressions --- we can't reliably rebuild
3914 // in-place because of expression sharing.
3915 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall2d637d22011-09-10 06:18:15 +00003916 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall4db5c3c2011-07-07 06:58:02 +00003917 return ice->getSubExpr();
3918
3919 return e;
3920}
3921
John McCall31168b02011-06-15 23:02:42 +00003922ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3923 ObjCBridgeCastKind Kind,
3924 SourceLocation BridgeKeywordLoc,
3925 TypeSourceInfo *TSInfo,
3926 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00003927 ExprResult SubResult = UsualUnaryConversions(SubExpr);
3928 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003929 SubExpr = SubResult.get();
John McCalleb075542011-08-26 00:48:42 +00003930
John McCall31168b02011-06-15 23:02:42 +00003931 QualType T = TSInfo->getType();
3932 QualType FromType = SubExpr->getType();
3933
John McCall9320b872011-09-09 05:25:32 +00003934 CastKind CK;
3935
John McCall31168b02011-06-15 23:02:42 +00003936 bool MustConsume = false;
3937 if (T->isDependentType() || SubExpr->isTypeDependent()) {
3938 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00003939 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00003940 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3941 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00003942 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3943 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00003944 switch (Kind) {
3945 case OBC_Bridge:
3946 break;
3947
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003948 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003949 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00003950 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3951 << 2
3952 << FromType
3953 << (T->isBlockPointerType()? 1 : 0)
3954 << T
3955 << SubExpr->getSourceRange()
3956 << Kind;
3957 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3958 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3959 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003960 << FromType << br
John McCall31168b02011-06-15 23:02:42 +00003961 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003962 br ? "CFBridgingRelease "
3963 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00003964
3965 Kind = OBC_Bridge;
3966 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003967 }
John McCall31168b02011-06-15 23:02:42 +00003968
3969 case OBC_BridgeTransfer:
3970 // We must consume the Objective-C object produced by the cast.
3971 MustConsume = true;
3972 break;
3973 }
3974 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3975 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00003976 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00003977 switch (Kind) {
3978 case OBC_Bridge:
John McCall4db5c3c2011-07-07 06:58:02 +00003979 // Reclaiming a value that's going to be __bridge-casted to CF
3980 // is very dangerous, so we don't do it.
3981 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCall31168b02011-06-15 23:02:42 +00003982 break;
3983
3984 case OBC_BridgeRetained:
3985 // Produce the object before casting it.
3986 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00003987 CK_ARCProduceObject,
Craig Topperc3ec1492014-05-26 06:22:03 +00003988 SubExpr, nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00003989 break;
3990
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003991 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003992 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00003993 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3994 << (FromType->isBlockPointerType()? 1 : 0)
3995 << FromType
3996 << 2
3997 << T
3998 << SubExpr->getSourceRange()
3999 << Kind;
4000
4001 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4002 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4003 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004004 << T << br
4005 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4006 br ? "CFBridgingRetain " : "__bridge_retained");
John McCall31168b02011-06-15 23:02:42 +00004007
4008 Kind = OBC_Bridge;
4009 break;
4010 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004011 }
John McCall31168b02011-06-15 23:02:42 +00004012 } else {
4013 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4014 << FromType << T << Kind
4015 << SubExpr->getSourceRange()
4016 << TSInfo->getTypeLoc().getSourceRange();
4017 return ExprError();
4018 }
4019
John McCall9320b872011-09-09 05:25:32 +00004020 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00004021 BridgeKeywordLoc,
4022 TSInfo, SubExpr);
4023
4024 if (MustConsume) {
4025 ExprNeedsCleanups = true;
John McCall2d637d22011-09-10 06:18:15 +00004026 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
Craig Topperc3ec1492014-05-26 06:22:03 +00004027 nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004028 }
4029
4030 return Result;
4031}
4032
4033ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4034 SourceLocation LParenLoc,
4035 ObjCBridgeCastKind Kind,
4036 SourceLocation BridgeKeywordLoc,
4037 ParsedType Type,
4038 SourceLocation RParenLoc,
4039 Expr *SubExpr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004040 TypeSourceInfo *TSInfo = nullptr;
John McCall31168b02011-06-15 23:02:42 +00004041 QualType T = GetTypeFromParser(Type, &TSInfo);
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00004042 if (Kind == OBC_Bridge)
4043 CheckTollFreeBridgeCast(T, SubExpr);
John McCall31168b02011-06-15 23:02:42 +00004044 if (!TSInfo)
4045 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4046 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
4047 SubExpr);
4048}