blob: 40ab95b6ec57dcdab30d834659086e90aa4c31e2 [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
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000600static ObjCMethodDecl *FindAllocMethod(Sema &S, ObjCInterfaceDecl *NSClass) {
601 ObjCMethodDecl *Method = nullptr;
602 ASTContext &Context = S.Context;
603
604 // Find +[NSClass alloc] method.
605 IdentifierInfo *II = &Context.Idents.get("alloc");
606 Selector AllocSel = Context.Selectors.getSelector(0, &II);
607 Method = NSClass->lookupClassMethod(AllocSel);
608 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
609 Method = ObjCMethodDecl::Create(Context,
610 SourceLocation(), SourceLocation(), AllocSel,
611 Context.getObjCIdType(),
612 nullptr /*TypeSourceInfo */,
613 Context.getTranslationUnitDecl(),
614 false /*Instance*/, false/*isVariadic*/,
615 /*isPropertyAccessor=*/false,
616 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
617 ObjCMethodDecl::Required,
618 false);
619 SmallVector<ParmVarDecl *, 1> Params;
620 Method->setMethodParams(Context, Params, None);
621 }
622 return Method;
623}
624
John McCallf2538342012-07-31 05:14:30 +0000625/// Build an ObjC subscript pseudo-object expression, given that
626/// that's supported by the runtime.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000627ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
628 Expr *IndexExpr,
629 ObjCMethodDecl *getterMethod,
630 ObjCMethodDecl *setterMethod) {
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +0000631 assert(!LangOpts.isSubscriptPointerArithmetic());
John McCall5fb5df92012-06-20 06:18:46 +0000632
John McCallf2538342012-07-31 05:14:30 +0000633 // We can't get dependent types here; our callers should have
634 // filtered them out.
635 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
636 "base or index cannot have dependent type here");
637
638 // Filter out placeholders in the index. In theory, overloads could
639 // be preserved here, although that might not actually work correctly.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000640 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
641 if (Result.isInvalid())
642 return ExprError();
643 IndexExpr = Result.get();
644
John McCallf2538342012-07-31 05:14:30 +0000645 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000646 Result = DefaultLvalueConversion(BaseExpr);
647 if (Result.isInvalid())
648 return ExprError();
649 BaseExpr = Result.get();
John McCallf2538342012-07-31 05:14:30 +0000650
651 // Build the pseudo-object expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000652 return ObjCSubscriptRefExpr::Create(Context, BaseExpr, IndexExpr,
653 Context.PseudoObjectTy, getterMethod,
654 setterMethod, RB);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000655}
656
657ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000658 bool Arc = getLangOpts().ObjCAutoRefCount;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000659 // Look up the NSArray class, if we haven't done so already.
660 if (!NSArrayDecl) {
661 NamedDecl *IF = LookupSingleName(TUScope,
662 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
663 SR.getBegin(),
664 LookupOrdinaryName);
665 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000666 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000667 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
668 Context.getTranslationUnitDecl(),
669 SourceLocation(),
670 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
Craig Topperc3ec1492014-05-26 06:22:03 +0000671 nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000672
673 if (!NSArrayDecl) {
674 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
675 return ExprError();
676 }
677 }
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000678 if (Arc && !ArrayAllocObjectsMethod) {
679 // Find +[NSArray alloc] method.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000680 ArrayAllocObjectsMethod = FindAllocMethod(*this, NSArrayDecl);
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000681 if (!ArrayAllocObjectsMethod) {
682 Diag(SR.getBegin(), diag::err_undeclared_alloc);
683 return ExprError();
684 }
685 }
686 // Find the arrayWithObjects:count: method, if we haven't done so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000687 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000688 if (!ArrayWithObjectsMethod) {
689 Selector
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000690 Sel = NSAPIObj->getNSArraySelector(
691 Arc? NSAPI::NSArr_initWithObjectsCount : NSAPI::NSArr_arrayWithObjectsCount);
692 ObjCMethodDecl *Method =
693 Arc? NSArrayDecl->lookupInstanceMethod(Sel)
694 : NSArrayDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000695 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000696 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000697 Method = ObjCMethodDecl::Create(
698 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000699 Context.getTranslationUnitDecl(),
700 Arc /*Instance for Arc, Class for MRR*/,
Alp Toker314cc812014-01-25 16:55:45 +0000701 false /*isVariadic*/,
702 /*isPropertyAccessor=*/false,
703 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
704 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000705 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000706 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000707 SourceLocation(),
708 SourceLocation(),
709 &Context.Idents.get("objects"),
710 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000711 /*TInfo=*/nullptr,
712 SC_None, nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000713 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000714 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000715 SourceLocation(),
716 SourceLocation(),
717 &Context.Idents.get("cnt"),
718 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000719 /*TInfo=*/nullptr, SC_None,
720 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000721 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000722 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000723 }
724
Jordy Rose08e500c2012-05-12 17:32:44 +0000725 if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000726 return ExprError();
Jordy Rose08e500c2012-05-12 17:32:44 +0000727
Jordy Rose4af44872012-05-12 17:32:56 +0000728 // Dig out the type that all elements should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000729 QualType T = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000730 const PointerType *PtrT = T->getAs<PointerType>();
731 if (!PtrT ||
732 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
733 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
734 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000735 Diag(Method->parameters()[0]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000736 diag::note_objc_literal_method_param)
737 << 0 << T
738 << Context.getPointerType(IdT.withConst());
739 return ExprError();
740 }
741
742 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000743 if (!Method->parameters()[1]->getType()->isIntegerType()) {
Jordy Rose4af44872012-05-12 17:32:56 +0000744 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
745 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000746 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000747 diag::note_objc_literal_method_param)
748 << 1
Alp Toker03376dc2014-07-07 09:02:20 +0000749 << Method->parameters()[1]->getType()
Jordy Rose4af44872012-05-12 17:32:56 +0000750 << "integral";
751 return ExprError();
752 }
753
754 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rose08e500c2012-05-12 17:32:44 +0000755 ArrayWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000756 }
757
Alp Toker03376dc2014-07-07 09:02:20 +0000758 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000759 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000760
761 // Check that each of the elements provided is valid in a collection literal,
762 // performing conversions as necessary.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000763 Expr **ElementsBuffer = Elements.data();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000764 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
765 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
766 ElementsBuffer[I],
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000767 RequiredType, true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000768 if (Converted.isInvalid())
769 return ExprError();
770
771 ElementsBuffer[I] = Converted.get();
772 }
773
774 QualType Ty
775 = Context.getObjCObjectPointerType(
776 Context.getObjCInterfaceType(NSArrayDecl));
777
778 return MaybeBindToTemporary(
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000779 ObjCArrayLiteral::Create(Context, Elements, Ty,
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000780 ArrayWithObjectsMethod,
781 ArrayAllocObjectsMethod, SR));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000782}
783
784ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
785 ObjCDictionaryElement *Elements,
786 unsigned NumElements) {
Fariborz Jahanian2a25dba2014-08-06 23:40:31 +0000787 bool Arc = getLangOpts().ObjCAutoRefCount;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000788 // Look up the NSDictionary class, if we haven't done so already.
789 if (!NSDictionaryDecl) {
790 NamedDecl *IF = LookupSingleName(TUScope,
791 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
792 SR.getBegin(), LookupOrdinaryName);
793 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000794 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000795 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
796 Context.getTranslationUnitDecl(),
797 SourceLocation(),
798 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
Craig Topperc3ec1492014-05-26 06:22:03 +0000799 nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000800
801 if (!NSDictionaryDecl) {
802 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
803 return ExprError();
804 }
805 }
806
Fariborz Jahanian2a25dba2014-08-06 23:40:31 +0000807 if (Arc && !DictAllocObjectsMethod) {
808 // Find +[NSDictionary alloc] method.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000809 DictAllocObjectsMethod = FindAllocMethod(*this, NSDictionaryDecl);
Fariborz Jahanian2a25dba2014-08-06 23:40:31 +0000810 if (!DictAllocObjectsMethod) {
811 Diag(SR.getBegin(), diag::err_undeclared_alloc);
812 return ExprError();
813 }
814 }
815
Fariborz Jahaniand45e7ce2014-08-07 20:57:35 +0000816 // Find the dictionaryWithObjects:forKeys:count: or initWithObjects:forKeys:count:
817 // (for arc) method, if we haven't done so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000818 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000819 if (!DictionaryWithObjectsMethod) {
Fariborz Jahaniand45e7ce2014-08-07 20:57:35 +0000820 Selector Sel =
821 NSAPIObj->getNSDictionarySelector(Arc? NSAPI::NSDict_initWithObjectsForKeysCount
822 : NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
823 ObjCMethodDecl *Method =
824 Arc ? NSDictionaryDecl->lookupInstanceMethod(Sel)
825 : NSDictionaryDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000826 if (!Method && getLangOpts().DebuggerObjCLiteral) {
827 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000828 SourceLocation(), SourceLocation(), Sel,
829 IdT,
Craig Topperc3ec1492014-05-26 06:22:03 +0000830 nullptr /*TypeSourceInfo */,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000831 Context.getTranslationUnitDecl(),
Fariborz Jahaniand45e7ce2014-08-07 20:57:35 +0000832 Arc /*Instance for Arc, Class for MRR*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000833 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000834 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
835 ObjCMethodDecl::Required,
836 false);
837 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000838 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000839 SourceLocation(),
840 SourceLocation(),
841 &Context.Idents.get("objects"),
842 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000843 /*TInfo=*/nullptr, SC_None,
844 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000845 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000846 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000847 SourceLocation(),
848 SourceLocation(),
849 &Context.Idents.get("keys"),
850 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000851 /*TInfo=*/nullptr, SC_None,
852 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000853 Params.push_back(keys);
Jordy Rose08e500c2012-05-12 17:32:44 +0000854 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000855 SourceLocation(),
856 SourceLocation(),
857 &Context.Idents.get("cnt"),
858 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000859 /*TInfo=*/nullptr, SC_None,
860 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000861 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000862 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000863 }
864
Jordy Rose08e500c2012-05-12 17:32:44 +0000865 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
866 Method))
867 return ExprError();
868
Jordy Rose4af44872012-05-12 17:32:56 +0000869 // Dig out the type that all values should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000870 QualType ValueT = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000871 const PointerType *PtrValue = ValueT->getAs<PointerType>();
872 if (!PtrValue ||
873 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000874 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000875 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000876 Diag(Method->parameters()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000877 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000878 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000879 << Context.getPointerType(IdT.withConst());
880 return ExprError();
881 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000882
Jordy Rose4af44872012-05-12 17:32:56 +0000883 // Dig out the type that all keys should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000884 QualType KeyT = Method->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000885 const PointerType *PtrKey = KeyT->getAs<PointerType>();
886 if (!PtrKey ||
887 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
888 IdT)) {
889 bool err = true;
890 if (PtrKey) {
891 if (QIDNSCopying.isNull()) {
892 // key argument of selector is id<NSCopying>?
893 if (ObjCProtocolDecl *NSCopyingPDecl =
894 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
895 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
896 QIDNSCopying =
897 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
898 (ObjCProtocolDecl**) PQ,1);
899 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
900 }
901 }
902 if (!QIDNSCopying.isNull())
903 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
904 QIDNSCopying);
905 }
906
907 if (err) {
908 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
909 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000910 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000911 diag::note_objc_literal_method_param)
912 << 1 << KeyT
913 << Context.getPointerType(IdT.withConst());
914 return ExprError();
915 }
916 }
917
918 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000919 QualType CountType = Method->parameters()[2]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000920 if (!CountType->isIntegerType()) {
921 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
922 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000923 Diag(Method->parameters()[2]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000924 diag::note_objc_literal_method_param)
925 << 2 << CountType
926 << "integral";
927 return ExprError();
928 }
929
930 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
931 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000932 }
933
Alp Toker03376dc2014-07-07 09:02:20 +0000934 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000935 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
Alp Toker03376dc2014-07-07 09:02:20 +0000936 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000937 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
938
Ted Kremeneke65b0862012-03-06 20:05:56 +0000939 // Check that each of the keys and values provided is valid in a collection
940 // literal, performing conversions as necessary.
941 bool HasPackExpansions = false;
942 for (unsigned I = 0, N = NumElements; I != N; ++I) {
943 // Check the key.
944 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
945 KeyT);
946 if (Key.isInvalid())
947 return ExprError();
948
949 // Check the value.
950 ExprResult Value
951 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
952 if (Value.isInvalid())
953 return ExprError();
954
955 Elements[I].Key = Key.get();
956 Elements[I].Value = Value.get();
957
958 if (Elements[I].EllipsisLoc.isInvalid())
959 continue;
960
961 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
962 !Elements[I].Value->containsUnexpandedParameterPack()) {
963 Diag(Elements[I].EllipsisLoc,
964 diag::err_pack_expansion_without_parameter_packs)
965 << SourceRange(Elements[I].Key->getLocStart(),
966 Elements[I].Value->getLocEnd());
967 return ExprError();
968 }
969
970 HasPackExpansions = true;
971 }
972
973
974 QualType Ty
975 = Context.getObjCObjectPointerType(
Robert Wilhelm88e02492013-08-19 07:57:02 +0000976 Context.getObjCInterfaceType(NSDictionaryDecl));
977 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
978 Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty,
Fariborz Jahanian2a25dba2014-08-06 23:40:31 +0000979 DictionaryWithObjectsMethod, DictAllocObjectsMethod, SR));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000980}
981
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000982ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregorabd9e962010-04-20 15:39:42 +0000983 TypeSourceInfo *EncodedTypeInfo,
Anders Carlsson315d2292009-06-07 18:45:35 +0000984 SourceLocation RParenLoc) {
Douglas Gregorabd9e962010-04-20 15:39:42 +0000985 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlsson315d2292009-06-07 18:45:35 +0000986 QualType StrTy;
Mike Stump11289f42009-09-09 15:08:12 +0000987 if (EncodedType->isDependentType())
Anders Carlsson315d2292009-06-07 18:45:35 +0000988 StrTy = Context.DependentTy;
989 else {
Fariborz Jahaniand9bc6c32011-06-16 22:34:44 +0000990 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
991 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000992 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000993 diag::err_incomplete_type_objc_at_encode,
994 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000995 return ExprError();
996
Anders Carlsson315d2292009-06-07 18:45:35 +0000997 std::string Str;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +0000998 QualType NotEncodedT;
999 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
1000 if (!NotEncodedT.isNull())
1001 Diag(AtLoc, diag::warn_incomplete_encoded_type)
1002 << EncodedType << NotEncodedT;
Anders Carlsson315d2292009-06-07 18:45:35 +00001003
1004 // The type of @encode is the same as the type of the corresponding string,
1005 // which is an array type.
1006 StrTy = Context.CharTy;
1007 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001008 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlsson315d2292009-06-07 18:45:35 +00001009 StrTy.addConst();
1010 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
1011 ArrayType::Normal, 0);
1012 }
Mike Stump11289f42009-09-09 15:08:12 +00001013
Douglas Gregorabd9e962010-04-20 15:39:42 +00001014 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlsson315d2292009-06-07 18:45:35 +00001015}
1016
John McCallfaf5fb42010-08-26 23:41:50 +00001017ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1018 SourceLocation EncodeLoc,
1019 SourceLocation LParenLoc,
1020 ParsedType ty,
1021 SourceLocation RParenLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001022 // FIXME: Preserve type source info ?
Douglas Gregorabd9e962010-04-20 15:39:42 +00001023 TypeSourceInfo *TInfo;
1024 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1025 if (!TInfo)
1026 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
1027 PP.getLocForEndOfToken(LParenLoc));
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001028
Douglas Gregorabd9e962010-04-20 15:39:42 +00001029 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001030}
1031
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001032static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1033 SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001034 SourceLocation LParenLoc,
1035 SourceLocation RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001036 ObjCMethodDecl *Method,
1037 ObjCMethodList &MethList) {
1038 ObjCMethodList *M = &MethList;
1039 bool Warned = false;
1040 for (M = M->getNext(); M; M=M->getNext()) {
1041 ObjCMethodDecl *MatchingMethodDecl = M->Method;
1042 if (MatchingMethodDecl == Method ||
1043 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1044 MatchingMethodDecl->getSelector() != Method->getSelector())
1045 continue;
1046 if (!S.MatchTwoMethodDeclarations(Method,
1047 MatchingMethodDecl, Sema::MMS_loose)) {
1048 if (!Warned) {
1049 Warned = true;
1050 S.Diag(AtLoc, diag::warning_multiple_selectors)
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001051 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1052 << FixItHint::CreateInsertion(RParenLoc, ")");
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001053 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1054 << Method->getDeclName();
1055 }
1056 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1057 << MatchingMethodDecl->getDeclName();
1058 }
1059 }
1060 return Warned;
1061}
1062
1063static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001064 ObjCMethodDecl *Method,
1065 SourceLocation LParenLoc,
1066 SourceLocation RParenLoc,
1067 bool WarnMultipleSelectors) {
1068 if (!WarnMultipleSelectors ||
1069 S.Diags.isIgnored(diag::warning_multiple_selectors, SourceLocation()))
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001070 return;
1071 bool Warned = false;
1072 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1073 e = S.MethodPool.end(); b != e; b++) {
1074 // first, instance methods
1075 ObjCMethodList &InstMethList = b->second.first;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001076 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001077 Method, InstMethList))
1078 Warned = true;
1079
1080 // second, class methods
1081 ObjCMethodList &ClsMethList = b->second.second;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001082 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1083 Method, ClsMethList) || Warned)
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001084 return;
1085 }
1086}
1087
John McCallfaf5fb42010-08-26 23:41:50 +00001088ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1089 SourceLocation AtLoc,
1090 SourceLocation SelLoc,
1091 SourceLocation LParenLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001092 SourceLocation RParenLoc,
1093 bool WarnMultipleSelectors) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001094 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1095 SourceRange(LParenLoc, RParenLoc), false, false);
1096 if (!Method)
1097 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian0571d9b2009-06-16 16:25:00 +00001098 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00001099 if (!Method) {
1100 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1101 Selector MatchedSel = OM->getSelector();
1102 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1103 RParenLoc.getLocWithOffset(-1));
1104 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1105 << Sel << MatchedSel
1106 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1107
1108 } else
1109 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001110 } else
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001111 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1112 WarnMultipleSelectors);
Fariborz Jahanian9a881012011-07-13 19:05:43 +00001113
Fariborz Jahanian65a78b52014-05-09 19:51:39 +00001114 if (Method &&
1115 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
1116 !getSourceManager().isInSystemHeader(Method->getLocation())) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001117 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
1118 = ReferencedSelectors.find(Sel);
1119 if (Pos == ReferencedSelectors.end())
1120 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian9a881012011-07-13 19:05:43 +00001121 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001122
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001123 // In ARC, forbid the user from using @selector for
John McCall31168b02011-06-15 23:02:42 +00001124 // retain/release/autorelease/dealloc/retainCount.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001125 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001126 switch (Sel.getMethodFamily()) {
1127 case OMF_retain:
1128 case OMF_release:
1129 case OMF_autorelease:
1130 case OMF_retainCount:
1131 case OMF_dealloc:
1132 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1133 Sel << SourceRange(LParenLoc, RParenLoc);
1134 break;
1135
1136 case OMF_None:
1137 case OMF_alloc:
1138 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00001139 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00001140 case OMF_init:
1141 case OMF_mutableCopy:
1142 case OMF_new:
1143 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00001144 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001145 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001146 break;
1147 }
1148 }
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001149 QualType Ty = Context.getObjCSelType();
Daniel Dunbar45858d22010-02-03 20:11:42 +00001150 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001151}
1152
John McCallfaf5fb42010-08-26 23:41:50 +00001153ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1154 SourceLocation AtLoc,
1155 SourceLocation ProtoLoc,
1156 SourceLocation LParenLoc,
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001157 SourceLocation ProtoIdLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00001158 SourceLocation RParenLoc) {
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001159 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001160 if (!PDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001161 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001162 return true;
1163 }
Fariborz Jahaniana57d91c22014-07-25 19:45:01 +00001164 if (PDecl->hasDefinition())
1165 PDecl = PDecl->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00001166
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001167 QualType Ty = Context.getObjCProtoType();
1168 if (Ty.isNull())
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001169 return true;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001170 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001171 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001172}
1173
John McCall5f2d5562011-02-03 09:00:02 +00001174/// Try to capture an implicit reference to 'self'.
Eli Friedman24af8502012-02-03 22:47:37 +00001175ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1176 DeclContext *DC = getFunctionLevelDeclContext();
John McCall5f2d5562011-02-03 09:00:02 +00001177
1178 // If we're not in an ObjC method, error out. Note that, unlike the
1179 // C++ case, we don't require an instance method --- class methods
1180 // still have a 'self', and we really do still need to capture it!
1181 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1182 if (!method)
Craig Topperc3ec1492014-05-26 06:22:03 +00001183 return nullptr;
John McCall5f2d5562011-02-03 09:00:02 +00001184
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001185 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall5f2d5562011-02-03 09:00:02 +00001186
1187 return method;
1188}
1189
Douglas Gregor64910ca2011-09-09 20:05:21 +00001190static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1191 if (T == Context.getObjCInstanceType())
1192 return Context.getObjCIdType();
1193
1194 return T;
1195}
1196
Douglas Gregor33823722011-06-11 01:09:30 +00001197QualType Sema::getMessageSendResultType(QualType ReceiverType,
1198 ObjCMethodDecl *Method,
1199 bool isClassMessage, bool isSuperMessage) {
1200 assert(Method && "Must have a method");
1201 if (!Method->hasRelatedResultType())
1202 return Method->getSendResultType();
1203
1204 // If a method has a related return type:
1205 // - if the method found is an instance method, but the message send
1206 // was a class message send, T is the declared return type of the method
1207 // found
1208 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor64910ca2011-09-09 20:05:21 +00001209 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001210
1211 // - if the receiver is super, T is a pointer to the class of the
1212 // enclosing method definition
1213 if (isSuperMessage) {
1214 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1215 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1216 return Context.getObjCObjectPointerType(
1217 Context.getObjCInterfaceType(Class));
1218 }
1219
1220 // - if the receiver is the name of a class U, T is a pointer to U
1221 if (ReceiverType->getAs<ObjCInterfaceType>() ||
1222 ReceiverType->isObjCQualifiedInterfaceType())
1223 return Context.getObjCObjectPointerType(ReceiverType);
1224 // - if the receiver is of type Class or qualified Class type,
1225 // T is the declared return type of the method.
1226 if (ReceiverType->isObjCClassType() ||
1227 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor64910ca2011-09-09 20:05:21 +00001228 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001229
1230 // - if the receiver is id, qualified id, Class, or qualified Class, T
1231 // is the receiver type, otherwise
1232 // - T is the type of the receiver expression.
1233 return ReceiverType;
1234}
John McCall5f2d5562011-02-03 09:00:02 +00001235
John McCall5ec7e7d2013-03-19 07:04:25 +00001236/// Look for an ObjC method whose result type exactly matches the given type.
1237static const ObjCMethodDecl *
1238findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1239 QualType instancetype) {
Alp Toker314cc812014-01-25 16:55:45 +00001240 if (MD->getReturnType() == instancetype)
1241 return MD;
John McCall5ec7e7d2013-03-19 07:04:25 +00001242
1243 // For these purposes, a method in an @implementation overrides a
1244 // declaration in the @interface.
1245 if (const ObjCImplDecl *impl =
1246 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1247 const ObjCContainerDecl *iface;
1248 if (const ObjCCategoryImplDecl *catImpl =
1249 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1250 iface = catImpl->getCategoryDecl();
1251 } else {
1252 iface = impl->getClassInterface();
1253 }
1254
1255 const ObjCMethodDecl *ifaceMD =
1256 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1257 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1258 }
1259
1260 SmallVector<const ObjCMethodDecl *, 4> overrides;
1261 MD->getOverriddenMethods(overrides);
1262 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1263 if (const ObjCMethodDecl *result =
1264 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1265 return result;
1266 }
1267
Craig Topperc3ec1492014-05-26 06:22:03 +00001268 return nullptr;
John McCall5ec7e7d2013-03-19 07:04:25 +00001269}
1270
1271void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1272 // Only complain if we're in an ObjC method and the required return
1273 // type doesn't match the method's declared return type.
1274 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1275 if (!MD || !MD->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +00001276 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
John McCall5ec7e7d2013-03-19 07:04:25 +00001277 return;
1278
1279 // Look for a method overridden by this method which explicitly uses
1280 // 'instancetype'.
1281 if (const ObjCMethodDecl *overridden =
1282 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +00001283 SourceRange range = overridden->getReturnTypeSourceRange();
1284 SourceLocation loc = range.getBegin();
John McCall5ec7e7d2013-03-19 07:04:25 +00001285 if (loc.isInvalid())
1286 loc = overridden->getLocation();
1287 Diag(loc, diag::note_related_result_type_explicit)
1288 << /*current method*/ 1 << range;
1289 return;
1290 }
1291
1292 // Otherwise, if we have an interesting method family, note that.
1293 // This should always trigger if the above didn't.
1294 if (ObjCMethodFamily family = MD->getMethodFamily())
1295 Diag(MD->getLocation(), diag::note_related_result_type_family)
1296 << /*current method*/ 1
1297 << family;
1298}
1299
Douglas Gregor33823722011-06-11 01:09:30 +00001300void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1301 E = E->IgnoreParenImpCasts();
1302 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1303 if (!MsgSend)
1304 return;
1305
1306 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1307 if (!Method)
1308 return;
1309
1310 if (!Method->hasRelatedResultType())
1311 return;
Alp Toker314cc812014-01-25 16:55:45 +00001312
1313 if (Context.hasSameUnqualifiedType(
1314 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
Douglas Gregor33823722011-06-11 01:09:30 +00001315 return;
Alp Toker314cc812014-01-25 16:55:45 +00001316
1317 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
Douglas Gregorbab8a962011-09-08 01:46:34 +00001318 Context.getObjCInstanceType()))
1319 return;
1320
Douglas Gregor33823722011-06-11 01:09:30 +00001321 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1322 << Method->isInstanceMethod() << Method->getSelector()
1323 << MsgSend->getType();
1324}
1325
1326bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001327 MultiExprArg Args,
1328 Selector Sel,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001329 ArrayRef<SourceLocation> SelectorLocs,
1330 ObjCMethodDecl *Method,
Douglas Gregor33823722011-06-11 01:09:30 +00001331 bool isClassMessage, bool isSuperMessage,
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001332 SourceLocation lbrac, SourceLocation rbrac,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001333 SourceRange RecRange,
John McCall7decc9e2010-11-18 06:31:45 +00001334 QualType &ReturnType, ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001335 SourceLocation SelLoc;
1336 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1337 SelLoc = SelectorLocs.front();
1338 else
1339 SelLoc = lbrac;
1340
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001341 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001342 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001343 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001344 if (Args[i]->isTypeDependent())
1345 continue;
1346
John McCallcc5788c2013-03-04 07:34:02 +00001347 ExprResult result;
1348 if (getLangOpts().DebuggerSupport) {
1349 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001350 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001351 } else {
1352 result = DefaultArgumentPromotion(Args[i]);
1353 }
1354 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001355 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001356 Args[i] = result.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001357 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001358
John McCall31168b02011-06-15 23:02:42 +00001359 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001360 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001361 DiagID = diag::err_arc_method_not_found;
1362 else
1363 DiagID = isClassMessage ? diag::warn_class_method_not_found
1364 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001365 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001366 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahanian06499232013-06-18 17:10:58 +00001367 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001368 if (getLangOpts().ObjCAutoRefCount)
1369 DiagID = diag::error_method_not_found_with_typo;
1370 else
1371 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1372 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001373 Selector MatchedSel = OMD->getSelector();
1374 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian5ab87502014-08-12 22:16:41 +00001375 if (MatchedSel.isUnarySelector())
1376 Diag(SelLoc, DiagID)
1377 << Sel<< isClassMessage << MatchedSel
1378 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1379 else
1380 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001381 }
1382 else
1383 Diag(SelLoc, DiagID)
1384 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001385 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001386 // Find the class to which we are sending this message.
1387 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001388 if (ObjCInterfaceDecl *ThisClass =
1389 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
1390 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1391 if (!RecRange.isInvalid())
1392 if (ThisClass->lookupClassMethod(Sel))
1393 Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
1394 << FixItHint::CreateReplacement(RecRange,
1395 ThisClass->getNameAsString());
1396 }
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001397 }
1398 }
John McCall3f4138c2011-07-13 17:56:40 +00001399
1400 // In debuggers, we want to use __unknown_anytype for these
1401 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001402 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001403 ReturnType = Context.UnknownAnyTy;
1404 } else {
1405 ReturnType = Context.getObjCIdType();
1406 }
John McCall7decc9e2010-11-18 06:31:45 +00001407 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001408 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001409 }
Mike Stump11289f42009-09-09 15:08:12 +00001410
Douglas Gregor33823722011-06-11 01:09:30 +00001411 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1412 isSuperMessage);
Alp Toker314cc812014-01-25 16:55:45 +00001413 VK = Expr::getValueKindForType(Method->getReturnType());
Mike Stump11289f42009-09-09 15:08:12 +00001414
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001415 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001416 // Method might have more arguments than selector indicates. This is due
1417 // to addition of c-style arguments in method.
1418 if (Method->param_size() > Sel.getNumArgs())
1419 NumNamedArgs = Method->param_size();
1420 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001421 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001422 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001423 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001424 return false;
1425 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001426
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001427 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001428 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001429 // We can't do any type-checking on a type-dependent argument.
1430 if (Args[i]->isTypeDependent())
1431 continue;
1432
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001433 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001434
Alp Toker03376dc2014-07-07 09:02:20 +00001435 ParmVarDecl *param = Method->parameters()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001436 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001437
John McCall4124c492011-10-17 18:40:02 +00001438 // Strip the unbridged-cast placeholder expression off unless it's
1439 // a consumed argument.
1440 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1441 !param->hasAttr<CFConsumedAttr>())
1442 argExpr = stripARCUnbridgedCast(argExpr);
1443
John McCallea0a39e2012-11-14 00:49:39 +00001444 // If the parameter is __unknown_anytype, infer its type
1445 // from the argument.
1446 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001447 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001448 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001449 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001450 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001451 } else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001452 Args[i] = argE.get();
John McCallea0a39e2012-11-14 00:49:39 +00001453
John McCallcc5788c2013-03-04 07:34:02 +00001454 // Update the parameter type in-place.
1455 param->setType(paramType);
1456 }
1457 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001458 }
1459
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001460 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall4124c492011-10-17 18:40:02 +00001461 param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001462 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001463 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001464
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001465 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall4124c492011-10-17 18:40:02 +00001466 param);
Fariborz Jahaniana1db7df2014-07-31 17:39:50 +00001467 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001468 if (ArgE.isInvalid())
1469 IsError = true;
1470 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001471 Args[i] = ArgE.getAs<Expr>();
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001472 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001473
1474 // Promote additional arguments to variadic methods.
1475 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001476 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001477 if (Args[i]->isTypeDependent())
1478 continue;
1479
Jordy Roseaca01f92012-05-12 17:32:52 +00001480 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
Craig Topperc3ec1492014-05-26 06:22:03 +00001481 nullptr);
John Wiegley01296292011-04-08 18:41:53 +00001482 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001483 Args[i] = Arg.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001484 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001485 } else {
1486 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001487 if (Args.size() != NumNamedArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00001488 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001489 diag::err_typecheck_call_too_many_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001490 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001491 << Method->getSourceRange()
Chris Lattner3b054132008-11-19 05:08:23 +00001492 << SourceRange(Args[NumNamedArgs]->getLocStart(),
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001493 Args.back()->getLocEnd());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001494 }
1495 }
1496
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001497 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001498
1499 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001500 IsError |= CheckObjCMethodCall(
Craig Topper8c2a2a02014-08-30 16:55:39 +00001501 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001502
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001503 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001504}
1505
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001506bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001507 // 'self' is objc 'self' in an objc method only.
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001508 ObjCMethodDecl *Method =
1509 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1510 return isSelfExpr(RExpr, Method);
1511}
1512
1513bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
John McCallfe96e0b2011-11-06 09:01:30 +00001514 if (!method) return false;
1515
John McCall31168b02011-06-15 23:02:42 +00001516 receiver = receiver->IgnoreParenLValueCasts();
1517 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001518 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001519 return true;
1520 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001521}
1522
John McCall526ab472011-10-25 17:37:35 +00001523/// LookupMethodInType - Look up a method in an ObjCObjectType.
1524ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1525 bool isInstance) {
1526 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1527 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1528 // Look it up in the main interface (and categories, etc.)
1529 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1530 return method;
1531
1532 // Okay, look for "private" methods declared in any
1533 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001534 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1535 return method;
John McCall526ab472011-10-25 17:37:35 +00001536 }
1537
1538 // Check qualifiers.
Aaron Ballman1683f7b2014-03-17 15:55:30 +00001539 for (const auto *I : objType->quals())
1540 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
John McCall526ab472011-10-25 17:37:35 +00001541 return method;
1542
Craig Topperc3ec1492014-05-26 06:22:03 +00001543 return nullptr;
John McCall526ab472011-10-25 17:37:35 +00001544}
1545
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001546/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1547/// list of a qualified objective pointer type.
1548ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1549 const ObjCObjectPointerType *OPT,
1550 bool Instance)
1551{
Craig Topperc3ec1492014-05-26 06:22:03 +00001552 ObjCMethodDecl *MD = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +00001553 for (const auto *PROTO : OPT->quals()) {
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001554 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1555 return MD;
1556 }
1557 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001558 return nullptr;
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001559}
1560
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001561static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1562 if (!Receiver)
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001563 return;
1564
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001565 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver))
1566 Receiver = OVE->getSourceExpr();
1567
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001568 Expr *RExpr = Receiver->IgnoreParenImpCasts();
1569 SourceLocation Loc = RExpr->getLocStart();
1570 QualType T = RExpr->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001571 const ObjCPropertyDecl *PDecl = nullptr;
1572 const ObjCMethodDecl *GDecl = nullptr;
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001573 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1574 RExpr = POE->getSyntacticForm();
1575 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1576 if (PRE->isImplicitProperty()) {
1577 GDecl = PRE->getImplicitPropertyGetter();
1578 if (GDecl) {
Alp Toker314cc812014-01-25 16:55:45 +00001579 T = GDecl->getReturnType();
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001580 }
1581 }
1582 else {
1583 PDecl = PRE->getExplicitProperty();
1584 if (PDecl) {
1585 T = PDecl->getType();
1586 }
1587 }
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001588 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001589 }
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001590 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) {
1591 // See if receiver is a method which envokes a synthesized getter
1592 // backing a 'weak' property.
1593 ObjCMethodDecl *Method = ME->getMethodDecl();
Jordan Rose2bd991a2012-10-10 16:42:54 +00001594 if (Method && Method->getSelector().getNumArgs() == 0) {
1595 PDecl = Method->findPropertyDecl();
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001596 if (PDecl)
1597 T = PDecl->getType();
1598 }
1599 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001600
Jordan Rose13d6b712012-09-28 22:21:42 +00001601 if (T.getObjCLifetime() != Qualifiers::OCL_Weak) {
1602 if (!PDecl)
1603 return;
1604 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak))
1605 return;
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001606 }
Jordan Rose13d6b712012-09-28 22:21:42 +00001607
1608 S.Diag(Loc, diag::warn_receiver_is_weak)
1609 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1610
1611 if (PDecl)
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001612 S.Diag(PDecl->getLocation(), diag::note_property_declare);
Jordan Rose13d6b712012-09-28 22:21:42 +00001613 else if (GDecl)
1614 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
1615
1616 S.Diag(Loc, diag::note_arc_assign_to_strong);
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001617}
1618
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001619/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1620/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001621ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001622HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001623 Expr *BaseExpr, SourceLocation OpLoc,
1624 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001625 SourceLocation MemberLoc,
1626 SourceLocation SuperLoc, QualType SuperType,
1627 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001628 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1629 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001630
Benjamin Kramer365082d2012-05-19 16:34:46 +00001631 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001632 Diag(MemberLoc, diag::err_invalid_property_name)
1633 << MemberName << QualType(OPT, 0);
1634 return ExprError();
1635 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001636
1637 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregord6459312011-04-20 18:19:55 +00001638
Douglas Gregor4123a862011-11-14 22:10:01 +00001639 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1640 : BaseExpr->getSourceRange();
1641 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001642 diag::err_property_not_found_forward_class,
1643 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001644 return ExprError();
Douglas Gregor4123a862011-11-14 22:10:01 +00001645
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001646 // Search for a declared property first.
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001647 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001648 // Check whether we can reference this property.
1649 if (DiagnoseUseOfDecl(PD, MemberLoc))
1650 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001651 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001652 return new (Context)
1653 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1654 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001655 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001656 return new (Context)
1657 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1658 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001659 }
1660 // Check protocols on qualified interfaces.
Aaron Ballman83731462014-03-17 16:14:00 +00001661 for (const auto *I : OPT->quals())
1662 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001663 // Check whether we can reference this property.
1664 if (DiagnoseUseOfDecl(PD, MemberLoc))
1665 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001666
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001667 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001668 return new (Context) ObjCPropertyRefExpr(
1669 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1670 SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001671 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001672 return new (Context)
1673 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1674 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001675 }
1676 // If that failed, look for an "implicit" property by seeing if the nullary
1677 // selector is implemented.
1678
1679 // FIXME: The logic for looking up nullary and unary selectors should be
1680 // shared with the code in ActOnInstanceMessage.
1681
1682 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1683 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001684
1685 // May be founf in property's qualified list.
1686 if (!Getter)
1687 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001688
1689 // If this reference is in an @implementation, check for 'private' methods.
1690 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001691 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001692
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001693 if (Getter) {
1694 // Check if we can reference this property.
1695 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1696 return ExprError();
1697 }
1698 // If we found a getter then this may be a valid dot-reference, we
1699 // will look for the matching setter, in case it is needed.
1700 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001701 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1702 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001703 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001704
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001705 // May be founf in property's qualified list.
1706 if (!Setter)
1707 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1708
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001709 if (!Setter) {
1710 // If this reference is in an @implementation, also check for 'private'
1711 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001712 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001713 }
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001714
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001715 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1716 return ExprError();
1717
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001718 // Special warning if member name used in a property-dot for a setter accessor
1719 // does not use a property with same name; e.g. obj.X = ... for a property with
1720 // name 'x'.
1721 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor()
1722 && !IFace->FindPropertyDeclaration(Member)) {
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001723 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
1724 // Do not warn if user is using property-dot syntax to make call to
1725 // user named setter.
1726 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001727 Diag(MemberLoc,
1728 diag::warn_property_access_suggest)
1729 << MemberName << QualType(OPT, 0) << PDecl->getName()
1730 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001731 }
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001732 }
1733
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001734 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001735 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001736 return new (Context)
1737 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1738 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001739 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001740 return new (Context)
1741 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1742 OK_ObjCProperty, MemberLoc, BaseExpr);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001743
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001744 }
1745
1746 // Attempt to correct for typos in property names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001747 if (TypoCorrection Corrected =
1748 CorrectTypo(DeclarationNameInfo(MemberName, MemberLoc),
1749 LookupOrdinaryName, nullptr, nullptr,
1750 llvm::make_unique<DeclFilterCCC<ObjCPropertyDecl>>(),
1751 CTK_ErrorRecovery, IFace, false, OPT)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001752 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1753 << MemberName << QualType(OPT, 0));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001754 DeclarationName TypoResult = Corrected.getCorrection();
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001755 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1756 TypoResult, MemberLoc,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001757 SuperLoc, SuperType, Super);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001758 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001759 ObjCInterfaceDecl *ClassDeclared;
1760 if (ObjCIvarDecl *Ivar =
1761 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1762 QualType T = Ivar->getType();
1763 if (const ObjCObjectPointerType * OBJPT =
1764 T->getAsObjCInterfacePointerType()) {
Douglas Gregor4123a862011-11-14 22:10:01 +00001765 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001766 diag::err_property_not_as_forward_class,
1767 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001768 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001769 }
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001770 Diag(MemberLoc,
1771 diag::err_ivar_access_using_property_syntax_suggest)
1772 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1773 << FixItHint::CreateReplacement(OpLoc, "->");
1774 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001775 }
Chris Lattner90c58fa2010-04-11 07:51:10 +00001776
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001777 Diag(MemberLoc, diag::err_property_not_found)
1778 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001779 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001780 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001781 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001782 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001783}
1784
1785
1786
John McCalldadc5752010-08-24 06:29:42 +00001787ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001788ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1789 IdentifierInfo &propertyName,
1790 SourceLocation receiverNameLoc,
1791 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001792
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001793 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001794 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1795 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001796
1797 bool IsSuper = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00001798 if (!IFace) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001799 // If the "receiver" is 'super' in a method, handle it as an expression-like
1800 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001801 if (receiverNamePtr->isStr("super")) {
Douglas Gregor33823722011-06-11 01:09:30 +00001802 IsSuper = true;
1803
Eli Friedman24af8502012-02-03 22:47:37 +00001804 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001805 if (CurMethod->isInstanceMethod()) {
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00001806 ObjCInterfaceDecl *Super =
1807 CurMethod->getClassInterface()->getSuperClass();
1808 if (!Super) {
1809 // The current class does not have a superclass.
1810 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1811 << CurMethod->getClassInterface()->getIdentifier();
1812 return ExprError();
1813 }
1814 QualType T = Context.getObjCInterfaceType(Super);
Chris Lattnera36ec422010-04-11 08:28:14 +00001815 T = Context.getObjCObjectPointerType(T);
Craig Topperc3ec1492014-05-26 06:22:03 +00001816
Chris Lattnera36ec422010-04-11 08:28:14 +00001817 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001818 /*BaseExpr*/nullptr,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001819 SourceLocation()/*OpLoc*/,
1820 &propertyName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001821 propertyNameLoc,
1822 receiverNameLoc, T, true);
Chris Lattnera36ec422010-04-11 08:28:14 +00001823 }
Mike Stump11289f42009-09-09 15:08:12 +00001824
Chris Lattnera36ec422010-04-11 08:28:14 +00001825 // Otherwise, if this is a class method, try dispatching to our
1826 // superclass.
1827 IFace = CurMethod->getClassInterface()->getSuperClass();
1828 }
John McCall5f2d5562011-02-03 09:00:02 +00001829 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001830
1831 if (!IFace) {
Alp Tokerec543272013-12-24 09:48:30 +00001832 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1833 << tok::l_paren;
Chris Lattnera36ec422010-04-11 08:28:14 +00001834 return ExprError();
1835 }
1836 }
1837
1838 // Search for a declared property first.
Steve Naroff9527bbf2009-03-09 21:12:44 +00001839 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001840 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001841
1842 // If this reference is in an @implementation, check for 'private' methods.
1843 if (!Getter)
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001844 Getter = IFace->lookupPrivateClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001845
1846 if (Getter) {
1847 // FIXME: refactor/share with ActOnMemberReference().
1848 // Check if we can reference this property.
1849 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1850 return ExprError();
1851 }
Mike Stump11289f42009-09-09 15:08:12 +00001852
Steve Naroff9527bbf2009-03-09 21:12:44 +00001853 // Look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00001854 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001855 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1856 PP.getSelectorTable(),
1857 &propertyName);
Mike Stump11289f42009-09-09 15:08:12 +00001858
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001859 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001860 if (!Setter) {
1861 // If this reference is in an @implementation, also check for 'private'
1862 // methods.
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001863 Setter = IFace->lookupPrivateClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001864 }
1865 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00001866 if (!Setter)
1867 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001868
1869 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1870 return ExprError();
1871
1872 if (Getter || Setter) {
Douglas Gregor33823722011-06-11 01:09:30 +00001873 if (IsSuper)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001874 return new (Context)
1875 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1876 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
1877 Context.getObjCInterfaceType(IFace));
Douglas Gregor33823722011-06-11 01:09:30 +00001878
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001879 return new (Context) ObjCPropertyRefExpr(
1880 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
1881 propertyNameLoc, receiverNameLoc, IFace);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001882 }
1883 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1884 << &propertyName << Context.getObjCInterfaceType(IFace));
1885}
1886
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001887namespace {
1888
1889class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1890 public:
1891 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1892 // Determine whether "super" is acceptable in the current context.
1893 if (Method && Method->getClassInterface())
1894 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1895 }
1896
Craig Toppere14c0f82014-03-12 04:55:44 +00001897 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001898 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1899 candidate.isKeyword("super");
1900 }
1901};
1902
1903}
1904
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001905Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001906 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001907 SourceLocation NameLoc,
1908 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001909 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00001910 ParsedType &ReceiverType) {
1911 ReceiverType = ParsedType();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001912
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001913 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00001914 // messaging super. If the identifier is "super" and there is a
1915 // trailing dot, it's an instance message.
1916 if (IsSuper && S->isInObjcMethodScope())
1917 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001918
1919 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1920 LookupName(Result, S);
1921
1922 switch (Result.getResultKind()) {
1923 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00001924 // Normal name lookup didn't find anything. If we're in an
1925 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00001926 // FIXME: This is a hack. Ivar lookup should be part of normal
1927 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00001928 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00001929 if (!Method->getClassInterface()) {
1930 // Fall back: let the parser try to parse it as an instance message.
1931 return ObjCInstanceMessage;
1932 }
1933
Douglas Gregorca7136b2010-04-19 20:09:36 +00001934 ObjCInterfaceDecl *ClassDeclared;
1935 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1936 ClassDeclared))
1937 return ObjCInstanceMessage;
1938 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00001939
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001940 // Break out; we'll perform typo correction below.
1941 break;
1942
1943 case LookupResult::NotFoundInCurrentInstantiation:
1944 case LookupResult::FoundOverloaded:
1945 case LookupResult::FoundUnresolvedValue:
1946 case LookupResult::Ambiguous:
1947 Result.suppressDiagnostics();
1948 return ObjCInstanceMessage;
1949
1950 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00001951 // If the identifier is a class or not, and there is a trailing dot,
1952 // it's an instance message.
1953 if (HasTrailingDot)
1954 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001955 // We found something. If it's a type, then we have a class
1956 // message. Otherwise, it's an instance message.
1957 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001958 QualType T;
1959 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1960 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001961 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00001962 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001963 DiagnoseUseOfDecl(Type, NameLoc);
1964 }
1965 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00001966 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001967
Douglas Gregore5798dc2010-04-21 20:38:13 +00001968 // We have a class message, and T is the type we're
1969 // messaging. Build source-location information for it.
1970 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00001971 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00001972 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001973 }
1974 }
1975
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001976 if (TypoCorrection Corrected = CorrectTypo(
1977 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr,
1978 llvm::make_unique<ObjCInterfaceOrSuperCCC>(getCurMethodDecl()),
1979 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001980 if (Corrected.isKeyword()) {
1981 // If we've found the keyword "super" (the only keyword that would be
1982 // returned by CorrectTypo), this is a send to super.
Richard Smithf9b15102013-08-17 00:46:16 +00001983 diagnoseTypo(Corrected,
1984 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001985 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001986 } else if (ObjCInterfaceDecl *Class =
Richard Smithf9b15102013-08-17 00:46:16 +00001987 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001988 // If we found a declaration, correct when it refers to an Objective-C
1989 // class.
Richard Smithf9b15102013-08-17 00:46:16 +00001990 diagnoseTypo(Corrected,
1991 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001992 QualType T = Context.getObjCInterfaceType(Class);
1993 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1994 ReceiverType = CreateParsedType(T, TSInfo);
1995 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001996 }
1997 }
Richard Smithf9b15102013-08-17 00:46:16 +00001998
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001999 // Fall back: let the parser try to parse it as an instance message.
2000 return ObjCInstanceMessage;
2001}
Steve Naroff9527bbf2009-03-09 21:12:44 +00002002
John McCalldadc5752010-08-24 06:29:42 +00002003ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002004 SourceLocation SuperLoc,
2005 Selector Sel,
2006 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002007 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002008 SourceLocation RBracLoc,
2009 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002010 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00002011 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00002012 if (!Method) {
2013 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
2014 return ExprError();
2015 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002016
Douglas Gregor4fdba132010-04-21 20:01:04 +00002017 ObjCInterfaceDecl *Class = Method->getClassInterface();
2018 if (!Class) {
2019 Diag(SuperLoc, diag::error_no_super_class_message)
2020 << Method->getDeclName();
2021 return ExprError();
2022 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002023
Douglas Gregor4fdba132010-04-21 20:01:04 +00002024 ObjCInterfaceDecl *Super = Class->getSuperClass();
2025 if (!Super) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002026 // The current class does not have a superclass.
Ted Kremenek499897b2011-01-23 17:21:34 +00002027 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
2028 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002029 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002030 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002031
Douglas Gregor4fdba132010-04-21 20:01:04 +00002032 // We are in a method whose class has a superclass, so 'super'
2033 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00002034 if (Method->getSelector() == Sel)
2035 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00002036
Jordan Rose2afd6612012-10-19 16:05:26 +00002037 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00002038 // Since we are in an instance method, this is an instance
2039 // message to the superclass instance.
2040 QualType SuperTy = Context.getObjCInterfaceType(Super);
2041 SuperTy = Context.getObjCObjectPointerType(SuperTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00002042 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2043 Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002044 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002045 }
Douglas Gregor4fdba132010-04-21 20:01:04 +00002046
2047 // Since we are in a class method, this is a class message to
2048 // the superclass.
Craig Topperc3ec1492014-05-26 06:22:03 +00002049 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
Douglas Gregor4fdba132010-04-21 20:01:04 +00002050 Context.getObjCInterfaceType(Super),
Craig Topperc3ec1492014-05-26 06:22:03 +00002051 SuperLoc, Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002052 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002053}
2054
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002055
2056ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2057 bool isSuperReceiver,
2058 SourceLocation Loc,
2059 Selector Sel,
2060 ObjCMethodDecl *Method,
2061 MultiExprArg Args) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002062 TypeSourceInfo *receiverTypeInfo = nullptr;
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002063 if (!ReceiverType.isNull())
2064 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2065
2066 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2067 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2068 Sel, Method, Loc, Loc, Loc, Args,
2069 /*isImplicit=*/true);
2070
2071}
2072
Ted Kremeneke65b0862012-03-06 20:05:56 +00002073static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2074 unsigned DiagID,
2075 bool (*refactor)(const ObjCMessageExpr *,
2076 const NSAPI &, edit::Commit &)) {
2077 SourceLocation MsgLoc = Msg->getExprLoc();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002078 if (S.Diags.isIgnored(DiagID, MsgLoc))
Ted Kremeneke65b0862012-03-06 20:05:56 +00002079 return;
2080
2081 SourceManager &SM = S.SourceMgr;
2082 edit::Commit ECommit(SM, S.LangOpts);
2083 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2084 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2085 << Msg->getSelector() << Msg->getSourceRange();
2086 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2087 if (!ECommit.isCommitable())
2088 return;
2089 for (edit::Commit::edit_iterator
2090 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2091 const edit::Commit::Edit &Edit = *I;
2092 switch (Edit.Kind) {
2093 case edit::Commit::Act_Insert:
2094 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2095 Edit.Text,
2096 Edit.BeforePrev));
2097 break;
2098 case edit::Commit::Act_InsertFromRange:
2099 Builder.AddFixItHint(
2100 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2101 Edit.getInsertFromRange(SM),
2102 Edit.BeforePrev));
2103 break;
2104 case edit::Commit::Act_Remove:
2105 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2106 break;
2107 }
2108 }
2109 }
2110}
2111
2112static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2113 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2114 edit::rewriteObjCRedundantCallWithLiteral);
2115}
2116
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002117/// \brief Diagnose use of %s directive in an NSString which is being passed
2118/// as formatting string to formatting method.
2119static void
2120DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2121 ObjCMethodDecl *Method,
2122 Selector Sel,
2123 Expr **Args, unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002124 unsigned Idx = 0;
2125 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002126 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2127 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002128 Idx = 0;
2129 Format = true;
2130 }
2131 else if (Method) {
2132 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2133 if (S.GetFormatNSStringIdx(I, Idx)) {
2134 Format = true;
2135 break;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002136 }
2137 }
2138 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002139 if (!Format || NumArgs <= Idx)
2140 return;
2141
2142 Expr *FormatExpr = Args[Idx];
2143 if (ObjCStringLiteral *OSL =
2144 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2145 StringLiteral *FormatString = OSL->getString();
2146 if (S.FormatStringHasSArg(FormatString)) {
2147 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2148 << "%s" << 0 << 0;
2149 if (Method)
2150 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2151 << Method->getDeclName();
2152 }
2153 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002154}
2155
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002156/// \brief Build an Objective-C class message expression.
2157///
2158/// This routine takes care of both normal class messages and
2159/// class messages to the superclass.
2160///
2161/// \param ReceiverTypeInfo Type source information that describes the
2162/// receiver of this message. This may be NULL, in which case we are
2163/// sending to the superclass and \p SuperLoc must be a valid source
2164/// location.
2165
2166/// \param ReceiverType The type of the object receiving the
2167/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2168/// type as that refers to. For a superclass send, this is the type of
2169/// the superclass.
2170///
2171/// \param SuperLoc The location of the "super" keyword in a
2172/// superclass message.
2173///
2174/// \param Sel The selector to which the message is being sent.
2175///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002176/// \param Method The method that this class message is invoking, if
2177/// already known.
2178///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002179/// \param LBracLoc The location of the opening square bracket ']'.
2180///
James Dennettffad8b72012-06-22 08:10:18 +00002181/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002182///
James Dennettffad8b72012-06-22 08:10:18 +00002183/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002184ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002185 QualType ReceiverType,
2186 SourceLocation SuperLoc,
2187 Selector Sel,
2188 ObjCMethodDecl *Method,
2189 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002190 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002191 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002192 MultiExprArg ArgsIn,
2193 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002194 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002195 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002196 if (LBracLoc.isInvalid()) {
2197 Diag(Loc, diag::err_missing_open_square_message_send)
2198 << FixItHint::CreateInsertion(Loc, "[");
2199 LBracLoc = Loc;
2200 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002201 SourceLocation SelLoc;
2202 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2203 SelLoc = SelectorLocs.front();
2204 else
2205 SelLoc = Loc;
2206
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002207 if (ReceiverType->isDependentType()) {
2208 // If the receiver type is dependent, we can't type-check anything
2209 // at this point. Build a dependent expression.
2210 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002211 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002212 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002213 return ObjCMessageExpr::Create(
2214 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2215 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2216 isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002217 }
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002218
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002219 // Find the class to which we are sending this message.
Craig Topperc3ec1492014-05-26 06:22:03 +00002220 ObjCInterfaceDecl *Class = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00002221 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2222 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002223 Diag(Loc, diag::err_invalid_receiver_class_message)
2224 << ReceiverType;
2225 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002226 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002227 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002228 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002229 if (!getLangOpts().CPlusPlus)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002230 (void)DiagnoseUseOfDecl(Class, SelLoc);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002231 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002232 if (!Method) {
Douglas Gregor4123a862011-11-14 22:10:01 +00002233 SourceRange TypeRange
2234 = SuperLoc.isValid()? SourceRange(SuperLoc)
2235 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002236 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002237 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002238 ? diag::err_arc_receiver_forward_class
2239 : diag::warn_receiver_forward_class),
2240 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002241 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorb5186b12010-04-22 17:01:48 +00002242 Method = LookupFactoryMethodInGlobalPool(Sel,
2243 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002244 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002245 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2246 << Method->getDeclName();
2247 }
2248 if (!Method)
2249 Method = Class->lookupClassMethod(Sel);
2250
2251 // If we have an implementation in scope, check "private" methods.
2252 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002253 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002254
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002255 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002256 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002257 }
Mike Stump11289f42009-09-09 15:08:12 +00002258
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002259 // Check the argument types and determine the result type.
2260 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002261 ExprValueKind VK = VK_RValue;
2262
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002263 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002264 Expr **Args = ArgsIn.data();
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002265 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2266 Sel, SelectorLocs,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00002267 Method, true,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002268 SuperLoc.isValid(), LBracLoc, RBracLoc,
2269 SourceRange(),
Douglas Gregor33823722011-06-11 01:09:30 +00002270 ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002271 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002272
Alp Toker314cc812014-01-25 16:55:45 +00002273 if (Method && !Method->getReturnType()->isVoidType() &&
2274 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002275 diag::err_illegal_message_expr_incomplete_type))
2276 return ExprError();
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002277
Fariborz Jahaniane8b45502014-08-22 19:52:49 +00002278 // Warn about explicit call of +initialize on its own class. But not on 'super'.
Fariborz Jahanian42292282014-08-25 21:27:38 +00002279 if (Method && Method->getMethodFamily() == OMF_initialize) {
2280 if (!SuperLoc.isValid()) {
2281 const ObjCInterfaceDecl *ID =
2282 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2283 if (ID == Class) {
2284 Diag(Loc, diag::warn_direct_initialize_call);
2285 Diag(Method->getLocation(), diag::note_method_declared_at)
2286 << Method->getDeclName();
2287 }
2288 }
2289 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2290 // [super initialize] is allowed only within an +initialize implementation
2291 if (CurMeth->getMethodFamily() != OMF_initialize) {
2292 Diag(Loc, diag::warn_direct_super_initialize_call);
2293 Diag(Method->getLocation(), diag::note_method_declared_at)
2294 << Method->getDeclName();
2295 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2296 << CurMeth->getDeclName();
2297 }
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002298 }
2299 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002300
2301 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2302
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002303 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002304 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002305 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002306 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002307 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002308 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002309 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002310 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002311 else {
John McCall7decc9e2010-11-18 06:31:45 +00002312 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002313 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002314 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002315 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002316 if (!isImplicit)
2317 checkCocoaAPI(*this, Result);
2318 }
Douglas Gregoraae38d62010-05-22 05:17:18 +00002319 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002320}
2321
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002322// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002323// ArgExprs is optional - if it is present, the number of expressions
2324// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002325ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002326 ParsedType Receiver,
2327 Selector Sel,
2328 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002329 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002330 SourceLocation RBracLoc,
2331 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002332 TypeSourceInfo *ReceiverTypeInfo;
2333 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2334 if (ReceiverType.isNull())
2335 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002336
Mike Stump11289f42009-09-09 15:08:12 +00002337
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002338 if (!ReceiverTypeInfo)
2339 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2340
2341 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002342 /*SuperLoc=*/SourceLocation(), Sel,
2343 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2344 Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002345}
2346
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002347ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2348 QualType ReceiverType,
2349 SourceLocation Loc,
2350 Selector Sel,
2351 ObjCMethodDecl *Method,
2352 MultiExprArg Args) {
2353 return BuildInstanceMessage(Receiver, ReceiverType,
2354 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2355 Sel, Method, Loc, Loc, Loc, Args,
2356 /*isImplicit=*/true);
2357}
2358
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002359/// \brief Build an Objective-C instance message expression.
2360///
2361/// This routine takes care of both normal instance messages and
2362/// instance messages to the superclass instance.
2363///
2364/// \param Receiver The expression that computes the object that will
2365/// receive this message. This may be empty, in which case we are
2366/// sending to the superclass instance and \p SuperLoc must be a valid
2367/// source location.
2368///
2369/// \param ReceiverType The (static) type of the object receiving the
2370/// message. When a \p Receiver expression is provided, this is the
2371/// same type as that expression. For a superclass instance send, this
2372/// is a pointer to the type of the superclass.
2373///
2374/// \param SuperLoc The location of the "super" keyword in a
2375/// superclass instance message.
2376///
2377/// \param Sel The selector to which the message is being sent.
2378///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002379/// \param Method The method that this instance message is invoking, if
2380/// already known.
2381///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002382/// \param LBracLoc The location of the opening square bracket ']'.
2383///
James Dennettffad8b72012-06-22 08:10:18 +00002384/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002385///
James Dennettffad8b72012-06-22 08:10:18 +00002386/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002387ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002388 QualType ReceiverType,
2389 SourceLocation SuperLoc,
2390 Selector Sel,
2391 ObjCMethodDecl *Method,
2392 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002393 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002394 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002395 MultiExprArg ArgsIn,
2396 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002397 // The location of the receiver.
2398 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002399 SourceRange RecRange =
2400 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2401 SourceLocation SelLoc;
2402 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2403 SelLoc = SelectorLocs.front();
2404 else
2405 SelLoc = Loc;
2406
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002407 if (LBracLoc.isInvalid()) {
2408 Diag(Loc, diag::err_missing_open_square_message_send)
2409 << FixItHint::CreateInsertion(Loc, "[");
2410 LBracLoc = Loc;
2411 }
2412
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002413 // If we have a receiver expression, perform appropriate promotions
2414 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002415 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002416 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002417 ExprResult Result;
2418 if (Receiver->getType() == Context.UnknownAnyTy)
2419 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2420 else
2421 Result = CheckPlaceholderExpr(Receiver);
2422 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002423 Receiver = Result.get();
John McCall4124c492011-10-17 18:40:02 +00002424 }
2425
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002426 if (Receiver->isTypeDependent()) {
2427 // If the receiver is type-dependent, we can't type-check anything
2428 // at this point. Build a dependent expression.
2429 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002430 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002431 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002432 return ObjCMessageExpr::Create(
2433 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2434 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2435 RBracLoc, isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002436 }
2437
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002438 // If necessary, apply function/array conversion to the receiver.
2439 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002440 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2441 if (Result.isInvalid())
2442 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002443 Receiver = Result.get();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002444 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002445
2446 // If the receiver is an ObjC pointer, a block pointer, or an
2447 // __attribute__((NSObject)) pointer, we don't need to do any
2448 // special conversion in order to look up a receiver.
2449 if (ReceiverType->isObjCRetainableType()) {
2450 // do nothing
2451 } else if (!getLangOpts().ObjCAutoRefCount &&
2452 !Context.getObjCIdType().isNull() &&
2453 (ReceiverType->isPointerType() ||
2454 ReceiverType->isIntegerType())) {
2455 // Implicitly convert integers and pointers to 'id' but emit a warning.
2456 // But not in ARC.
2457 Diag(Loc, diag::warn_bad_receiver_type)
2458 << ReceiverType
2459 << Receiver->getSourceRange();
2460 if (ReceiverType->isPointerType()) {
2461 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002462 CK_CPointerToObjCPointerCast).get();
John McCall80c93a02013-03-01 09:20:14 +00002463 } else {
2464 // TODO: specialized warning on null receivers?
2465 bool IsNull = Receiver->isNullPointerConstant(Context,
2466 Expr::NPC_ValueDependentIsNull);
2467 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2468 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002469 Kind).get();
John McCall80c93a02013-03-01 09:20:14 +00002470 }
2471 ReceiverType = Receiver->getType();
2472 } else if (getLangOpts().CPlusPlus) {
Douglas Gregor4b60a152013-11-07 22:34:54 +00002473 // The receiver must be a complete type.
2474 if (RequireCompleteType(Loc, Receiver->getType(),
2475 diag::err_incomplete_receiver_type))
2476 return ExprError();
2477
John McCall80c93a02013-03-01 09:20:14 +00002478 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2479 if (result.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002480 Receiver = result.get();
John McCall80c93a02013-03-01 09:20:14 +00002481 ReceiverType = Receiver->getType();
2482 }
2483 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002484 }
2485
John McCall80c93a02013-03-01 09:20:14 +00002486 // There's a somewhat weird interaction here where we assume that we
2487 // won't actually have a method unless we also don't need to do some
2488 // of the more detailed type-checking on the receiver.
2489
Douglas Gregorb5186b12010-04-22 17:01:48 +00002490 if (!Method) {
2491 // Handle messages to id.
Fariborz Jahanian32e59ba2010-08-10 18:10:50 +00002492 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002493 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002494 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2495 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002496 SourceRange(LBracLoc, RBracLoc),
2497 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002498 if (!Method)
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002499 Method = LookupFactoryMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002500 SourceRange(LBracLoc,RBracLoc),
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002501 receiverIsId);
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002502 if (Method)
2503 if (ObjCMethodDecl *BestMethod =
Fariborz Jahaniand288fad2014-08-13 23:38:04 +00002504 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002505 Method = BestMethod;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002506 } else if (ReceiverType->isObjCClassType() ||
2507 ReceiverType->isObjCQualifiedClassType()) {
2508 // Handle messages to Class.
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002509 // We allow sending a message to a qualified Class ("Class<foo>"), which
2510 // is ok as long as one of the protocols implements the selector (if not, warn).
2511 if (const ObjCObjectPointerType *QClassTy
2512 = ReceiverType->getAsObjCQualifiedClassType()) {
2513 // Search protocols for class methods.
2514 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2515 if (!Method) {
2516 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2517 // warn if instance method found for a Class message.
2518 if (Method) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002519 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002520 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002521 Diag(Method->getLocation(), diag::note_method_declared_at)
2522 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002523 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002524 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002525 } else {
2526 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2527 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2528 // First check the public methods in the class interface.
2529 Method = ClassDecl->lookupClassMethod(Sel);
2530
2531 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002532 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002533 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002534 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002535 return ExprError();
2536 }
2537 if (!Method) {
2538 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002539 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002540 Method = LookupFactoryMethodInGlobalPool(Sel,
2541 SourceRange(LBracLoc, RBracLoc),
2542 true);
2543 if (!Method) {
2544 // If no class (factory) method was found, check if an _instance_
2545 // method of the same name exists in the root class only.
2546 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002547 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002548 true);
2549 if (Method)
2550 if (const ObjCInterfaceDecl *ID =
2551 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2552 if (ID->getSuperClass())
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002553 Diag(SelLoc, diag::warn_root_inst_method_not_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002554 << Sel << SourceRange(LBracLoc, RBracLoc);
2555 }
2556 }
Fariborz Jahaniand288fad2014-08-13 23:38:04 +00002557 if (Method)
2558 if (ObjCMethodDecl *BestMethod =
2559 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
2560 Method = BestMethod;
Douglas Gregor9a129192010-04-21 00:45:42 +00002561 }
2562 }
2563 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002564 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002565 ObjCInterfaceDecl *ClassDecl = nullptr;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002566
2567 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2568 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002569 // And as long as message is not deprecated/unavailable (warn if it is).
Douglas Gregorb5186b12010-04-22 17:01:48 +00002570 if (const ObjCObjectPointerType *QIdTy
2571 = ReceiverType->getAsObjCQualifiedIdType()) {
2572 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002573 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2574 if (!Method)
2575 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002576 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002577 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002578 } else if (const ObjCObjectPointerType *OCIType
2579 = ReceiverType->getAsObjCInterfacePointerType()) {
2580 // We allow sending a message to a pointer to an interface (an object).
2581 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002582
Douglas Gregor4123a862011-11-14 22:10:01 +00002583 // Try to complete the type. Under ARC, this is a hard error from which
2584 // we don't try to recover.
Craig Topperc3ec1492014-05-26 06:22:03 +00002585 const ObjCInterfaceDecl *forwardClass = nullptr;
Douglas Gregor4123a862011-11-14 22:10:01 +00002586 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002587 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002588 ? diag::err_arc_receiver_forward_instance
2589 : diag::warn_receiver_forward_instance,
2590 Receiver? Receiver->getSourceRange()
2591 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002592 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002593 return ExprError();
2594
2595 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanianc934de62012-02-03 01:02:44 +00002596 Diag(Receiver ? Receiver->getLocStart()
2597 : SuperLoc, diag::note_receiver_is_id);
Craig Topperc3ec1492014-05-26 06:22:03 +00002598 Method = nullptr;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002599 } else {
2600 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002601 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002602
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002603 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002604 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002605 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2606
Douglas Gregorb5186b12010-04-22 17:01:48 +00002607 if (!Method) {
2608 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002609 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002610
David Blaikiebbafb8a2012-03-11 07:00:24 +00002611 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002612 Diag(SelLoc, diag::err_arc_may_not_respond)
2613 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002614 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002615 return ExprError();
2616 }
2617
Douglas Gregor486b74e2011-09-27 16:10:05 +00002618 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002619 // If we still haven't found a method, look in the global pool. This
2620 // behavior isn't very desirable, however we need it for GCC
2621 // compatibility. FIXME: should we deviate??
2622 if (OCIType->qual_empty()) {
2623 Method = LookupInstanceMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002624 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002625 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002626 Diag(SelLoc, diag::warn_maynot_respond)
2627 << OCIType->getInterfaceDecl()->getIdentifier()
2628 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002629 }
2630 }
2631 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002632 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002633 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002634 } else {
John McCall80c93a02013-03-01 09:20:14 +00002635 // Reject other random receiver types (e.g. structs).
2636 Diag(Loc, diag::err_bad_receiver_type)
2637 << ReceiverType << Receiver->getSourceRange();
2638 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002639 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002640 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002641 }
Mike Stump11289f42009-09-09 15:08:12 +00002642
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002643 FunctionScopeInfo *DIFunctionScopeInfo =
2644 (Method && Method->getMethodFamily() == OMF_init)
Craig Topperc3ec1492014-05-26 06:22:03 +00002645 ? getEnclosingFunction() : nullptr;
2646
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002647 if (DIFunctionScopeInfo &&
2648 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002649 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2650 bool isDesignatedInitChain = false;
2651 if (SuperLoc.isValid()) {
2652 if (const ObjCObjectPointerType *
2653 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2654 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
Argyrios Kyrtzidisd664a342013-12-13 03:48:17 +00002655 // Either we know this is a designated initializer or we
2656 // conservatively assume it because we don't know for sure.
2657 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2658 ID->isDesignatedInitializer(Sel)) {
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002659 isDesignatedInitChain = true;
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002660 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002661 }
2662 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002663 }
2664 }
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002665 if (!isDesignatedInitChain) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002666 const ObjCMethodDecl *InitMethod = nullptr;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002667 bool isDesignated =
2668 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2669 assert(isDesignated && InitMethod);
2670 (void)isDesignated;
2671 Diag(SelLoc, SuperLoc.isValid() ?
2672 diag::warn_objc_designated_init_non_designated_init_call :
2673 diag::warn_objc_designated_init_non_super_designated_init_call);
2674 Diag(InitMethod->getLocation(),
2675 diag::note_objc_designated_init_marked_here);
2676 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002677 }
2678
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002679 if (DIFunctionScopeInfo &&
2680 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002681 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2682 if (SuperLoc.isValid()) {
2683 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2684 } else {
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002685 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002686 }
2687 }
2688
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002689 // Check the message arguments.
2690 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002691 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002692 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002693 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00002694 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2695 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002696 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2697 Sel, SelectorLocs, Method,
Douglas Gregor33823722011-06-11 01:09:30 +00002698 ClassMessage, SuperLoc.isValid(),
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002699 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002700 return ExprError();
Alp Toker314cc812014-01-25 16:55:45 +00002701
2702 if (Method && !Method->getReturnType()->isVoidType() &&
2703 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002704 diag::err_illegal_message_expr_incomplete_type))
2705 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00002706
John McCall31168b02011-06-15 23:02:42 +00002707 // In ARC, forbid the user from sending messages to
2708 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002709 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002710 ObjCMethodFamily family =
2711 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2712 switch (family) {
2713 case OMF_init:
2714 if (Method)
2715 checkInitMethod(Method, ReceiverType);
2716
2717 case OMF_None:
2718 case OMF_alloc:
2719 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00002720 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002721 case OMF_mutableCopy:
2722 case OMF_new:
2723 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002724 case OMF_initialize:
John McCall31168b02011-06-15 23:02:42 +00002725 break;
2726
2727 case OMF_dealloc:
2728 case OMF_retain:
2729 case OMF_release:
2730 case OMF_autorelease:
2731 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002732 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2733 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00002734 break;
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002735
2736 case OMF_performSelector:
2737 if (Method && NumArgs >= 1) {
2738 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2739 Selector ArgSel = SelExp->getSelector();
2740 ObjCMethodDecl *SelMethod =
2741 LookupInstanceMethodInGlobalPool(ArgSel,
2742 SelExp->getSourceRange());
2743 if (!SelMethod)
2744 SelMethod =
2745 LookupFactoryMethodInGlobalPool(ArgSel,
2746 SelExp->getSourceRange());
2747 if (SelMethod) {
2748 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2749 switch (SelFamily) {
2750 case OMF_alloc:
2751 case OMF_copy:
2752 case OMF_mutableCopy:
2753 case OMF_new:
2754 case OMF_self:
2755 case OMF_init:
2756 // Issue error, unless ns_returns_not_retained.
2757 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2758 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002759 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002760 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002761 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2762 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002763 }
2764 break;
2765 default:
2766 // +0 call. OK. unless ns_returns_retained.
2767 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2768 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002769 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002770 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002771 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2772 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002773 }
2774 break;
2775 }
2776 }
2777 } else {
2778 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002779 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002780 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2781 }
2782 }
2783 break;
John McCall31168b02011-06-15 23:02:42 +00002784 }
2785 }
2786
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002787 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2788
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002789 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00002790 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002791 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002792 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002793 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002794 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002795 makeArrayRef(Args, NumArgs), RBracLoc,
2796 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002797 else {
John McCall7decc9e2010-11-18 06:31:45 +00002798 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002799 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002800 makeArrayRef(Args, NumArgs), RBracLoc,
2801 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002802 if (!isImplicit)
2803 checkCocoaAPI(*this, Result);
2804 }
John McCall31168b02011-06-15 23:02:42 +00002805
David Blaikiebbafb8a2012-03-11 07:00:24 +00002806 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahanian9277ff42014-06-17 23:35:13 +00002807 // Do not warn about IBOutlet weak property receivers being set to null
2808 // as this cannot asynchronously happen.
2809 bool WarnWeakReceiver = true;
2810 if (isImplicit && Method)
2811 if (const ObjCPropertyDecl *PropertyDecl = Method->findPropertyDecl())
2812 WarnWeakReceiver = !PropertyDecl->hasAttr<IBOutletAttr>();
2813 if (WarnWeakReceiver)
2814 DiagnoseARCUseOfWeakReceiver(*this, Receiver);
Fariborz Jahanian6bd22262012-04-04 20:05:25 +00002815
John McCall31168b02011-06-15 23:02:42 +00002816 // In ARC, annotate delegate init calls.
2817 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00002818 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00002819 // Only consider init calls *directly* in init implementations,
2820 // not within blocks.
2821 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2822 if (method && method->getMethodFamily() == OMF_init) {
2823 // The implicit assignment to self means we also don't want to
2824 // consume the result.
2825 Result->setDelegateInitCall(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002826 return Result;
John McCall31168b02011-06-15 23:02:42 +00002827 }
2828 }
2829
2830 // In ARC, check for message sends which are likely to introduce
2831 // retain cycles.
2832 checkRetainCycles(Result);
Jordan Rose22487652012-10-11 16:06:21 +00002833
2834 if (!isImplicit && Method) {
2835 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2836 bool IsWeak =
2837 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2838 if (!IsWeak && Sel.isUnarySelector())
2839 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002840 if (IsWeak &&
2841 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
2842 getCurFunction()->recordUseOfWeak(Result, Prop);
Jordan Rose22487652012-10-11 16:06:21 +00002843 }
2844 }
John McCall31168b02011-06-15 23:02:42 +00002845 }
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00002846
Douglas Gregoraae38d62010-05-22 05:17:18 +00002847 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002848}
2849
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002850static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2851 if (ObjCSelectorExpr *OSE =
2852 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2853 Selector Sel = OSE->getSelector();
2854 SourceLocation Loc = OSE->getAtLoc();
2855 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
2856 = S.ReferencedSelectors.find(Sel);
2857 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
2858 S.ReferencedSelectors.erase(Pos);
2859 }
2860}
2861
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002862// ActOnInstanceMessage - used for both unary and keyword messages.
2863// ArgExprs is optional - if it is present, the number of expressions
2864// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002865ExprResult Sema::ActOnInstanceMessage(Scope *S,
2866 Expr *Receiver,
2867 Selector Sel,
2868 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002869 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00002870 SourceLocation RBracLoc,
2871 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002872 if (!Receiver)
2873 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002874
2875 // A ParenListExpr can show up while doing error recovery with invalid code.
2876 if (isa<ParenListExpr>(Receiver)) {
2877 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
2878 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002879 Receiver = Result.get();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002880 }
Fariborz Jahanian17748062013-01-22 19:05:17 +00002881
2882 if (RespondsToSelectorSel.isNull()) {
2883 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
2884 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
2885 }
2886 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002887 RemoveSelectorFromWarningCache(*this, Args[0]);
Craig Topperc3ec1492014-05-26 06:22:03 +00002888
John McCallb268a282010-08-23 23:25:46 +00002889 return BuildInstanceMessage(Receiver, Receiver->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002890 /*SuperLoc=*/SourceLocation(), Sel,
2891 /*Method=*/nullptr, LBracLoc, SelectorLocs,
2892 RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002893}
Chris Lattner2a3569b2008-04-07 05:30:13 +00002894
John McCall31168b02011-06-15 23:02:42 +00002895enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00002896 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00002897 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00002898
2899 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00002900 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00002901
2902 /// id*, id***, void (^*)(),
2903 ACTC_indirectRetainable,
2904
2905 /// void* might be a normal C type, or it might a CF type.
2906 ACTC_voidPtr,
2907
2908 /// struct A*
2909 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00002910};
John McCalle4fe2452011-10-01 01:01:08 +00002911static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2912 return (ACTC == ACTC_retainable ||
2913 ACTC == ACTC_coreFoundation ||
2914 ACTC == ACTC_voidPtr);
2915}
2916static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2917 return ACTC == ACTC_none ||
2918 ACTC == ACTC_voidPtr ||
2919 ACTC == ACTC_coreFoundation;
2920}
2921
John McCall31168b02011-06-15 23:02:42 +00002922static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00002923 bool isIndirect = false;
John McCall31168b02011-06-15 23:02:42 +00002924
2925 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00002926 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00002927 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002928 isIndirect = true;
2929 }
John McCall31168b02011-06-15 23:02:42 +00002930
2931 // Drill through pointers and arrays recursively.
2932 while (true) {
2933 if (const PointerType *ptr = type->getAs<PointerType>()) {
2934 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002935
2936 // The first level of pointer may be the innermost pointer on a CF type.
2937 if (!isIndirect) {
2938 if (type->isVoidType()) return ACTC_voidPtr;
2939 if (type->isRecordType()) return ACTC_coreFoundation;
2940 }
John McCall31168b02011-06-15 23:02:42 +00002941 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2942 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2943 } else {
2944 break;
2945 }
John McCalle4fe2452011-10-01 01:01:08 +00002946 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00002947 }
2948
John McCalle4fe2452011-10-01 01:01:08 +00002949 if (isIndirect) {
2950 if (type->isObjCARCBridgableType())
2951 return ACTC_indirectRetainable;
2952 return ACTC_none;
2953 }
2954
2955 if (type->isObjCARCBridgableType())
2956 return ACTC_retainable;
2957
2958 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00002959}
2960
2961namespace {
John McCalle4fe2452011-10-01 01:01:08 +00002962 /// A result from the cast checker.
2963 enum ACCResult {
2964 /// Cannot be casted.
2965 ACC_invalid,
2966
2967 /// Can be safely retained or not retained.
2968 ACC_bottom,
2969
2970 /// Can be casted at +0.
2971 ACC_plusZero,
2972
2973 /// Can be casted at +1.
2974 ACC_plusOne
2975 };
2976 ACCResult merge(ACCResult left, ACCResult right) {
2977 if (left == right) return left;
2978 if (left == ACC_bottom) return right;
2979 if (right == ACC_bottom) return left;
2980 return ACC_invalid;
2981 }
2982
2983 /// A checker which white-lists certain expressions whose conversion
2984 /// to or from retainable type would otherwise be forbidden in ARC.
2985 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2986 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2987
John McCall31168b02011-06-15 23:02:42 +00002988 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00002989 ARCConversionTypeClass SourceClass;
2990 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002991 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00002992
2993 static bool isCFType(QualType type) {
2994 // Someday this can use ns_bridged. For now, it has to do this.
2995 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00002996 }
John McCalle4fe2452011-10-01 01:01:08 +00002997
2998 public:
2999 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003000 ARCConversionTypeClass target, bool diagnose)
3001 : Context(Context), SourceClass(source), TargetClass(target),
3002 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00003003
3004 using super::Visit;
3005 ACCResult Visit(Expr *e) {
3006 return super::Visit(e->IgnoreParens());
3007 }
3008
3009 ACCResult VisitStmt(Stmt *s) {
3010 return ACC_invalid;
3011 }
3012
3013 /// Null pointer constants can be casted however you please.
3014 ACCResult VisitExpr(Expr *e) {
3015 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
3016 return ACC_bottom;
3017 return ACC_invalid;
3018 }
3019
3020 /// Objective-C string literals can be safely casted.
3021 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3022 // If we're casting to any retainable type, go ahead. Global
3023 // strings are immune to retains, so this is bottom.
3024 if (isAnyRetainable(TargetClass)) return ACC_bottom;
3025
3026 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00003027 }
3028
John McCalle4fe2452011-10-01 01:01:08 +00003029 /// Look through certain implicit and explicit casts.
3030 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003031 switch (e->getCastKind()) {
3032 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00003033 return ACC_bottom;
3034
John McCall31168b02011-06-15 23:02:42 +00003035 case CK_NoOp:
3036 case CK_LValueToRValue:
3037 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00003038 case CK_CPointerToObjCPointerCast:
3039 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00003040 case CK_AnyPointerToBlockPointerCast:
3041 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00003042
John McCall31168b02011-06-15 23:02:42 +00003043 default:
John McCalle4fe2452011-10-01 01:01:08 +00003044 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00003045 }
3046 }
John McCalle4fe2452011-10-01 01:01:08 +00003047
3048 /// Look through unary extension.
3049 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003050 return Visit(e->getSubExpr());
3051 }
John McCalle4fe2452011-10-01 01:01:08 +00003052
3053 /// Ignore the LHS of a comma operator.
3054 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003055 return Visit(e->getRHS());
3056 }
John McCalle4fe2452011-10-01 01:01:08 +00003057
3058 /// Conditional operators are okay if both sides are okay.
3059 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3060 ACCResult left = Visit(e->getTrueExpr());
3061 if (left == ACC_invalid) return ACC_invalid;
3062 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00003063 }
John McCalle4fe2452011-10-01 01:01:08 +00003064
John McCallfe96e0b2011-11-06 09:01:30 +00003065 /// Look through pseudo-objects.
3066 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3067 // If we're getting here, we should always have a result.
3068 return Visit(e->getResultExpr());
3069 }
3070
John McCalle4fe2452011-10-01 01:01:08 +00003071 /// Statement expressions are okay if their result expression is okay.
3072 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003073 return Visit(e->getSubStmt()->body_back());
3074 }
John McCall31168b02011-06-15 23:02:42 +00003075
John McCalle4fe2452011-10-01 01:01:08 +00003076 /// Some declaration references are okay.
3077 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
3078 // References to global constants from system headers are okay.
3079 // These are things like 'kCFStringTransformToLatin'. They are
3080 // can also be assumed to be immune to retains.
3081 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
3082 if (isAnyRetainable(TargetClass) &&
3083 isAnyRetainable(SourceClass) &&
3084 var &&
3085 var->getStorageClass() == SC_Extern &&
3086 var->getType().isConstQualified() &&
3087 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
3088 return ACC_bottom;
3089 }
3090
3091 // Nothing else.
3092 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00003093 }
John McCalle4fe2452011-10-01 01:01:08 +00003094
3095 /// Some calls are okay.
3096 ACCResult VisitCallExpr(CallExpr *e) {
3097 if (FunctionDecl *fn = e->getDirectCallee())
3098 if (ACCResult result = checkCallToFunction(fn))
3099 return result;
3100
3101 return super::VisitCallExpr(e);
3102 }
3103
3104 ACCResult checkCallToFunction(FunctionDecl *fn) {
3105 // Require a CF*Ref return type.
Alp Toker314cc812014-01-25 16:55:45 +00003106 if (!isCFType(fn->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003107 return ACC_invalid;
3108
3109 if (!isAnyRetainable(TargetClass))
3110 return ACC_invalid;
3111
3112 // Honor an explicit 'not retained' attribute.
3113 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3114 return ACC_plusZero;
3115
3116 // Honor an explicit 'retained' attribute, except that for
3117 // now we're not going to permit implicit handling of +1 results,
3118 // because it's a bit frightening.
3119 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003120 return Diagnose ? ACC_plusOne
3121 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003122
3123 // Recognize this specific builtin function, which is used by CFSTR.
3124 unsigned builtinID = fn->getBuiltinID();
3125 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3126 return ACC_bottom;
3127
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003128 // Otherwise, don't do anything implicit with an unaudited function.
3129 if (!fn->hasAttr<CFAuditedTransferAttr>())
3130 return ACC_invalid;
3131
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003132 // Otherwise, it's +0 unless it follows the create convention.
3133 if (ento::coreFoundation::followsCreateRule(fn))
3134 return Diagnose ? ACC_plusOne
3135 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003136
John McCalle4fe2452011-10-01 01:01:08 +00003137 return ACC_plusZero;
3138 }
3139
3140 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3141 return checkCallToMethod(e->getMethodDecl());
3142 }
3143
3144 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3145 ObjCMethodDecl *method;
3146 if (e->isExplicitProperty())
3147 method = e->getExplicitProperty()->getGetterMethodDecl();
3148 else
3149 method = e->getImplicitPropertyGetter();
3150 return checkCallToMethod(method);
3151 }
3152
3153 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3154 if (!method) return ACC_invalid;
3155
3156 // Check for message sends to functions returning CF types. We
3157 // just obey the Cocoa conventions with these, even though the
3158 // return type is CF.
Alp Toker314cc812014-01-25 16:55:45 +00003159 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003160 return ACC_invalid;
3161
3162 // If the method is explicitly marked not-retained, it's +0.
3163 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3164 return ACC_plusZero;
3165
3166 // If the method is explicitly marked as returning retained, or its
3167 // selector follows a +1 Cocoa convention, treat it as +1.
3168 if (method->hasAttr<CFReturnsRetainedAttr>())
3169 return ACC_plusOne;
3170
3171 switch (method->getSelector().getMethodFamily()) {
3172 case OMF_alloc:
3173 case OMF_copy:
3174 case OMF_mutableCopy:
3175 case OMF_new:
3176 return ACC_plusOne;
3177
3178 default:
3179 // Otherwise, treat it as +0.
3180 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00003181 }
3182 }
John McCalle4fe2452011-10-01 01:01:08 +00003183 };
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00003184}
3185
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003186bool Sema::isKnownName(StringRef name) {
3187 if (name.empty())
3188 return false;
3189 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003190 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003191 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003192}
3193
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003194static void addFixitForObjCARCConversion(Sema &S,
3195 DiagnosticBuilder &DiagB,
3196 Sema::CheckedConversionKind CCK,
3197 SourceLocation afterLParen,
3198 QualType castType,
3199 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003200 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003201 const char *bridgeKeyword,
3202 const char *CFBridgeName) {
3203 // We handle C-style and implicit casts here.
3204 switch (CCK) {
3205 case Sema::CCK_ImplicitConversion:
3206 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003207 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003208 break;
3209 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003210 return;
3211 }
3212
3213 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003214 if (CCK == Sema::CCK_OtherCast) {
3215 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3216 SourceRange range(NCE->getOperatorLoc(),
3217 NCE->getAngleBrackets().getEnd());
3218 SmallString<32> BridgeCall;
3219
3220 SourceManager &SM = S.getSourceManager();
3221 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3222 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3223 BridgeCall += ' ';
3224
3225 BridgeCall += CFBridgeName;
3226 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3227 }
3228 return;
3229 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003230 Expr *castedE = castExpr;
3231 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3232 castedE = CCE->getSubExpr();
3233 castedE = castedE->IgnoreImpCasts();
3234 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00003235
3236 SmallString<32> BridgeCall;
3237
3238 SourceManager &SM = S.getSourceManager();
3239 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3240 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3241 BridgeCall += ' ';
3242
3243 BridgeCall += CFBridgeName;
3244
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003245 if (isa<ParenExpr>(castedE)) {
3246 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003247 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003248 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00003249 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003250 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003251 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003252 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3253 S.PP.getLocForEndOfToken(range.getEnd()),
3254 ")"));
3255 }
3256 return;
3257 }
3258
3259 if (CCK == Sema::CCK_CStyleCast) {
3260 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003261 } else if (CCK == Sema::CCK_OtherCast) {
3262 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3263 std::string castCode = "(";
3264 castCode += bridgeKeyword;
3265 castCode += castType.getAsString();
3266 castCode += ")";
3267 SourceRange Range(NCE->getOperatorLoc(),
3268 NCE->getAngleBrackets().getEnd());
3269 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3270 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003271 } else {
3272 std::string castCode = "(";
3273 castCode += bridgeKeyword;
3274 castCode += castType.getAsString();
3275 castCode += ")";
3276 Expr *castedE = castExpr->IgnoreImpCasts();
3277 SourceRange range = castedE->getSourceRange();
3278 if (isa<ParenExpr>(castedE)) {
3279 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3280 castCode));
3281 } else {
3282 castCode += "(";
3283 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3284 castCode));
3285 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3286 S.PP.getLocForEndOfToken(range.getEnd()),
3287 ")"));
3288 }
3289 }
3290}
3291
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003292template <typename T>
3293static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3294 TypedefNameDecl *TDNDecl = TD->getDecl();
3295 QualType QT = TDNDecl->getUnderlyingType();
3296 if (QT->isPointerType()) {
3297 QT = QT->getPointeeType();
3298 if (const RecordType *RT = QT->getAs<RecordType>())
Fariborz Jahanian9af6a782014-06-11 19:10:46 +00003299 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
Aaron Ballman2084f8f2013-12-19 13:20:36 +00003300 return RD->getAttr<T>();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003301 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003302 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003303}
3304
3305static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3306 TypedefNameDecl *&TDNDecl) {
3307 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3308 TDNDecl = TD->getDecl();
3309 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3310 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3311 return ObjCBAttr;
3312 T = TDNDecl->getUnderlyingType();
3313 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003314 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003315}
3316
John McCall4124c492011-10-17 18:40:02 +00003317static void
3318diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3319 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003320 Expr *castExpr, Expr *realCast,
3321 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003322 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003323 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003324 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00003325
John McCall4124c492011-10-17 18:40:02 +00003326 if (S.makeUnavailableInSystemHeader(loc,
John McCalle4fe2452011-10-01 01:01:08 +00003327 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCall31168b02011-06-15 23:02:42 +00003328 return;
John McCall4124c492011-10-17 18:40:02 +00003329
3330 QualType castExprType = castExpr->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003331 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003332 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3333 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3334 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
Fariborz Jahanian1ad83a32014-06-18 23:22:38 +00003335 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003336 return;
John McCall31168b02011-06-15 23:02:42 +00003337
John McCall640767f2011-06-17 06:50:50 +00003338 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003339 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003340 case ACTC_none:
3341 case ACTC_coreFoundation:
3342 case ACTC_voidPtr:
3343 srcKind = (castExprType->isPointerType() ? 1 : 0);
3344 break;
3345 case ACTC_retainable:
3346 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3347 break;
3348 case ACTC_indirectRetainable:
3349 srcKind = 4;
3350 break;
John McCall31168b02011-06-15 23:02:42 +00003351 }
3352
John McCall4124c492011-10-17 18:40:02 +00003353 // Check whether this could be fixed with a bridge cast.
3354 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3355 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003356
John McCall4124c492011-10-17 18:40:02 +00003357 // Bridge from an ARC type to a CF type.
3358 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003359
John McCall4124c492011-10-17 18:40:02 +00003360 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3361 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3362 << 2 // of C pointer type
3363 << castExprType
3364 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3365 << castType
3366 << castRange
3367 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003368 bool br = S.isKnownName("CFBridgingRelease");
Jordan Rose4502b532012-07-31 01:07:43 +00003369 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003370 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003371 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003372 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003373 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003374 DiagnosticBuilder DiagB =
3375 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3376 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Craig Topperc3ec1492014-05-26 06:22:03 +00003377
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003378 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003379 castType, castExpr, realCast, "__bridge ",
3380 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003381 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003382 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003383 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003384 DiagnosticBuilder DiagB =
3385 (CCK == Sema::CCK_OtherCast && !br) ?
3386 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3387 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3388 diag::note_arc_bridge_transfer)
3389 << castExprType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003390
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003391 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003392 castType, castExpr, realCast, "__bridge_transfer ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003393 br ? "CFBridgingRelease" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003394 }
John McCall4124c492011-10-17 18:40:02 +00003395
3396 return;
3397 }
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003398
John McCall4124c492011-10-17 18:40:02 +00003399 // Bridge from a CF type to an ARC type.
3400 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003401 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003402 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3403 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3404 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3405 << castExprType
3406 << 2 // to C pointer type
3407 << castType
3408 << castRange
3409 << castExpr->getSourceRange();
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003410 ACCResult CreateRule =
3411 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003412 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003413 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003414 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003415 DiagnosticBuilder DiagB =
3416 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3417 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003418 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003419 castType, castExpr, realCast, "__bridge ",
3420 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003421 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003422 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003423 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003424 DiagnosticBuilder DiagB =
3425 (CCK == Sema::CCK_OtherCast && !br) ?
3426 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3427 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3428 diag::note_arc_bridge_retained)
3429 << castType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003430
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003431 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003432 castType, castExpr, realCast, "__bridge_retained ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003433 br ? "CFBridgingRetain" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003434 }
John McCall4124c492011-10-17 18:40:02 +00003435
3436 return;
John McCall31168b02011-06-15 23:02:42 +00003437 }
3438
John McCall4124c492011-10-17 18:40:02 +00003439 S.Diag(loc, diag::err_arc_mismatched_cast)
3440 << (CCK != Sema::CCK_ImplicitConversion)
3441 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003442 << castRange << castExpr->getSourceRange();
3443}
3444
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003445template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003446static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3447 bool &HadTheAttribute, bool warn) {
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003448 QualType T = castExpr->getType();
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003449 HadTheAttribute = false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003450 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3451 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003452 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003453 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003454 HadTheAttribute = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003455 NamedDecl *Target = nullptr;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003456 // Check for an existing type with this name.
3457 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3458 Sema::LookupOrdinaryName);
3459 if (S.LookupName(R, S.TUScope)) {
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003460 Target = R.getFoundDecl();
3461 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3462 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3463 if (const ObjCObjectPointerType *InterfacePointerType =
3464 castType->getAsObjCInterfacePointerType()) {
3465 ObjCInterfaceDecl *CastClass
3466 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003467 if ((CastClass == ExprClass) ||
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003468 (CastClass && ExprClass->isSuperClassOf(CastClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003469 return true;
3470 if (warn)
3471 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3472 << T << Target->getName() << castType->getPointeeType();
3473 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003474 } else if (castType->isObjCIdType() ||
3475 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3476 castType, ExprClass)))
3477 // ok to cast to 'id'.
3478 // casting to id<p-list> is ok if bridge type adopts all of
3479 // p-list protocols.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003480 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003481 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003482 if (warn) {
3483 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3484 << T << Target->getName() << castType;
3485 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3486 S.Diag(Target->getLocStart(), diag::note_declared_at);
3487 }
3488 return false;
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003489 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003490 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003491 }
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003492 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
Aaron Ballmanc0550742014-01-03 02:07:43 +00003493 << castExpr->getType() << Parm;
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003494 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3495 if (Target)
3496 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003497 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003498 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003499 return false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003500 }
3501 T = TDNDecl->getUnderlyingType();
3502 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003503 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003504}
3505
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003506template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003507static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3508 bool &HadTheAttribute, bool warn) {
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003509 QualType T = castType;
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003510 HadTheAttribute = false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003511 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3512 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003513 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003514 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003515 HadTheAttribute = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003516 NamedDecl *Target = nullptr;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003517 // Check for an existing type with this name.
3518 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3519 Sema::LookupOrdinaryName);
3520 if (S.LookupName(R, S.TUScope)) {
3521 Target = R.getFoundDecl();
3522 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3523 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3524 if (const ObjCObjectPointerType *InterfacePointerType =
3525 castExpr->getType()->getAsObjCInterfacePointerType()) {
3526 ObjCInterfaceDecl *ExprClass
3527 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003528 if ((CastClass == ExprClass) ||
3529 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003530 return true;
3531 if (warn) {
3532 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3533 << castExpr->getType()->getPointeeType() << T;
3534 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3535 }
3536 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003537 } else if (castExpr->getType()->isObjCIdType() ||
3538 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3539 castExpr->getType(), CastClass)))
3540 // ok to cast an 'id' expression to a CFtype.
3541 // ok to cast an 'id<plist>' expression to CFtype provided plist
3542 // adopts all of CFtype's ObjetiveC's class plist.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003543 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003544 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003545 if (warn) {
3546 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3547 << castExpr->getType() << castType;
3548 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3549 S.Diag(Target->getLocStart(), diag::note_declared_at);
3550 }
3551 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003552 }
3553 }
3554 }
3555 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3556 << castExpr->getType() << castType;
3557 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3558 if (Target)
3559 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003560 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003561 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003562 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003563 }
3564 T = TDNDecl->getUnderlyingType();
3565 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003566 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003567}
3568
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003569void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003570 if (!getLangOpts().ObjC1)
3571 return;
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003572 // warn in presence of __bridge casting to or from a toll free bridge cast.
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003573 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3574 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003575 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003576 bool HasObjCBridgeAttr;
3577 bool ObjCBridgeAttrWillNotWarn =
3578 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3579 false);
3580 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3581 return;
3582 bool HasObjCBridgeMutableAttr;
3583 bool ObjCBridgeMutableAttrWillNotWarn =
3584 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3585 HasObjCBridgeMutableAttr, false);
3586 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3587 return;
3588
3589 if (HasObjCBridgeAttr)
3590 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3591 true);
3592 else if (HasObjCBridgeMutableAttr)
3593 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3594 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003595 }
3596 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003597 bool HasObjCBridgeAttr;
3598 bool ObjCBridgeAttrWillNotWarn =
3599 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3600 false);
3601 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3602 return;
3603 bool HasObjCBridgeMutableAttr;
3604 bool ObjCBridgeMutableAttrWillNotWarn =
3605 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3606 HasObjCBridgeMutableAttr, false);
3607 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3608 return;
3609
3610 if (HasObjCBridgeAttr)
3611 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3612 true);
3613 else if (HasObjCBridgeMutableAttr)
3614 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3615 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003616 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003617}
3618
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003619void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3620 QualType SrcType = castExpr->getType();
3621 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3622 if (PRE->isExplicitProperty()) {
3623 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3624 SrcType = PDecl->getType();
3625 }
3626 else if (PRE->isImplicitProperty()) {
3627 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3628 SrcType = Getter->getReturnType();
3629
3630 }
3631 }
3632
3633 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3634 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3635 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3636 return;
3637 CheckObjCBridgeRelatedConversions(castExpr->getLocStart(),
3638 castType, SrcType, castExpr);
3639 return;
3640}
3641
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00003642bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3643 CastKind &Kind) {
3644 if (!getLangOpts().ObjC1)
3645 return false;
3646 ARCConversionTypeClass exprACTC =
3647 classifyTypeForARCConversion(castExpr->getType());
3648 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3649 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3650 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3651 CheckTollFreeBridgeCast(castType, castExpr);
3652 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3653 : CK_CPointerToObjCPointerCast;
3654 return true;
3655 }
3656 return false;
3657}
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003658
3659bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3660 QualType DestType, QualType SrcType,
3661 ObjCInterfaceDecl *&RelatedClass,
3662 ObjCMethodDecl *&ClassMethod,
3663 ObjCMethodDecl *&InstanceMethod,
3664 TypedefNameDecl *&TDNDecl,
3665 bool CfToNs) {
3666 QualType T = CfToNs ? SrcType : DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003667 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3668 if (!ObjCBAttr)
3669 return false;
3670
3671 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3672 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3673 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3674 if (!RCId)
3675 return false;
Craig Topperc3ec1492014-05-26 06:22:03 +00003676 NamedDecl *Target = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003677 // Check for an existing type with this name.
3678 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3679 Sema::LookupOrdinaryName);
3680 if (!LookupName(R, TUScope)) {
3681 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003682 << SrcType << DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003683 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3684 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003685 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003686 Target = R.getFoundDecl();
3687 if (Target && isa<ObjCInterfaceDecl>(Target))
3688 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3689 else {
3690 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3691 << SrcType << DestType;
3692 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3693 if (Target)
3694 Diag(Target->getLocStart(), diag::note_declared_at);
3695 return false;
3696 }
3697
3698 // Check for an existing class method with the given selector name.
3699 if (CfToNs && CMId) {
3700 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3701 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3702 if (!ClassMethod) {
3703 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003704 << SrcType << DestType << Sel << false;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003705 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3706 return false;
3707 }
3708 }
3709
3710 // Check for an existing instance method with the given selector name.
3711 if (!CfToNs && IMId) {
3712 Selector Sel = Context.Selectors.getNullarySelector(IMId);
3713 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3714 if (!InstanceMethod) {
3715 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003716 << SrcType << DestType << Sel << true;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003717 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3718 return false;
3719 }
3720 }
3721 return true;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003722}
3723
3724bool
3725Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003726 QualType DestType, QualType SrcType,
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003727 Expr *&SrcExpr) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003728 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3729 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3730 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3731 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3732 if (!CfToNs && !NsToCf)
3733 return false;
3734
3735 ObjCInterfaceDecl *RelatedClass;
Craig Topperc3ec1492014-05-26 06:22:03 +00003736 ObjCMethodDecl *ClassMethod = nullptr;
3737 ObjCMethodDecl *InstanceMethod = nullptr;
3738 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003739 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
3740 ClassMethod, InstanceMethod, TDNDecl, CfToNs))
3741 return false;
3742
3743 if (CfToNs) {
3744 // Implicit conversion from CF to ObjC object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003745 if (ClassMethod) {
3746 std::string ExpressionString = "[";
3747 ExpressionString += RelatedClass->getNameAsString();
3748 ExpressionString += " ";
3749 ExpressionString += ClassMethod->getSelector().getAsString();
3750 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3751 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003752 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003753 << SrcType << DestType << ClassMethod->getSelector() << false
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003754 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3755 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003756 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3757 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3758
3759 QualType receiverType =
3760 Context.getObjCInterfaceType(RelatedClass);
3761 // Argument.
3762 Expr *args[] = { SrcExpr };
3763 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
3764 ClassMethod->getLocation(),
3765 ClassMethod->getSelector(), ClassMethod,
3766 MultiExprArg(args, 1));
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003767 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003768 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003769 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003770 }
3771 else {
3772 // Implicit conversion from ObjC type to CF object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003773 if (InstanceMethod) {
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003774 std::string ExpressionString;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003775 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003776 if (InstanceMethod->isPropertyAccessor())
3777 if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
3778 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
3779 ExpressionString = ".";
3780 ExpressionString += PDecl->getNameAsString();
3781 Diag(Loc, diag::err_objc_bridged_related_known_method)
3782 << SrcType << DestType << InstanceMethod->getSelector() << true
3783 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3784 }
3785 if (ExpressionString.empty()) {
3786 // Provide a fixit: [ObjectExpr InstanceMethod]
3787 ExpressionString = " ";
3788 ExpressionString += InstanceMethod->getSelector().getAsString();
3789 ExpressionString += "]";
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003790
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003791 Diag(Loc, diag::err_objc_bridged_related_known_method)
3792 << SrcType << DestType << InstanceMethod->getSelector() << true
3793 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3794 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3795 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003796 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3797 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3798
3799 ExprResult msg =
3800 BuildInstanceMessageImplicit(SrcExpr, SrcType,
3801 InstanceMethod->getLocation(),
3802 InstanceMethod->getSelector(),
3803 InstanceMethod, None);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003804 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003805 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003806 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003807 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003808 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003809}
3810
John McCall4124c492011-10-17 18:40:02 +00003811Sema::ARCConversionResult
3812Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003813 Expr *&castExpr, CheckedConversionKind CCK,
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00003814 bool DiagnoseCFAudited,
3815 BinaryOperatorKind Opc) {
John McCall4124c492011-10-17 18:40:02 +00003816 QualType castExprType = castExpr->getType();
3817
3818 // For the purposes of the classification, we assume reference types
3819 // will bind to temporaries.
3820 QualType effCastType = castType;
3821 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3822 effCastType = ref->getPointeeType();
3823
3824 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3825 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003826 if (exprACTC == castACTC) {
3827 // check for viablity and report error if casting an rvalue to a
3828 // life-time qualifier.
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003829 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003830 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003831 (castType != castExprType)) {
3832 const Type *DT = castType.getTypePtr();
3833 QualType QDT = castType;
3834 // We desugar some types but not others. We ignore those
3835 // that cannot happen in a cast; i.e. auto, and those which
3836 // should not be de-sugared; i.e typedef.
3837 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3838 QDT = PT->desugar();
3839 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3840 QDT = TP->desugar();
3841 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3842 QDT = AT->desugar();
3843 if (QDT != castType &&
3844 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3845 SourceLocation loc =
3846 (castRange.isValid() ? castRange.getBegin()
3847 : castExpr->getExprLoc());
3848 Diag(loc, diag::err_arc_nolifetime_behavior);
3849 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003850 }
3851 return ACR_okay;
3852 }
3853
John McCall4124c492011-10-17 18:40:02 +00003854 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
3855
3856 // Allow all of these types to be cast to integer types (but not
3857 // vice-versa).
3858 if (castACTC == ACTC_none && castType->isIntegralType(Context))
3859 return ACR_okay;
3860
3861 // Allow casts between pointers to lifetime types (e.g., __strong id*)
3862 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
3863 // must be explicit.
3864 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
3865 return ACR_okay;
3866 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
3867 CCK != CCK_ImplicitConversion)
3868 return ACR_okay;
3869
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003870 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00003871 // For invalid casts, fall through.
3872 case ACC_invalid:
3873 break;
3874
3875 // Do nothing for both bottom and +0.
3876 case ACC_bottom:
3877 case ACC_plusZero:
3878 return ACR_okay;
3879
3880 // If the result is +1, consume it here.
3881 case ACC_plusOne:
3882 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3883 CK_ARCConsumeObject, castExpr,
Craig Topperc3ec1492014-05-26 06:22:03 +00003884 nullptr, VK_RValue);
John McCall4124c492011-10-17 18:40:02 +00003885 ExprNeedsCleanups = true;
3886 return ACR_okay;
3887 }
3888
3889 // If this is a non-implicit cast from id or block type to a
3890 // CoreFoundation type, delay complaining in case the cast is used
3891 // in an acceptable context.
3892 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3893 CCK != CCK_ImplicitConversion)
3894 return ACR_unbridged;
3895
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003896 // Do not issue bridge cast" diagnostic when implicit casting a cstring
3897 // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
3898 // suitable fix-it.
Fariborz Jahanian283bf892013-12-18 21:04:43 +00003899 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
3900 ConversionToObjCStringLiteralCheck(castType, castExpr))
3901 return ACR_okay;
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003902
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003903 // Do not issue "bridge cast" diagnostic when implicit casting
3904 // a retainable object to a CF type parameter belonging to an audited
3905 // CF API function. Let caller issue a normal type mismatched diagnostic
3906 // instead.
3907 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
3908 castACTC != ACTC_coreFoundation)
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00003909 if (!(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
3910 (Opc == BO_NE || Opc == BO_EQ)))
3911 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3912 castExpr, castExpr, exprACTC, CCK);
John McCall4124c492011-10-17 18:40:02 +00003913 return ACR_okay;
3914}
3915
3916/// Given that we saw an expression with the ARCUnbridgedCastTy
3917/// placeholder type, complain bitterly.
3918void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3919 // We expect the spurious ImplicitCastExpr to already have been stripped.
3920 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3921 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3922
3923 SourceRange castRange;
3924 QualType castType;
3925 CheckedConversionKind CCK;
3926
3927 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3928 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3929 castType = cast->getTypeAsWritten();
3930 CCK = CCK_CStyleCast;
3931 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3932 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3933 castType = cast->getTypeAsWritten();
3934 CCK = CCK_OtherCast;
3935 } else {
3936 castType = cast->getType();
3937 CCK = CCK_ImplicitConversion;
3938 }
3939
3940 ARCConversionTypeClass castACTC =
3941 classifyTypeForARCConversion(castType.getNonReferenceType());
3942
3943 Expr *castExpr = realCast->getSubExpr();
3944 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3945
3946 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003947 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00003948}
3949
3950/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3951/// type, remove the placeholder cast.
3952Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3953 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3954
3955 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3956 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3957 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3958 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3959 assert(uo->getOpcode() == UO_Extension);
3960 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3961 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3962 sub->getValueKind(), sub->getObjectKind(),
3963 uo->getOperatorLoc());
3964 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3965 assert(!gse->isResultDependent());
3966
3967 unsigned n = gse->getNumAssocs();
3968 SmallVector<Expr*, 4> subExprs(n);
3969 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3970 for (unsigned i = 0; i != n; ++i) {
3971 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3972 Expr *sub = gse->getAssocExpr(i);
3973 if (i == gse->getResultIndex())
3974 sub = stripARCUnbridgedCast(sub);
3975 subExprs[i] = sub;
3976 }
3977
3978 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3979 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003980 subTypes, subExprs,
3981 gse->getDefaultLoc(),
John McCall4124c492011-10-17 18:40:02 +00003982 gse->getRParenLoc(),
3983 gse->containsUnexpandedParameterPack(),
3984 gse->getResultIndex());
3985 } else {
3986 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3987 return cast<ImplicitCastExpr>(e)->getSubExpr();
3988 }
3989}
3990
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003991bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3992 QualType exprType) {
3993 QualType canCastType =
3994 Context.getCanonicalType(castType).getUnqualifiedType();
3995 QualType canExprType =
3996 Context.getCanonicalType(exprType).getUnqualifiedType();
3997 if (isa<ObjCObjectPointerType>(canCastType) &&
3998 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3999 canExprType->isObjCObjectPointerType()) {
4000 if (const ObjCObjectPointerType *ObjT =
4001 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00004002 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4003 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00004004 }
4005 return true;
4006}
4007
John McCall4db5c3c2011-07-07 06:58:02 +00004008/// Look for an ObjCReclaimReturnedObject cast and destroy it.
4009static Expr *maybeUndoReclaimObject(Expr *e) {
4010 // For now, we just undo operands that are *immediately* reclaim
4011 // expressions, which prevents the vast majority of potential
4012 // problems here. To catch them all, we'd need to rebuild arbitrary
4013 // value-propagating subexpressions --- we can't reliably rebuild
4014 // in-place because of expression sharing.
4015 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall2d637d22011-09-10 06:18:15 +00004016 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall4db5c3c2011-07-07 06:58:02 +00004017 return ice->getSubExpr();
4018
4019 return e;
4020}
4021
John McCall31168b02011-06-15 23:02:42 +00004022ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
4023 ObjCBridgeCastKind Kind,
4024 SourceLocation BridgeKeywordLoc,
4025 TypeSourceInfo *TSInfo,
4026 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00004027 ExprResult SubResult = UsualUnaryConversions(SubExpr);
4028 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004029 SubExpr = SubResult.get();
John McCalleb075542011-08-26 00:48:42 +00004030
John McCall31168b02011-06-15 23:02:42 +00004031 QualType T = TSInfo->getType();
4032 QualType FromType = SubExpr->getType();
4033
John McCall9320b872011-09-09 05:25:32 +00004034 CastKind CK;
4035
John McCall31168b02011-06-15 23:02:42 +00004036 bool MustConsume = false;
4037 if (T->isDependentType() || SubExpr->isTypeDependent()) {
4038 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00004039 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00004040 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
4041 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00004042 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4043 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00004044 switch (Kind) {
4045 case OBC_Bridge:
4046 break;
4047
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004048 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004049 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00004050 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4051 << 2
4052 << FromType
4053 << (T->isBlockPointerType()? 1 : 0)
4054 << T
4055 << SubExpr->getSourceRange()
4056 << Kind;
4057 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4058 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4059 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004060 << FromType << br
John McCall31168b02011-06-15 23:02:42 +00004061 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004062 br ? "CFBridgingRelease "
4063 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00004064
4065 Kind = OBC_Bridge;
4066 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004067 }
John McCall31168b02011-06-15 23:02:42 +00004068
4069 case OBC_BridgeTransfer:
4070 // We must consume the Objective-C object produced by the cast.
4071 MustConsume = true;
4072 break;
4073 }
4074 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4075 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00004076 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00004077 switch (Kind) {
Fariborz Jahanian214567c2014-10-28 17:26:21 +00004078 case OBC_Bridge:
4079 // Reclaiming a value that's going to be __bridge-casted to CF
4080 // is very dangerous, so we don't do it.
4081 SubExpr = maybeUndoReclaimObject(SubExpr);
4082 break;
John McCall31168b02011-06-15 23:02:42 +00004083
4084 case OBC_BridgeRetained:
4085 // Produce the object before casting it.
4086 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00004087 CK_ARCProduceObject,
Craig Topperc3ec1492014-05-26 06:22:03 +00004088 SubExpr, nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004089 break;
4090
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004091 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004092 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00004093 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4094 << (FromType->isBlockPointerType()? 1 : 0)
4095 << FromType
4096 << 2
4097 << T
4098 << SubExpr->getSourceRange()
4099 << Kind;
4100
4101 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4102 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4103 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004104 << T << br
4105 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4106 br ? "CFBridgingRetain " : "__bridge_retained");
John McCall31168b02011-06-15 23:02:42 +00004107
4108 Kind = OBC_Bridge;
4109 break;
4110 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004111 }
John McCall31168b02011-06-15 23:02:42 +00004112 } else {
4113 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4114 << FromType << T << Kind
4115 << SubExpr->getSourceRange()
4116 << TSInfo->getTypeLoc().getSourceRange();
4117 return ExprError();
4118 }
4119
John McCall9320b872011-09-09 05:25:32 +00004120 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00004121 BridgeKeywordLoc,
4122 TSInfo, SubExpr);
4123
4124 if (MustConsume) {
4125 ExprNeedsCleanups = true;
John McCall2d637d22011-09-10 06:18:15 +00004126 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
Craig Topperc3ec1492014-05-26 06:22:03 +00004127 nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004128 }
4129
4130 return Result;
4131}
4132
4133ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4134 SourceLocation LParenLoc,
4135 ObjCBridgeCastKind Kind,
4136 SourceLocation BridgeKeywordLoc,
4137 ParsedType Type,
4138 SourceLocation RParenLoc,
4139 Expr *SubExpr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004140 TypeSourceInfo *TSInfo = nullptr;
John McCall31168b02011-06-15 23:02:42 +00004141 QualType T = GetTypeFromParser(Type, &TSInfo);
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00004142 if (Kind == OBC_Bridge)
4143 CheckTollFreeBridgeCast(T, SubExpr);
John McCall31168b02011-06-15 23:02:42 +00004144 if (!TSInfo)
4145 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4146 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
4147 SubExpr);
4148}