blob: 7cb3c0ad0075f19ff0d2a65df60bf8bb817c2238 [file] [log] [blame]
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for Objective-C expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnera3fc41d2008-01-04 22:32:30 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
Steve Naroff021ca182008-05-29 21:12:08 +000017#include "clang/AST/ExprObjC.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor0c78ad92010-04-21 19:57:20 +000019#include "clang/AST/TypeLoc.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
21#include "clang/Edit/Commit.h"
22#include "clang/Edit/Rewriters.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000023#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/Initialization.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/Scope.h"
27#include "clang/Sema/ScopeInfo.h"
28#include "llvm/ADT/SmallString.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000029
Chris Lattnera3fc41d2008-01-04 22:32:30 +000030using namespace clang;
John McCall5f2d5562011-02-03 09:00:02 +000031using namespace sema;
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +000032using llvm::makeArrayRef;
Chris Lattnera3fc41d2008-01-04 22:32:30 +000033
John McCallfaf5fb42010-08-26 23:41:50 +000034ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
35 Expr **strings,
36 unsigned NumStrings) {
Chris Lattner163ffd22009-02-18 06:48:40 +000037 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
38
Chris Lattnerd7670d92009-02-18 06:13:04 +000039 // Most ObjC strings are formed out of a single piece. However, we *can*
40 // have strings formed out of multiple @ strings with multiple pptokens in
41 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
42 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner163ffd22009-02-18 06:48:40 +000043 StringLiteral *S = Strings[0];
Mike Stump11289f42009-09-09 15:08:12 +000044
Chris Lattnerd7670d92009-02-18 06:13:04 +000045 // If we have a multi-part string, merge it all together.
46 if (NumStrings != 1) {
Chris Lattnera3fc41d2008-01-04 22:32:30 +000047 // Concatenate objc strings.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000048 SmallString<128> StrBuf;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000049 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump11289f42009-09-09 15:08:12 +000050
Chris Lattner630970d2009-02-18 05:49:11 +000051 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner163ffd22009-02-18 06:48:40 +000052 S = Strings[i];
Mike Stump11289f42009-09-09 15:08:12 +000053
Douglas Gregorfb65e592011-07-27 05:40:30 +000054 // ObjC strings can't be wide or UTF.
55 if (!S->isAscii()) {
Chris Lattnerd7670d92009-02-18 06:13:04 +000056 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
57 << S->getSourceRange();
58 return true;
59 }
Mike Stump11289f42009-09-09 15:08:12 +000060
Benjamin Kramer35b077e2010-08-17 12:54:38 +000061 // Append the string.
62 StrBuf += S->getString();
Mike Stump11289f42009-09-09 15:08:12 +000063
Chris Lattner163ffd22009-02-18 06:48:40 +000064 // Get the locations of the string tokens.
65 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000066 }
Mike Stump11289f42009-09-09 15:08:12 +000067
Chris Lattner163ffd22009-02-18 06:48:40 +000068 // Create the aggregate string with the appropriate content and location
69 // information.
Benjamin Kramercdac7612014-02-25 12:26:20 +000070 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
71 assert(CAT && "String literal not of constant array type!");
72 QualType StrTy = Context.getConstantArrayType(
73 CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1),
74 CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
75 S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
76 /*Pascal=*/false, StrTy, &StrLocs[0],
77 StrLocs.size());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000078 }
Ted Kremeneke65b0862012-03-06 20:05:56 +000079
80 return BuildObjCStringLiteral(AtLocs[0], S);
81}
Mike Stump11289f42009-09-09 15:08:12 +000082
Ted Kremeneke65b0862012-03-06 20:05:56 +000083ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
Chris Lattner6436fb62009-02-18 06:01:06 +000084 // Verify that this composite string is acceptable for ObjC strings.
85 if (CheckObjCString(S))
Chris Lattnera3fc41d2008-01-04 22:32:30 +000086 return true;
Chris Lattnerfffd6a72009-02-18 06:06:56 +000087
88 // Initialize the constant string interface lazily. This assumes
Steve Naroff54e59452009-04-07 14:18:33 +000089 // the NSString interface is seen in this translation unit. Note: We
90 // don't use NSConstantString, since the runtime team considers this
91 // interface private (even though it appears in the header files).
Chris Lattnerfffd6a72009-02-18 06:06:56 +000092 QualType Ty = Context.getObjCConstantStringInterface();
93 if (!Ty.isNull()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +000094 Ty = Context.getObjCObjectPointerType(Ty);
David Blaikiebbafb8a2012-03-11 07:00:24 +000095 } else if (getLangOpts().NoConstantCFStrings) {
Craig Topperc3ec1492014-05-26 06:22:03 +000096 IdentifierInfo *NSIdent=nullptr;
David Blaikiebbafb8a2012-03-11 07:00:24 +000097 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +000098
99 if (StringClass.empty())
100 NSIdent = &Context.Idents.get("NSConstantString");
101 else
102 NSIdent = &Context.Idents.get(StringClass);
103
Ted Kremeneke65b0862012-03-06 20:05:56 +0000104 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Fariborz Jahanian07317632010-04-23 23:19:04 +0000105 LookupOrdinaryName);
106 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
107 Context.setObjCConstantStringInterface(StrIF);
108 Ty = Context.getObjCConstantStringInterface();
109 Ty = Context.getObjCObjectPointerType(Ty);
110 } else {
111 // If there is no NSConstantString interface defined then treat this
112 // as error and recover from it.
113 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
114 << S->getSourceRange();
115 Ty = Context.getObjCIdType();
116 }
Chris Lattner091f6982008-06-21 21:44:18 +0000117 } else {
Patrick Beard0caa3942012-04-19 00:25:12 +0000118 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000119 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000120 LookupOrdinaryName);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000121 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
122 Context.setObjCConstantStringInterface(StrIF);
123 Ty = Context.getObjCConstantStringInterface();
Steve Naroff7cae42b2009-07-10 23:34:53 +0000124 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000125 } else {
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000126 // If there is no NSString interface defined, implicitly declare
127 // a @class NSString; and use that instead. This is to make sure
128 // type of an NSString literal is represented correctly, instead of
129 // being an 'id' type.
130 Ty = Context.getObjCNSStringType();
131 if (Ty.isNull()) {
132 ObjCInterfaceDecl *NSStringIDecl =
133 ObjCInterfaceDecl::Create (Context,
134 Context.getTranslationUnitDecl(),
135 SourceLocation(), NSIdent,
Craig Topperc3ec1492014-05-26 06:22:03 +0000136 nullptr, SourceLocation());
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000137 Ty = Context.getObjCInterfaceType(NSStringIDecl);
138 Context.setObjCNSStringType(Ty);
139 }
140 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000141 }
Chris Lattner091f6982008-06-21 21:44:18 +0000142 }
Mike Stump11289f42009-09-09 15:08:12 +0000143
Ted Kremeneke65b0862012-03-06 20:05:56 +0000144 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
145}
146
Jordy Rose08e500c2012-05-12 17:32:44 +0000147/// \brief Emits an error if the given method does not exist, or if the return
148/// type is not an Objective-C object.
149static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
150 const ObjCInterfaceDecl *Class,
151 Selector Sel, const ObjCMethodDecl *Method) {
152 if (!Method) {
153 // FIXME: Is there a better way to avoid quotes than using getName()?
154 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
155 return false;
156 }
157
158 // Make sure the return type is reasonable.
Alp Toker314cc812014-01-25 16:55:45 +0000159 QualType ReturnType = Method->getReturnType();
Jordy Rose08e500c2012-05-12 17:32:44 +0000160 if (!ReturnType->isObjCObjectPointerType()) {
161 S.Diag(Loc, diag::err_objc_literal_method_sig)
162 << Sel;
163 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
164 << ReturnType;
165 return false;
166 }
167
168 return true;
169}
170
Ted Kremeneke65b0862012-03-06 20:05:56 +0000171/// \brief Retrieve the NSNumber factory method that should be used to create
172/// an Objective-C literal for the given type.
173static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
Patrick Beard0caa3942012-04-19 00:25:12 +0000174 QualType NumberType,
175 bool isLiteral = false,
176 SourceRange R = SourceRange()) {
David Blaikie05785d12013-02-20 22:23:23 +0000177 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
178 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
179
Ted Kremeneke65b0862012-03-06 20:05:56 +0000180 if (!Kind) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000181 if (isLiteral) {
182 S.Diag(Loc, diag::err_invalid_nsnumber_type)
183 << NumberType << R;
184 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000185 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000186 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000187
Ted Kremeneke65b0862012-03-06 20:05:56 +0000188 // If we already looked up this method, we're done.
189 if (S.NSNumberLiteralMethods[*Kind])
190 return S.NSNumberLiteralMethods[*Kind];
191
192 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
193 /*Instance=*/false);
194
Patrick Beard0caa3942012-04-19 00:25:12 +0000195 ASTContext &CX = S.Context;
196
197 // Look up the NSNumber class, if we haven't done so already. It's cached
198 // in the Sema instance.
199 if (!S.NSNumberDecl) {
Jordy Roseaca01f92012-05-12 17:32:52 +0000200 IdentifierInfo *NSNumberId =
201 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber);
Patrick Beard0caa3942012-04-19 00:25:12 +0000202 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId,
203 Loc, Sema::LookupOrdinaryName);
204 S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
205 if (!S.NSNumberDecl) {
206 if (S.getLangOpts().DebuggerObjCLiteral) {
207 // Create a stub definition of NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000208 S.NSNumberDecl = ObjCInterfaceDecl::Create(CX,
209 CX.getTranslationUnitDecl(),
210 SourceLocation(), NSNumberId,
Craig Topperc3ec1492014-05-26 06:22:03 +0000211 nullptr, SourceLocation());
Patrick Beard0caa3942012-04-19 00:25:12 +0000212 } else {
213 // Otherwise, require a declaration of NSNumber.
214 S.Diag(Loc, diag::err_undeclared_nsnumber);
Craig Topperc3ec1492014-05-26 06:22:03 +0000215 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000216 }
217 } else if (!S.NSNumberDecl->hasDefinition()) {
218 S.Diag(Loc, diag::err_undeclared_nsnumber);
Craig Topperc3ec1492014-05-26 06:22:03 +0000219 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000220 }
221
222 // generate the pointer to NSNumber type.
Jordy Roseaca01f92012-05-12 17:32:52 +0000223 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
224 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000225 }
226
Ted Kremeneke65b0862012-03-06 20:05:56 +0000227 // Look for the appropriate method within NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000228 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000229 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000230 // create a stub definition this NSNumber factory method.
Craig Topperc3ec1492014-05-26 06:22:03 +0000231 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000232 Method =
233 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
234 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
235 /*isInstance=*/false, /*isVariadic=*/false,
236 /*isPropertyAccessor=*/false,
237 /*isImplicitlyDeclared=*/true,
238 /*isDefined=*/false, ObjCMethodDecl::Required,
239 /*HasRelatedResultType=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000240 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
241 SourceLocation(), SourceLocation(),
Patrick Beard0caa3942012-04-19 00:25:12 +0000242 &CX.Idents.get("value"),
Craig Topperc3ec1492014-05-26 06:22:03 +0000243 NumberType, /*TInfo=*/nullptr,
244 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000245 Method->setMethodParams(S.Context, value, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000246 }
247
Jordy Rose08e500c2012-05-12 17:32:44 +0000248 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
Craig Topperc3ec1492014-05-26 06:22:03 +0000249 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000250
251 // Note: if the parameter type is out-of-line, we'll catch it later in the
252 // implicit conversion.
253
254 S.NSNumberLiteralMethods[*Kind] = Method;
255 return Method;
256}
257
Patrick Beard0caa3942012-04-19 00:25:12 +0000258/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
259/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremeneke65b0862012-03-06 20:05:56 +0000260ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000261 // Determine the type of the literal.
262 QualType NumberType = Number->getType();
263 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
264 // In C, character literals have type 'int'. That's not the type we want
265 // to use to determine the Objective-c literal kind.
266 switch (Char->getKind()) {
267 case CharacterLiteral::Ascii:
268 NumberType = Context.CharTy;
269 break;
270
271 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000272 NumberType = Context.getWideCharType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000273 break;
274
275 case CharacterLiteral::UTF16:
276 NumberType = Context.Char16Ty;
277 break;
278
279 case CharacterLiteral::UTF32:
280 NumberType = Context.Char32Ty;
281 break;
282 }
283 }
284
Ted Kremeneke65b0862012-03-06 20:05:56 +0000285 // Look for the appropriate method within NSNumber.
286 // Construct the literal.
Patrick Beard2565c592012-05-01 21:47:19 +0000287 SourceRange NR(Number->getSourceRange());
Patrick Beard0caa3942012-04-19 00:25:12 +0000288 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
Patrick Beard2565c592012-05-01 21:47:19 +0000289 true, NR);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000290 if (!Method)
291 return ExprError();
292
293 // Convert the number to the type that the parameter expects.
Alp Toker03376dc2014-07-07 09:02:20 +0000294 ParmVarDecl *ParamDecl = Method->parameters()[0];
Patrick Beard2565c592012-05-01 21:47:19 +0000295 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
296 ParamDecl);
297 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
298 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000299 Number);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000300 if (ConvertedNumber.isInvalid())
301 return ExprError();
302 Number = ConvertedNumber.get();
303
Patrick Beard2565c592012-05-01 21:47:19 +0000304 // Use the effective source range of the literal, including the leading '@'.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000305 return MaybeBindToTemporary(
Patrick Beard2565c592012-05-01 21:47:19 +0000306 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
307 SourceRange(AtLoc, NR.getEnd())));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000308}
309
310ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
311 SourceLocation ValueLoc,
312 bool Value) {
313 ExprResult Inner;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000314 if (getLangOpts().CPlusPlus) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000315 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
316 } else {
317 // C doesn't actually have a way to represent literal values of type
318 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
319 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
320 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
321 CK_IntegralToBoolean);
322 }
323
324 return BuildObjCNumericLiteral(AtLoc, Inner.get());
325}
326
327/// \brief Check that the given expression is a valid element of an Objective-C
328/// collection literal.
329static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000330 QualType T,
331 bool ArrayLiteral = false) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000332 // If the expression is type-dependent, there's nothing for us to do.
333 if (Element->isTypeDependent())
334 return Element;
335
336 ExprResult Result = S.CheckPlaceholderExpr(Element);
337 if (Result.isInvalid())
338 return ExprError();
339 Element = Result.get();
340
341 // In C++, check for an implicit conversion to an Objective-C object pointer
342 // type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000343 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000344 InitializedEntity Entity
Jordy Roseaca01f92012-05-12 17:32:52 +0000345 = InitializedEntity::InitializeParameter(S.Context, T,
346 /*Consumed=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000347 InitializationKind Kind
Jordy Roseaca01f92012-05-12 17:32:52 +0000348 = InitializationKind::CreateCopy(Element->getLocStart(),
349 SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000350 InitializationSequence Seq(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000351 if (!Seq.Failed())
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000352 return Seq.Perform(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000353 }
354
355 Expr *OrigElement = Element;
356
357 // Perform lvalue-to-rvalue conversion.
358 Result = S.DefaultLvalueConversion(Element);
359 if (Result.isInvalid())
360 return ExprError();
361 Element = Result.get();
362
363 // Make sure that we have an Objective-C pointer type or block.
364 if (!Element->getType()->isObjCObjectPointerType() &&
365 !Element->getType()->isBlockPointerType()) {
366 bool Recovered = false;
367
368 // If this is potentially an Objective-C numeric literal, add the '@'.
369 if (isa<IntegerLiteral>(OrigElement) ||
370 isa<CharacterLiteral>(OrigElement) ||
371 isa<FloatingLiteral>(OrigElement) ||
372 isa<ObjCBoolLiteralExpr>(OrigElement) ||
373 isa<CXXBoolLiteralExpr>(OrigElement)) {
374 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
375 int Which = isa<CharacterLiteral>(OrigElement) ? 1
376 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
377 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
378 : 3;
379
380 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
381 << Which << OrigElement->getSourceRange()
382 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
383
384 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
385 OrigElement);
386 if (Result.isInvalid())
387 return ExprError();
388
389 Element = Result.get();
390 Recovered = true;
391 }
392 }
393 // If this is potentially an Objective-C string literal, add the '@'.
394 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
395 if (String->isAscii()) {
396 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
397 << 0 << OrigElement->getSourceRange()
398 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
399
400 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
401 if (Result.isInvalid())
402 return ExprError();
403
404 Element = Result.get();
405 Recovered = true;
406 }
407 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000408
Ted Kremeneke65b0862012-03-06 20:05:56 +0000409 if (!Recovered) {
410 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
411 << Element->getType();
412 return ExprError();
413 }
414 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000415 if (ArrayLiteral)
Ted Kremenek197fee42013-10-09 22:34:33 +0000416 if (ObjCStringLiteral *getString =
417 dyn_cast<ObjCStringLiteral>(OrigElement)) {
418 if (StringLiteral *SL = getString->getString()) {
419 unsigned numConcat = SL->getNumConcatenated();
420 if (numConcat > 1) {
421 // Only warn if the concatenated string doesn't come from a macro.
422 bool hasMacro = false;
423 for (unsigned i = 0; i < numConcat ; ++i)
424 if (SL->getStrTokenLoc(i).isMacroID()) {
425 hasMacro = true;
426 break;
427 }
428 if (!hasMacro)
429 S.Diag(Element->getLocStart(),
430 diag::warn_concatenated_nsarray_literal)
431 << Element->getType();
432 }
433 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000434 }
435
Ted Kremeneke65b0862012-03-06 20:05:56 +0000436 // Make sure that the element has the type that the container factory
437 // function expects.
438 return S.PerformCopyInitialization(
439 InitializedEntity::InitializeParameter(S.Context, T,
440 /*Consumed=*/false),
441 Element->getLocStart(), Element);
442}
443
Patrick Beard0caa3942012-04-19 00:25:12 +0000444ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
445 if (ValueExpr->isTypeDependent()) {
446 ObjCBoxedExpr *BoxedExpr =
Craig Topperc3ec1492014-05-26 06:22:03 +0000447 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000448 return BoxedExpr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000449 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000450 ObjCMethodDecl *BoxingMethod = nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000451 QualType BoxedType;
452 // Convert the expression to an RValue, so we can check for pointer types...
453 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
454 if (RValue.isInvalid()) {
455 return ExprError();
456 }
457 ValueExpr = RValue.get();
Patrick Beard2565c592012-05-01 21:47:19 +0000458 QualType ValueType(ValueExpr->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +0000459 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
460 QualType PointeeType = PT->getPointeeType();
461 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
462
463 if (!NSStringDecl) {
464 IdentifierInfo *NSStringId =
465 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
466 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
467 SR.getBegin(), LookupOrdinaryName);
468 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
469 if (!NSStringDecl) {
470 if (getLangOpts().DebuggerObjCLiteral) {
471 // Support boxed expressions in the debugger w/o NSString declaration.
Jordy Roseaca01f92012-05-12 17:32:52 +0000472 DeclContext *TU = Context.getTranslationUnitDecl();
473 NSStringDecl = ObjCInterfaceDecl::Create(Context, TU,
474 SourceLocation(),
475 NSStringId,
Craig Topperc3ec1492014-05-26 06:22:03 +0000476 nullptr, SourceLocation());
Patrick Beard0caa3942012-04-19 00:25:12 +0000477 } else {
478 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
479 return ExprError();
480 }
481 } else if (!NSStringDecl->hasDefinition()) {
482 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
483 return ExprError();
484 }
485 assert(NSStringDecl && "NSStringDecl should not be NULL");
Jordy Roseaca01f92012-05-12 17:32:52 +0000486 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
487 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000488 }
489
490 if (!StringWithUTF8StringMethod) {
491 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
492 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
493
494 // Look for the appropriate method within NSString.
Jordy Rose08e500c2012-05-12 17:32:44 +0000495 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
496 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000497 // Debugger needs to work even if NSString hasn't been defined.
Craig Topperc3ec1492014-05-26 06:22:03 +0000498 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000499 ObjCMethodDecl *M = ObjCMethodDecl::Create(
500 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
501 NSStringPointer, ReturnTInfo, NSStringDecl,
502 /*isInstance=*/false, /*isVariadic=*/false,
503 /*isPropertyAccessor=*/false,
504 /*isImplicitlyDeclared=*/true,
505 /*isDefined=*/false, ObjCMethodDecl::Required,
506 /*HasRelatedResultType=*/false);
Jordy Roseaca01f92012-05-12 17:32:52 +0000507 QualType ConstCharType = Context.CharTy.withConst();
Patrick Beard0caa3942012-04-19 00:25:12 +0000508 ParmVarDecl *value =
509 ParmVarDecl::Create(Context, M,
510 SourceLocation(), SourceLocation(),
511 &Context.Idents.get("value"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000512 Context.getPointerType(ConstCharType),
Craig Topperc3ec1492014-05-26 06:22:03 +0000513 /*TInfo=*/nullptr,
514 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000515 M->setMethodParams(Context, value, None);
Jordy Rose08e500c2012-05-12 17:32:44 +0000516 BoxingMethod = M;
Patrick Beard0caa3942012-04-19 00:25:12 +0000517 }
Jordy Rose890f4572012-05-12 15:53:41 +0000518
Jordy Rose08e500c2012-05-12 17:32:44 +0000519 if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
520 stringWithUTF8String, BoxingMethod))
521 return ExprError();
522
523 StringWithUTF8StringMethod = BoxingMethod;
Patrick Beard0caa3942012-04-19 00:25:12 +0000524 }
525
526 BoxingMethod = StringWithUTF8StringMethod;
527 BoxedType = NSStringPointer;
528 }
Patrick Beard2565c592012-05-01 21:47:19 +0000529 } else if (ValueType->isBuiltinType()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000530 // The other types we support are numeric, char and BOOL/bool. We could also
531 // provide limited support for structure types, such as NSRange, NSRect, and
532 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
533 // for more details.
534
535 // Check for a top-level character literal.
536 if (const CharacterLiteral *Char =
537 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
538 // In C, character literals have type 'int'. That's not the type we want
539 // to use to determine the Objective-c literal kind.
540 switch (Char->getKind()) {
541 case CharacterLiteral::Ascii:
542 ValueType = Context.CharTy;
543 break;
544
545 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000546 ValueType = Context.getWideCharType();
Patrick Beard0caa3942012-04-19 00:25:12 +0000547 break;
548
549 case CharacterLiteral::UTF16:
550 ValueType = Context.Char16Ty;
551 break;
552
553 case CharacterLiteral::UTF32:
554 ValueType = Context.Char32Ty;
555 break;
556 }
557 }
Fariborz Jahanian5d64abb2014-06-18 20:49:02 +0000558 CheckForIntOverflow(ValueExpr);
Patrick Beard0caa3942012-04-19 00:25:12 +0000559 // FIXME: Do I need to do anything special with BoolTy expressions?
560
561 // Look for the appropriate method within NSNumber.
562 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
563 BoxedType = NSNumberPointer;
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000564
565 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
566 if (!ET->getDecl()->isComplete()) {
567 Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type)
568 << ValueType << ValueExpr->getSourceRange();
569 return ExprError();
570 }
571
572 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(),
573 ET->getDecl()->getIntegerType());
574 BoxedType = NSNumberPointer;
Patrick Beard0caa3942012-04-19 00:25:12 +0000575 }
576
577 if (!BoxingMethod) {
578 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
579 << ValueType << ValueExpr->getSourceRange();
580 return ExprError();
581 }
582
583 // Convert the expression to the type that the parameter requires.
Alp Toker03376dc2014-07-07 09:02:20 +0000584 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
Patrick Beard2565c592012-05-01 21:47:19 +0000585 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
586 ParamDecl);
587 ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
588 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000589 ValueExpr);
Patrick Beard0caa3942012-04-19 00:25:12 +0000590 if (ConvertedValueExpr.isInvalid())
591 return ExprError();
592 ValueExpr = ConvertedValueExpr.get();
593
594 ObjCBoxedExpr *BoxedExpr =
595 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
596 BoxingMethod, SR);
597 return MaybeBindToTemporary(BoxedExpr);
598}
599
John McCallf2538342012-07-31 05:14:30 +0000600/// Build an ObjC subscript pseudo-object expression, given that
601/// that's supported by the runtime.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000602ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
603 Expr *IndexExpr,
604 ObjCMethodDecl *getterMethod,
605 ObjCMethodDecl *setterMethod) {
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +0000606 assert(!LangOpts.isSubscriptPointerArithmetic());
John McCall5fb5df92012-06-20 06:18:46 +0000607
John McCallf2538342012-07-31 05:14:30 +0000608 // We can't get dependent types here; our callers should have
609 // filtered them out.
610 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
611 "base or index cannot have dependent type here");
612
613 // Filter out placeholders in the index. In theory, overloads could
614 // be preserved here, although that might not actually work correctly.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000615 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
616 if (Result.isInvalid())
617 return ExprError();
618 IndexExpr = Result.get();
619
John McCallf2538342012-07-31 05:14:30 +0000620 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000621 Result = DefaultLvalueConversion(BaseExpr);
622 if (Result.isInvalid())
623 return ExprError();
624 BaseExpr = Result.get();
John McCallf2538342012-07-31 05:14:30 +0000625
626 // Build the pseudo-object expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000627 return ObjCSubscriptRefExpr::Create(Context, BaseExpr, IndexExpr,
628 Context.PseudoObjectTy, getterMethod,
629 setterMethod, RB);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000630}
631
632ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
633 // Look up the NSArray class, if we haven't done so already.
634 if (!NSArrayDecl) {
635 NamedDecl *IF = LookupSingleName(TUScope,
636 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
637 SR.getBegin(),
638 LookupOrdinaryName);
639 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000640 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000641 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
642 Context.getTranslationUnitDecl(),
643 SourceLocation(),
644 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
Craig Topperc3ec1492014-05-26 06:22:03 +0000645 nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000646
647 if (!NSArrayDecl) {
648 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
649 return ExprError();
650 }
651 }
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000652
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000653 // Find the arrayWithObjects:count: method, if we haven't done so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000654 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000655 if (!ArrayWithObjectsMethod) {
656 Selector
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000657 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
658 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000659 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000660 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000661 Method = ObjCMethodDecl::Create(
662 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000663 Context.getTranslationUnitDecl(), false /*Instance*/,
Alp Toker314cc812014-01-25 16:55:45 +0000664 false /*isVariadic*/,
665 /*isPropertyAccessor=*/false,
666 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
667 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000668 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000669 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000670 SourceLocation(),
671 SourceLocation(),
672 &Context.Idents.get("objects"),
673 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000674 /*TInfo=*/nullptr,
675 SC_None, nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000676 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000677 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000678 SourceLocation(),
679 SourceLocation(),
680 &Context.Idents.get("cnt"),
681 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000682 /*TInfo=*/nullptr, SC_None,
683 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000684 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000685 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000686 }
687
Jordy Rose08e500c2012-05-12 17:32:44 +0000688 if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000689 return ExprError();
Jordy Rose08e500c2012-05-12 17:32:44 +0000690
Jordy Rose4af44872012-05-12 17:32:56 +0000691 // Dig out the type that all elements should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000692 QualType T = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000693 const PointerType *PtrT = T->getAs<PointerType>();
694 if (!PtrT ||
695 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
696 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
697 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000698 Diag(Method->parameters()[0]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000699 diag::note_objc_literal_method_param)
700 << 0 << T
701 << Context.getPointerType(IdT.withConst());
702 return ExprError();
703 }
704
705 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000706 if (!Method->parameters()[1]->getType()->isIntegerType()) {
Jordy Rose4af44872012-05-12 17:32:56 +0000707 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
708 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000709 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000710 diag::note_objc_literal_method_param)
711 << 1
Alp Toker03376dc2014-07-07 09:02:20 +0000712 << Method->parameters()[1]->getType()
Jordy Rose4af44872012-05-12 17:32:56 +0000713 << "integral";
714 return ExprError();
715 }
716
717 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rose08e500c2012-05-12 17:32:44 +0000718 ArrayWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000719 }
720
Alp Toker03376dc2014-07-07 09:02:20 +0000721 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000722 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000723
724 // Check that each of the elements provided is valid in a collection literal,
725 // performing conversions as necessary.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000726 Expr **ElementsBuffer = Elements.data();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000727 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
728 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
729 ElementsBuffer[I],
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000730 RequiredType, true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000731 if (Converted.isInvalid())
732 return ExprError();
733
734 ElementsBuffer[I] = Converted.get();
735 }
736
737 QualType Ty
738 = Context.getObjCObjectPointerType(
739 Context.getObjCInterfaceType(NSArrayDecl));
740
741 return MaybeBindToTemporary(
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000742 ObjCArrayLiteral::Create(Context, Elements, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000743 ArrayWithObjectsMethod, SR));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000744}
745
746ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
747 ObjCDictionaryElement *Elements,
748 unsigned NumElements) {
749 // Look up the NSDictionary class, if we haven't done so already.
750 if (!NSDictionaryDecl) {
751 NamedDecl *IF = LookupSingleName(TUScope,
752 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
753 SR.getBegin(), LookupOrdinaryName);
754 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000755 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000756 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
757 Context.getTranslationUnitDecl(),
758 SourceLocation(),
759 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
Craig Topperc3ec1492014-05-26 06:22:03 +0000760 nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000761
762 if (!NSDictionaryDecl) {
763 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
764 return ExprError();
765 }
766 }
767
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000768 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
769 // so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000770 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000771 if (!DictionaryWithObjectsMethod) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000772 Selector Sel = NSAPIObj->getNSDictionarySelector(
773 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
774 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000775 if (!Method && getLangOpts().DebuggerObjCLiteral) {
776 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000777 SourceLocation(), SourceLocation(), Sel,
778 IdT,
Craig Topperc3ec1492014-05-26 06:22:03 +0000779 nullptr /*TypeSourceInfo */,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000780 Context.getTranslationUnitDecl(),
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000781 false /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000782 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000783 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
784 ObjCMethodDecl::Required,
785 false);
786 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000787 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000788 SourceLocation(),
789 SourceLocation(),
790 &Context.Idents.get("objects"),
791 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000792 /*TInfo=*/nullptr, SC_None,
793 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000794 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000795 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000796 SourceLocation(),
797 SourceLocation(),
798 &Context.Idents.get("keys"),
799 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000800 /*TInfo=*/nullptr, SC_None,
801 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000802 Params.push_back(keys);
Jordy Rose08e500c2012-05-12 17:32:44 +0000803 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000804 SourceLocation(),
805 SourceLocation(),
806 &Context.Idents.get("cnt"),
807 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000808 /*TInfo=*/nullptr, SC_None,
809 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000810 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000811 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000812 }
813
Jordy Rose08e500c2012-05-12 17:32:44 +0000814 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
815 Method))
816 return ExprError();
817
Jordy Rose4af44872012-05-12 17:32:56 +0000818 // Dig out the type that all values should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000819 QualType ValueT = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000820 const PointerType *PtrValue = ValueT->getAs<PointerType>();
821 if (!PtrValue ||
822 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000823 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000824 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000825 Diag(Method->parameters()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000826 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000827 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000828 << Context.getPointerType(IdT.withConst());
829 return ExprError();
830 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000831
Jordy Rose4af44872012-05-12 17:32:56 +0000832 // Dig out the type that all keys should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000833 QualType KeyT = Method->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000834 const PointerType *PtrKey = KeyT->getAs<PointerType>();
835 if (!PtrKey ||
836 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
837 IdT)) {
838 bool err = true;
839 if (PtrKey) {
840 if (QIDNSCopying.isNull()) {
841 // key argument of selector is id<NSCopying>?
842 if (ObjCProtocolDecl *NSCopyingPDecl =
843 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
844 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
845 QIDNSCopying =
846 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
847 (ObjCProtocolDecl**) PQ,1);
848 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
849 }
850 }
851 if (!QIDNSCopying.isNull())
852 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
853 QIDNSCopying);
854 }
855
856 if (err) {
857 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
858 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000859 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000860 diag::note_objc_literal_method_param)
861 << 1 << KeyT
862 << Context.getPointerType(IdT.withConst());
863 return ExprError();
864 }
865 }
866
867 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000868 QualType CountType = Method->parameters()[2]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000869 if (!CountType->isIntegerType()) {
870 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
871 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000872 Diag(Method->parameters()[2]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000873 diag::note_objc_literal_method_param)
874 << 2 << CountType
875 << "integral";
876 return ExprError();
877 }
878
879 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
880 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000881 }
882
Alp Toker03376dc2014-07-07 09:02:20 +0000883 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000884 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
Alp Toker03376dc2014-07-07 09:02:20 +0000885 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000886 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
887
Ted Kremeneke65b0862012-03-06 20:05:56 +0000888 // Check that each of the keys and values provided is valid in a collection
889 // literal, performing conversions as necessary.
890 bool HasPackExpansions = false;
891 for (unsigned I = 0, N = NumElements; I != N; ++I) {
892 // Check the key.
893 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
894 KeyT);
895 if (Key.isInvalid())
896 return ExprError();
897
898 // Check the value.
899 ExprResult Value
900 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
901 if (Value.isInvalid())
902 return ExprError();
903
904 Elements[I].Key = Key.get();
905 Elements[I].Value = Value.get();
906
907 if (Elements[I].EllipsisLoc.isInvalid())
908 continue;
909
910 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
911 !Elements[I].Value->containsUnexpandedParameterPack()) {
912 Diag(Elements[I].EllipsisLoc,
913 diag::err_pack_expansion_without_parameter_packs)
914 << SourceRange(Elements[I].Key->getLocStart(),
915 Elements[I].Value->getLocEnd());
916 return ExprError();
917 }
918
919 HasPackExpansions = true;
920 }
921
922
923 QualType Ty
924 = Context.getObjCObjectPointerType(
Robert Wilhelm88e02492013-08-19 07:57:02 +0000925 Context.getObjCInterfaceType(NSDictionaryDecl));
926 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
927 Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000928 DictionaryWithObjectsMethod, SR));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000929}
930
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000931ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregorabd9e962010-04-20 15:39:42 +0000932 TypeSourceInfo *EncodedTypeInfo,
Anders Carlsson315d2292009-06-07 18:45:35 +0000933 SourceLocation RParenLoc) {
Douglas Gregorabd9e962010-04-20 15:39:42 +0000934 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlsson315d2292009-06-07 18:45:35 +0000935 QualType StrTy;
Mike Stump11289f42009-09-09 15:08:12 +0000936 if (EncodedType->isDependentType())
Anders Carlsson315d2292009-06-07 18:45:35 +0000937 StrTy = Context.DependentTy;
938 else {
Fariborz Jahaniand9bc6c32011-06-16 22:34:44 +0000939 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
940 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000941 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000942 diag::err_incomplete_type_objc_at_encode,
943 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000944 return ExprError();
945
Anders Carlsson315d2292009-06-07 18:45:35 +0000946 std::string Str;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +0000947 QualType NotEncodedT;
948 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
949 if (!NotEncodedT.isNull())
950 Diag(AtLoc, diag::warn_incomplete_encoded_type)
951 << EncodedType << NotEncodedT;
Anders Carlsson315d2292009-06-07 18:45:35 +0000952
953 // The type of @encode is the same as the type of the corresponding string,
954 // which is an array type.
955 StrTy = Context.CharTy;
956 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +0000957 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlsson315d2292009-06-07 18:45:35 +0000958 StrTy.addConst();
959 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
960 ArrayType::Normal, 0);
961 }
Mike Stump11289f42009-09-09 15:08:12 +0000962
Douglas Gregorabd9e962010-04-20 15:39:42 +0000963 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlsson315d2292009-06-07 18:45:35 +0000964}
965
John McCallfaf5fb42010-08-26 23:41:50 +0000966ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
967 SourceLocation EncodeLoc,
968 SourceLocation LParenLoc,
969 ParsedType ty,
970 SourceLocation RParenLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000971 // FIXME: Preserve type source info ?
Douglas Gregorabd9e962010-04-20 15:39:42 +0000972 TypeSourceInfo *TInfo;
973 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
974 if (!TInfo)
975 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
976 PP.getLocForEndOfToken(LParenLoc));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000977
Douglas Gregorabd9e962010-04-20 15:39:42 +0000978 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000979}
980
Fariborz Jahanian44be1542014-03-12 18:34:01 +0000981static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
982 SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +0000983 SourceLocation LParenLoc,
984 SourceLocation RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +0000985 ObjCMethodDecl *Method,
986 ObjCMethodList &MethList) {
987 ObjCMethodList *M = &MethList;
988 bool Warned = false;
989 for (M = M->getNext(); M; M=M->getNext()) {
990 ObjCMethodDecl *MatchingMethodDecl = M->Method;
991 if (MatchingMethodDecl == Method ||
992 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
993 MatchingMethodDecl->getSelector() != Method->getSelector())
994 continue;
995 if (!S.MatchTwoMethodDeclarations(Method,
996 MatchingMethodDecl, Sema::MMS_loose)) {
997 if (!Warned) {
998 Warned = true;
999 S.Diag(AtLoc, diag::warning_multiple_selectors)
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001000 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1001 << FixItHint::CreateInsertion(RParenLoc, ")");
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001002 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1003 << Method->getDeclName();
1004 }
1005 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1006 << MatchingMethodDecl->getDeclName();
1007 }
1008 }
1009 return Warned;
1010}
1011
1012static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001013 ObjCMethodDecl *Method,
1014 SourceLocation LParenLoc,
1015 SourceLocation RParenLoc,
1016 bool WarnMultipleSelectors) {
1017 if (!WarnMultipleSelectors ||
1018 S.Diags.isIgnored(diag::warning_multiple_selectors, SourceLocation()))
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001019 return;
1020 bool Warned = false;
1021 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1022 e = S.MethodPool.end(); b != e; b++) {
1023 // first, instance methods
1024 ObjCMethodList &InstMethList = b->second.first;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001025 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001026 Method, InstMethList))
1027 Warned = true;
1028
1029 // second, class methods
1030 ObjCMethodList &ClsMethList = b->second.second;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001031 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1032 Method, ClsMethList) || Warned)
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001033 return;
1034 }
1035}
1036
John McCallfaf5fb42010-08-26 23:41:50 +00001037ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1038 SourceLocation AtLoc,
1039 SourceLocation SelLoc,
1040 SourceLocation LParenLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001041 SourceLocation RParenLoc,
1042 bool WarnMultipleSelectors) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001043 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1044 SourceRange(LParenLoc, RParenLoc), false, false);
1045 if (!Method)
1046 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian0571d9b2009-06-16 16:25:00 +00001047 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00001048 if (!Method) {
1049 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1050 Selector MatchedSel = OM->getSelector();
1051 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1052 RParenLoc.getLocWithOffset(-1));
1053 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1054 << Sel << MatchedSel
1055 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1056
1057 } else
1058 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001059 } else
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001060 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1061 WarnMultipleSelectors);
Fariborz Jahanian9a881012011-07-13 19:05:43 +00001062
Fariborz Jahanian65a78b52014-05-09 19:51:39 +00001063 if (Method &&
1064 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
1065 !getSourceManager().isInSystemHeader(Method->getLocation())) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001066 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
1067 = ReferencedSelectors.find(Sel);
1068 if (Pos == ReferencedSelectors.end())
1069 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian9a881012011-07-13 19:05:43 +00001070 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001071
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001072 // In ARC, forbid the user from using @selector for
John McCall31168b02011-06-15 23:02:42 +00001073 // retain/release/autorelease/dealloc/retainCount.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001074 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001075 switch (Sel.getMethodFamily()) {
1076 case OMF_retain:
1077 case OMF_release:
1078 case OMF_autorelease:
1079 case OMF_retainCount:
1080 case OMF_dealloc:
1081 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1082 Sel << SourceRange(LParenLoc, RParenLoc);
1083 break;
1084
1085 case OMF_None:
1086 case OMF_alloc:
1087 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00001088 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00001089 case OMF_init:
1090 case OMF_mutableCopy:
1091 case OMF_new:
1092 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00001093 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001094 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001095 break;
1096 }
1097 }
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001098 QualType Ty = Context.getObjCSelType();
Daniel Dunbar45858d22010-02-03 20:11:42 +00001099 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001100}
1101
John McCallfaf5fb42010-08-26 23:41:50 +00001102ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1103 SourceLocation AtLoc,
1104 SourceLocation ProtoLoc,
1105 SourceLocation LParenLoc,
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001106 SourceLocation ProtoIdLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00001107 SourceLocation RParenLoc) {
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001108 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001109 if (!PDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001110 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001111 return true;
1112 }
Fariborz Jahaniana57d91c22014-07-25 19:45:01 +00001113 if (PDecl->hasDefinition())
1114 PDecl = PDecl->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00001115
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001116 QualType Ty = Context.getObjCProtoType();
1117 if (Ty.isNull())
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001118 return true;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001119 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001120 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001121}
1122
John McCall5f2d5562011-02-03 09:00:02 +00001123/// Try to capture an implicit reference to 'self'.
Eli Friedman24af8502012-02-03 22:47:37 +00001124ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1125 DeclContext *DC = getFunctionLevelDeclContext();
John McCall5f2d5562011-02-03 09:00:02 +00001126
1127 // If we're not in an ObjC method, error out. Note that, unlike the
1128 // C++ case, we don't require an instance method --- class methods
1129 // still have a 'self', and we really do still need to capture it!
1130 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1131 if (!method)
Craig Topperc3ec1492014-05-26 06:22:03 +00001132 return nullptr;
John McCall5f2d5562011-02-03 09:00:02 +00001133
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001134 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall5f2d5562011-02-03 09:00:02 +00001135
1136 return method;
1137}
1138
Douglas Gregor64910ca2011-09-09 20:05:21 +00001139static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1140 if (T == Context.getObjCInstanceType())
1141 return Context.getObjCIdType();
1142
1143 return T;
1144}
1145
Douglas Gregor33823722011-06-11 01:09:30 +00001146QualType Sema::getMessageSendResultType(QualType ReceiverType,
1147 ObjCMethodDecl *Method,
1148 bool isClassMessage, bool isSuperMessage) {
1149 assert(Method && "Must have a method");
1150 if (!Method->hasRelatedResultType())
1151 return Method->getSendResultType();
1152
1153 // If a method has a related return type:
1154 // - if the method found is an instance method, but the message send
1155 // was a class message send, T is the declared return type of the method
1156 // found
1157 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor64910ca2011-09-09 20:05:21 +00001158 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001159
1160 // - if the receiver is super, T is a pointer to the class of the
1161 // enclosing method definition
1162 if (isSuperMessage) {
1163 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1164 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1165 return Context.getObjCObjectPointerType(
1166 Context.getObjCInterfaceType(Class));
1167 }
1168
1169 // - if the receiver is the name of a class U, T is a pointer to U
1170 if (ReceiverType->getAs<ObjCInterfaceType>() ||
1171 ReceiverType->isObjCQualifiedInterfaceType())
1172 return Context.getObjCObjectPointerType(ReceiverType);
1173 // - if the receiver is of type Class or qualified Class type,
1174 // T is the declared return type of the method.
1175 if (ReceiverType->isObjCClassType() ||
1176 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor64910ca2011-09-09 20:05:21 +00001177 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001178
1179 // - if the receiver is id, qualified id, Class, or qualified Class, T
1180 // is the receiver type, otherwise
1181 // - T is the type of the receiver expression.
1182 return ReceiverType;
1183}
John McCall5f2d5562011-02-03 09:00:02 +00001184
John McCall5ec7e7d2013-03-19 07:04:25 +00001185/// Look for an ObjC method whose result type exactly matches the given type.
1186static const ObjCMethodDecl *
1187findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1188 QualType instancetype) {
Alp Toker314cc812014-01-25 16:55:45 +00001189 if (MD->getReturnType() == instancetype)
1190 return MD;
John McCall5ec7e7d2013-03-19 07:04:25 +00001191
1192 // For these purposes, a method in an @implementation overrides a
1193 // declaration in the @interface.
1194 if (const ObjCImplDecl *impl =
1195 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1196 const ObjCContainerDecl *iface;
1197 if (const ObjCCategoryImplDecl *catImpl =
1198 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1199 iface = catImpl->getCategoryDecl();
1200 } else {
1201 iface = impl->getClassInterface();
1202 }
1203
1204 const ObjCMethodDecl *ifaceMD =
1205 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1206 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1207 }
1208
1209 SmallVector<const ObjCMethodDecl *, 4> overrides;
1210 MD->getOverriddenMethods(overrides);
1211 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1212 if (const ObjCMethodDecl *result =
1213 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1214 return result;
1215 }
1216
Craig Topperc3ec1492014-05-26 06:22:03 +00001217 return nullptr;
John McCall5ec7e7d2013-03-19 07:04:25 +00001218}
1219
1220void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1221 // Only complain if we're in an ObjC method and the required return
1222 // type doesn't match the method's declared return type.
1223 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1224 if (!MD || !MD->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +00001225 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
John McCall5ec7e7d2013-03-19 07:04:25 +00001226 return;
1227
1228 // Look for a method overridden by this method which explicitly uses
1229 // 'instancetype'.
1230 if (const ObjCMethodDecl *overridden =
1231 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +00001232 SourceRange range = overridden->getReturnTypeSourceRange();
1233 SourceLocation loc = range.getBegin();
John McCall5ec7e7d2013-03-19 07:04:25 +00001234 if (loc.isInvalid())
1235 loc = overridden->getLocation();
1236 Diag(loc, diag::note_related_result_type_explicit)
1237 << /*current method*/ 1 << range;
1238 return;
1239 }
1240
1241 // Otherwise, if we have an interesting method family, note that.
1242 // This should always trigger if the above didn't.
1243 if (ObjCMethodFamily family = MD->getMethodFamily())
1244 Diag(MD->getLocation(), diag::note_related_result_type_family)
1245 << /*current method*/ 1
1246 << family;
1247}
1248
Douglas Gregor33823722011-06-11 01:09:30 +00001249void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1250 E = E->IgnoreParenImpCasts();
1251 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1252 if (!MsgSend)
1253 return;
1254
1255 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1256 if (!Method)
1257 return;
1258
1259 if (!Method->hasRelatedResultType())
1260 return;
Alp Toker314cc812014-01-25 16:55:45 +00001261
1262 if (Context.hasSameUnqualifiedType(
1263 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
Douglas Gregor33823722011-06-11 01:09:30 +00001264 return;
Alp Toker314cc812014-01-25 16:55:45 +00001265
1266 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
Douglas Gregorbab8a962011-09-08 01:46:34 +00001267 Context.getObjCInstanceType()))
1268 return;
1269
Douglas Gregor33823722011-06-11 01:09:30 +00001270 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1271 << Method->isInstanceMethod() << Method->getSelector()
1272 << MsgSend->getType();
1273}
1274
1275bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001276 MultiExprArg Args,
1277 Selector Sel,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001278 ArrayRef<SourceLocation> SelectorLocs,
1279 ObjCMethodDecl *Method,
Douglas Gregor33823722011-06-11 01:09:30 +00001280 bool isClassMessage, bool isSuperMessage,
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001281 SourceLocation lbrac, SourceLocation rbrac,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001282 SourceRange RecRange,
John McCall7decc9e2010-11-18 06:31:45 +00001283 QualType &ReturnType, ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001284 SourceLocation SelLoc;
1285 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1286 SelLoc = SelectorLocs.front();
1287 else
1288 SelLoc = lbrac;
1289
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001290 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001291 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001292 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001293 if (Args[i]->isTypeDependent())
1294 continue;
1295
John McCallcc5788c2013-03-04 07:34:02 +00001296 ExprResult result;
1297 if (getLangOpts().DebuggerSupport) {
1298 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001299 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001300 } else {
1301 result = DefaultArgumentPromotion(Args[i]);
1302 }
1303 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001304 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001305 Args[i] = result.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001306 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001307
John McCall31168b02011-06-15 23:02:42 +00001308 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001309 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001310 DiagID = diag::err_arc_method_not_found;
1311 else
1312 DiagID = isClassMessage ? diag::warn_class_method_not_found
1313 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001314 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001315 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahanian06499232013-06-18 17:10:58 +00001316 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001317 if (getLangOpts().ObjCAutoRefCount)
1318 DiagID = diag::error_method_not_found_with_typo;
1319 else
1320 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1321 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001322 Selector MatchedSel = OMD->getSelector();
1323 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian5ab87502014-08-12 22:16:41 +00001324 if (MatchedSel.isUnarySelector())
1325 Diag(SelLoc, DiagID)
1326 << Sel<< isClassMessage << MatchedSel
1327 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1328 else
1329 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001330 }
1331 else
1332 Diag(SelLoc, DiagID)
1333 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001334 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001335 // Find the class to which we are sending this message.
1336 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001337 if (ObjCInterfaceDecl *ThisClass =
1338 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
1339 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1340 if (!RecRange.isInvalid())
1341 if (ThisClass->lookupClassMethod(Sel))
1342 Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
1343 << FixItHint::CreateReplacement(RecRange,
1344 ThisClass->getNameAsString());
1345 }
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001346 }
1347 }
John McCall3f4138c2011-07-13 17:56:40 +00001348
1349 // In debuggers, we want to use __unknown_anytype for these
1350 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001351 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001352 ReturnType = Context.UnknownAnyTy;
1353 } else {
1354 ReturnType = Context.getObjCIdType();
1355 }
John McCall7decc9e2010-11-18 06:31:45 +00001356 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001357 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001358 }
Mike Stump11289f42009-09-09 15:08:12 +00001359
Douglas Gregor33823722011-06-11 01:09:30 +00001360 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1361 isSuperMessage);
Alp Toker314cc812014-01-25 16:55:45 +00001362 VK = Expr::getValueKindForType(Method->getReturnType());
Mike Stump11289f42009-09-09 15:08:12 +00001363
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001364 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001365 // Method might have more arguments than selector indicates. This is due
1366 // to addition of c-style arguments in method.
1367 if (Method->param_size() > Sel.getNumArgs())
1368 NumNamedArgs = Method->param_size();
1369 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001370 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001371 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001372 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001373 return false;
1374 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001375
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001376 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001377 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001378 // We can't do any type-checking on a type-dependent argument.
1379 if (Args[i]->isTypeDependent())
1380 continue;
1381
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001382 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001383
Alp Toker03376dc2014-07-07 09:02:20 +00001384 ParmVarDecl *param = Method->parameters()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001385 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001386
John McCall4124c492011-10-17 18:40:02 +00001387 // Strip the unbridged-cast placeholder expression off unless it's
1388 // a consumed argument.
1389 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1390 !param->hasAttr<CFConsumedAttr>())
1391 argExpr = stripARCUnbridgedCast(argExpr);
1392
John McCallea0a39e2012-11-14 00:49:39 +00001393 // If the parameter is __unknown_anytype, infer its type
1394 // from the argument.
1395 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001396 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001397 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001398 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001399 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001400 } else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001401 Args[i] = argE.get();
John McCallea0a39e2012-11-14 00:49:39 +00001402
John McCallcc5788c2013-03-04 07:34:02 +00001403 // Update the parameter type in-place.
1404 param->setType(paramType);
1405 }
1406 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001407 }
1408
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001409 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall4124c492011-10-17 18:40:02 +00001410 param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001411 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001412 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001413
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001414 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall4124c492011-10-17 18:40:02 +00001415 param);
Fariborz Jahaniana1db7df2014-07-31 17:39:50 +00001416 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001417 if (ArgE.isInvalid())
1418 IsError = true;
1419 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001420 Args[i] = ArgE.getAs<Expr>();
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001421 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001422
1423 // Promote additional arguments to variadic methods.
1424 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001425 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001426 if (Args[i]->isTypeDependent())
1427 continue;
1428
Jordy Roseaca01f92012-05-12 17:32:52 +00001429 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
Craig Topperc3ec1492014-05-26 06:22:03 +00001430 nullptr);
John Wiegley01296292011-04-08 18:41:53 +00001431 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001432 Args[i] = Arg.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001433 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001434 } else {
1435 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001436 if (Args.size() != NumNamedArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00001437 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001438 diag::err_typecheck_call_too_many_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001439 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001440 << Method->getSourceRange()
Chris Lattner3b054132008-11-19 05:08:23 +00001441 << SourceRange(Args[NumNamedArgs]->getLocStart(),
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001442 Args.back()->getLocEnd());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001443 }
1444 }
1445
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001446 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001447
1448 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001449 IsError |= CheckObjCMethodCall(
Craig Topper8c2a2a02014-08-30 16:55:39 +00001450 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001451
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001452 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001453}
1454
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001455bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001456 // 'self' is objc 'self' in an objc method only.
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001457 ObjCMethodDecl *Method =
1458 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1459 return isSelfExpr(RExpr, Method);
1460}
1461
1462bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
John McCallfe96e0b2011-11-06 09:01:30 +00001463 if (!method) return false;
1464
John McCall31168b02011-06-15 23:02:42 +00001465 receiver = receiver->IgnoreParenLValueCasts();
1466 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001467 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001468 return true;
1469 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001470}
1471
John McCall526ab472011-10-25 17:37:35 +00001472/// LookupMethodInType - Look up a method in an ObjCObjectType.
1473ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1474 bool isInstance) {
1475 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1476 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1477 // Look it up in the main interface (and categories, etc.)
1478 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1479 return method;
1480
1481 // Okay, look for "private" methods declared in any
1482 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001483 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1484 return method;
John McCall526ab472011-10-25 17:37:35 +00001485 }
1486
1487 // Check qualifiers.
Aaron Ballman1683f7b2014-03-17 15:55:30 +00001488 for (const auto *I : objType->quals())
1489 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
John McCall526ab472011-10-25 17:37:35 +00001490 return method;
1491
Craig Topperc3ec1492014-05-26 06:22:03 +00001492 return nullptr;
John McCall526ab472011-10-25 17:37:35 +00001493}
1494
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001495/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1496/// list of a qualified objective pointer type.
1497ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1498 const ObjCObjectPointerType *OPT,
1499 bool Instance)
1500{
Craig Topperc3ec1492014-05-26 06:22:03 +00001501 ObjCMethodDecl *MD = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +00001502 for (const auto *PROTO : OPT->quals()) {
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001503 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1504 return MD;
1505 }
1506 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001507 return nullptr;
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001508}
1509
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001510static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1511 if (!Receiver)
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001512 return;
1513
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001514 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver))
1515 Receiver = OVE->getSourceExpr();
1516
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001517 Expr *RExpr = Receiver->IgnoreParenImpCasts();
1518 SourceLocation Loc = RExpr->getLocStart();
1519 QualType T = RExpr->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001520 const ObjCPropertyDecl *PDecl = nullptr;
1521 const ObjCMethodDecl *GDecl = nullptr;
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001522 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1523 RExpr = POE->getSyntacticForm();
1524 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1525 if (PRE->isImplicitProperty()) {
1526 GDecl = PRE->getImplicitPropertyGetter();
1527 if (GDecl) {
Alp Toker314cc812014-01-25 16:55:45 +00001528 T = GDecl->getReturnType();
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001529 }
1530 }
1531 else {
1532 PDecl = PRE->getExplicitProperty();
1533 if (PDecl) {
1534 T = PDecl->getType();
1535 }
1536 }
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001537 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001538 }
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001539 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) {
1540 // See if receiver is a method which envokes a synthesized getter
1541 // backing a 'weak' property.
1542 ObjCMethodDecl *Method = ME->getMethodDecl();
Jordan Rose2bd991a2012-10-10 16:42:54 +00001543 if (Method && Method->getSelector().getNumArgs() == 0) {
1544 PDecl = Method->findPropertyDecl();
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001545 if (PDecl)
1546 T = PDecl->getType();
1547 }
1548 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001549
Jordan Rose13d6b712012-09-28 22:21:42 +00001550 if (T.getObjCLifetime() != Qualifiers::OCL_Weak) {
1551 if (!PDecl)
1552 return;
1553 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak))
1554 return;
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001555 }
Jordan Rose13d6b712012-09-28 22:21:42 +00001556
1557 S.Diag(Loc, diag::warn_receiver_is_weak)
1558 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1559
1560 if (PDecl)
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001561 S.Diag(PDecl->getLocation(), diag::note_property_declare);
Jordan Rose13d6b712012-09-28 22:21:42 +00001562 else if (GDecl)
1563 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
1564
1565 S.Diag(Loc, diag::note_arc_assign_to_strong);
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001566}
1567
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001568/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1569/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001570ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001571HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001572 Expr *BaseExpr, SourceLocation OpLoc,
1573 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001574 SourceLocation MemberLoc,
1575 SourceLocation SuperLoc, QualType SuperType,
1576 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001577 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1578 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001579
Benjamin Kramer365082d2012-05-19 16:34:46 +00001580 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001581 Diag(MemberLoc, diag::err_invalid_property_name)
1582 << MemberName << QualType(OPT, 0);
1583 return ExprError();
1584 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001585
1586 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregord6459312011-04-20 18:19:55 +00001587
Douglas Gregor4123a862011-11-14 22:10:01 +00001588 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1589 : BaseExpr->getSourceRange();
1590 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001591 diag::err_property_not_found_forward_class,
1592 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001593 return ExprError();
Douglas Gregor4123a862011-11-14 22:10:01 +00001594
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001595 // Search for a declared property first.
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001596 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001597 // Check whether we can reference this property.
1598 if (DiagnoseUseOfDecl(PD, MemberLoc))
1599 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001600 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001601 return new (Context)
1602 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1603 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001604 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001605 return new (Context)
1606 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1607 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001608 }
1609 // Check protocols on qualified interfaces.
Aaron Ballman83731462014-03-17 16:14:00 +00001610 for (const auto *I : OPT->quals())
1611 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001612 // Check whether we can reference this property.
1613 if (DiagnoseUseOfDecl(PD, MemberLoc))
1614 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001615
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001616 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001617 return new (Context) ObjCPropertyRefExpr(
1618 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1619 SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001620 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001621 return new (Context)
1622 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1623 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001624 }
1625 // If that failed, look for an "implicit" property by seeing if the nullary
1626 // selector is implemented.
1627
1628 // FIXME: The logic for looking up nullary and unary selectors should be
1629 // shared with the code in ActOnInstanceMessage.
1630
1631 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1632 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001633
1634 // May be founf in property's qualified list.
1635 if (!Getter)
1636 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001637
1638 // If this reference is in an @implementation, check for 'private' methods.
1639 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001640 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001641
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001642 if (Getter) {
1643 // Check if we can reference this property.
1644 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1645 return ExprError();
1646 }
1647 // If we found a getter then this may be a valid dot-reference, we
1648 // will look for the matching setter, in case it is needed.
1649 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001650 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1651 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001652 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001653
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001654 // May be founf in property's qualified list.
1655 if (!Setter)
1656 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1657
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001658 if (!Setter) {
1659 // If this reference is in an @implementation, also check for 'private'
1660 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001661 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001662 }
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001663
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001664 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1665 return ExprError();
1666
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001667 // Special warning if member name used in a property-dot for a setter accessor
1668 // does not use a property with same name; e.g. obj.X = ... for a property with
1669 // name 'x'.
1670 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor()
1671 && !IFace->FindPropertyDeclaration(Member)) {
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001672 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
1673 // Do not warn if user is using property-dot syntax to make call to
1674 // user named setter.
1675 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001676 Diag(MemberLoc,
1677 diag::warn_property_access_suggest)
1678 << MemberName << QualType(OPT, 0) << PDecl->getName()
1679 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001680 }
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001681 }
1682
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001683 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001684 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001685 return new (Context)
1686 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1687 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001688 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001689 return new (Context)
1690 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1691 OK_ObjCProperty, MemberLoc, BaseExpr);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001692
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001693 }
1694
1695 // Attempt to correct for typos in property names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001696 if (TypoCorrection Corrected =
1697 CorrectTypo(DeclarationNameInfo(MemberName, MemberLoc),
1698 LookupOrdinaryName, nullptr, nullptr,
1699 llvm::make_unique<DeclFilterCCC<ObjCPropertyDecl>>(),
1700 CTK_ErrorRecovery, IFace, false, OPT)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001701 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1702 << MemberName << QualType(OPT, 0));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001703 DeclarationName TypoResult = Corrected.getCorrection();
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001704 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1705 TypoResult, MemberLoc,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001706 SuperLoc, SuperType, Super);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001707 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001708 ObjCInterfaceDecl *ClassDeclared;
1709 if (ObjCIvarDecl *Ivar =
1710 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1711 QualType T = Ivar->getType();
1712 if (const ObjCObjectPointerType * OBJPT =
1713 T->getAsObjCInterfacePointerType()) {
Douglas Gregor4123a862011-11-14 22:10:01 +00001714 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001715 diag::err_property_not_as_forward_class,
1716 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001717 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001718 }
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001719 Diag(MemberLoc,
1720 diag::err_ivar_access_using_property_syntax_suggest)
1721 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1722 << FixItHint::CreateReplacement(OpLoc, "->");
1723 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001724 }
Chris Lattner90c58fa2010-04-11 07:51:10 +00001725
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001726 Diag(MemberLoc, diag::err_property_not_found)
1727 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001728 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001729 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001730 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001731 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001732}
1733
1734
1735
John McCalldadc5752010-08-24 06:29:42 +00001736ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001737ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1738 IdentifierInfo &propertyName,
1739 SourceLocation receiverNameLoc,
1740 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001741
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001742 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001743 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1744 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001745
1746 bool IsSuper = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00001747 if (!IFace) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001748 // If the "receiver" is 'super' in a method, handle it as an expression-like
1749 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001750 if (receiverNamePtr->isStr("super")) {
Douglas Gregor33823722011-06-11 01:09:30 +00001751 IsSuper = true;
1752
Eli Friedman24af8502012-02-03 22:47:37 +00001753 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001754 if (CurMethod->isInstanceMethod()) {
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00001755 ObjCInterfaceDecl *Super =
1756 CurMethod->getClassInterface()->getSuperClass();
1757 if (!Super) {
1758 // The current class does not have a superclass.
1759 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1760 << CurMethod->getClassInterface()->getIdentifier();
1761 return ExprError();
1762 }
1763 QualType T = Context.getObjCInterfaceType(Super);
Chris Lattnera36ec422010-04-11 08:28:14 +00001764 T = Context.getObjCObjectPointerType(T);
Craig Topperc3ec1492014-05-26 06:22:03 +00001765
Chris Lattnera36ec422010-04-11 08:28:14 +00001766 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001767 /*BaseExpr*/nullptr,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001768 SourceLocation()/*OpLoc*/,
1769 &propertyName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001770 propertyNameLoc,
1771 receiverNameLoc, T, true);
Chris Lattnera36ec422010-04-11 08:28:14 +00001772 }
Mike Stump11289f42009-09-09 15:08:12 +00001773
Chris Lattnera36ec422010-04-11 08:28:14 +00001774 // Otherwise, if this is a class method, try dispatching to our
1775 // superclass.
1776 IFace = CurMethod->getClassInterface()->getSuperClass();
1777 }
John McCall5f2d5562011-02-03 09:00:02 +00001778 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001779
1780 if (!IFace) {
Alp Tokerec543272013-12-24 09:48:30 +00001781 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1782 << tok::l_paren;
Chris Lattnera36ec422010-04-11 08:28:14 +00001783 return ExprError();
1784 }
1785 }
1786
1787 // Search for a declared property first.
Steve Naroff9527bbf2009-03-09 21:12:44 +00001788 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001789 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001790
1791 // If this reference is in an @implementation, check for 'private' methods.
1792 if (!Getter)
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001793 Getter = IFace->lookupPrivateClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001794
1795 if (Getter) {
1796 // FIXME: refactor/share with ActOnMemberReference().
1797 // Check if we can reference this property.
1798 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1799 return ExprError();
1800 }
Mike Stump11289f42009-09-09 15:08:12 +00001801
Steve Naroff9527bbf2009-03-09 21:12:44 +00001802 // Look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00001803 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001804 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1805 PP.getSelectorTable(),
1806 &propertyName);
Mike Stump11289f42009-09-09 15:08:12 +00001807
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001808 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001809 if (!Setter) {
1810 // If this reference is in an @implementation, also check for 'private'
1811 // methods.
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001812 Setter = IFace->lookupPrivateClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001813 }
1814 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00001815 if (!Setter)
1816 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001817
1818 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1819 return ExprError();
1820
1821 if (Getter || Setter) {
Douglas Gregor33823722011-06-11 01:09:30 +00001822 if (IsSuper)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001823 return new (Context)
1824 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1825 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
1826 Context.getObjCInterfaceType(IFace));
Douglas Gregor33823722011-06-11 01:09:30 +00001827
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001828 return new (Context) ObjCPropertyRefExpr(
1829 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
1830 propertyNameLoc, receiverNameLoc, IFace);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001831 }
1832 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1833 << &propertyName << Context.getObjCInterfaceType(IFace));
1834}
1835
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001836namespace {
1837
1838class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1839 public:
1840 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1841 // Determine whether "super" is acceptable in the current context.
1842 if (Method && Method->getClassInterface())
1843 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1844 }
1845
Craig Toppere14c0f82014-03-12 04:55:44 +00001846 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001847 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1848 candidate.isKeyword("super");
1849 }
1850};
1851
1852}
1853
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001854Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001855 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001856 SourceLocation NameLoc,
1857 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001858 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00001859 ParsedType &ReceiverType) {
1860 ReceiverType = ParsedType();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001861
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001862 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00001863 // messaging super. If the identifier is "super" and there is a
1864 // trailing dot, it's an instance message.
1865 if (IsSuper && S->isInObjcMethodScope())
1866 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001867
1868 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1869 LookupName(Result, S);
1870
1871 switch (Result.getResultKind()) {
1872 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00001873 // Normal name lookup didn't find anything. If we're in an
1874 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00001875 // FIXME: This is a hack. Ivar lookup should be part of normal
1876 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00001877 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00001878 if (!Method->getClassInterface()) {
1879 // Fall back: let the parser try to parse it as an instance message.
1880 return ObjCInstanceMessage;
1881 }
1882
Douglas Gregorca7136b2010-04-19 20:09:36 +00001883 ObjCInterfaceDecl *ClassDeclared;
1884 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1885 ClassDeclared))
1886 return ObjCInstanceMessage;
1887 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00001888
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001889 // Break out; we'll perform typo correction below.
1890 break;
1891
1892 case LookupResult::NotFoundInCurrentInstantiation:
1893 case LookupResult::FoundOverloaded:
1894 case LookupResult::FoundUnresolvedValue:
1895 case LookupResult::Ambiguous:
1896 Result.suppressDiagnostics();
1897 return ObjCInstanceMessage;
1898
1899 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00001900 // If the identifier is a class or not, and there is a trailing dot,
1901 // it's an instance message.
1902 if (HasTrailingDot)
1903 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001904 // We found something. If it's a type, then we have a class
1905 // message. Otherwise, it's an instance message.
1906 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001907 QualType T;
1908 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1909 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001910 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00001911 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001912 DiagnoseUseOfDecl(Type, NameLoc);
1913 }
1914 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00001915 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001916
Douglas Gregore5798dc2010-04-21 20:38:13 +00001917 // We have a class message, and T is the type we're
1918 // messaging. Build source-location information for it.
1919 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00001920 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00001921 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001922 }
1923 }
1924
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001925 if (TypoCorrection Corrected = CorrectTypo(
1926 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr,
1927 llvm::make_unique<ObjCInterfaceOrSuperCCC>(getCurMethodDecl()),
1928 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001929 if (Corrected.isKeyword()) {
1930 // If we've found the keyword "super" (the only keyword that would be
1931 // returned by CorrectTypo), this is a send to super.
Richard Smithf9b15102013-08-17 00:46:16 +00001932 diagnoseTypo(Corrected,
1933 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001934 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001935 } else if (ObjCInterfaceDecl *Class =
Richard Smithf9b15102013-08-17 00:46:16 +00001936 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001937 // If we found a declaration, correct when it refers to an Objective-C
1938 // class.
Richard Smithf9b15102013-08-17 00:46:16 +00001939 diagnoseTypo(Corrected,
1940 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001941 QualType T = Context.getObjCInterfaceType(Class);
1942 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1943 ReceiverType = CreateParsedType(T, TSInfo);
1944 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001945 }
1946 }
Richard Smithf9b15102013-08-17 00:46:16 +00001947
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001948 // Fall back: let the parser try to parse it as an instance message.
1949 return ObjCInstanceMessage;
1950}
Steve Naroff9527bbf2009-03-09 21:12:44 +00001951
John McCalldadc5752010-08-24 06:29:42 +00001952ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001953 SourceLocation SuperLoc,
1954 Selector Sel,
1955 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00001956 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001957 SourceLocation RBracLoc,
1958 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001959 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00001960 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00001961 if (!Method) {
1962 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1963 return ExprError();
1964 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001965
Douglas Gregor4fdba132010-04-21 20:01:04 +00001966 ObjCInterfaceDecl *Class = Method->getClassInterface();
1967 if (!Class) {
1968 Diag(SuperLoc, diag::error_no_super_class_message)
1969 << Method->getDeclName();
1970 return ExprError();
1971 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001972
Douglas Gregor4fdba132010-04-21 20:01:04 +00001973 ObjCInterfaceDecl *Super = Class->getSuperClass();
1974 if (!Super) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001975 // The current class does not have a superclass.
Ted Kremenek499897b2011-01-23 17:21:34 +00001976 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1977 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001978 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00001979 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001980
Douglas Gregor4fdba132010-04-21 20:01:04 +00001981 // We are in a method whose class has a superclass, so 'super'
1982 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00001983 if (Method->getSelector() == Sel)
1984 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00001985
Jordan Rose2afd6612012-10-19 16:05:26 +00001986 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00001987 // Since we are in an instance method, this is an instance
1988 // message to the superclass instance.
1989 QualType SuperTy = Context.getObjCInterfaceType(Super);
1990 SuperTy = Context.getObjCObjectPointerType(SuperTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00001991 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
1992 Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001993 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001994 }
Douglas Gregor4fdba132010-04-21 20:01:04 +00001995
1996 // Since we are in a class method, this is a class message to
1997 // the superclass.
Craig Topperc3ec1492014-05-26 06:22:03 +00001998 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
Douglas Gregor4fdba132010-04-21 20:01:04 +00001999 Context.getObjCInterfaceType(Super),
Craig Topperc3ec1492014-05-26 06:22:03 +00002000 SuperLoc, Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002001 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002002}
2003
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002004
2005ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2006 bool isSuperReceiver,
2007 SourceLocation Loc,
2008 Selector Sel,
2009 ObjCMethodDecl *Method,
2010 MultiExprArg Args) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002011 TypeSourceInfo *receiverTypeInfo = nullptr;
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002012 if (!ReceiverType.isNull())
2013 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2014
2015 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2016 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2017 Sel, Method, Loc, Loc, Loc, Args,
2018 /*isImplicit=*/true);
2019
2020}
2021
Ted Kremeneke65b0862012-03-06 20:05:56 +00002022static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2023 unsigned DiagID,
2024 bool (*refactor)(const ObjCMessageExpr *,
2025 const NSAPI &, edit::Commit &)) {
2026 SourceLocation MsgLoc = Msg->getExprLoc();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002027 if (S.Diags.isIgnored(DiagID, MsgLoc))
Ted Kremeneke65b0862012-03-06 20:05:56 +00002028 return;
2029
2030 SourceManager &SM = S.SourceMgr;
2031 edit::Commit ECommit(SM, S.LangOpts);
2032 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2033 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2034 << Msg->getSelector() << Msg->getSourceRange();
2035 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2036 if (!ECommit.isCommitable())
2037 return;
2038 for (edit::Commit::edit_iterator
2039 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2040 const edit::Commit::Edit &Edit = *I;
2041 switch (Edit.Kind) {
2042 case edit::Commit::Act_Insert:
2043 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2044 Edit.Text,
2045 Edit.BeforePrev));
2046 break;
2047 case edit::Commit::Act_InsertFromRange:
2048 Builder.AddFixItHint(
2049 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2050 Edit.getInsertFromRange(SM),
2051 Edit.BeforePrev));
2052 break;
2053 case edit::Commit::Act_Remove:
2054 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2055 break;
2056 }
2057 }
2058 }
2059}
2060
2061static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2062 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2063 edit::rewriteObjCRedundantCallWithLiteral);
2064}
2065
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002066/// \brief Diagnose use of %s directive in an NSString which is being passed
2067/// as formatting string to formatting method.
2068static void
2069DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2070 ObjCMethodDecl *Method,
2071 Selector Sel,
2072 Expr **Args, unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002073 unsigned Idx = 0;
2074 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002075 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2076 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002077 Idx = 0;
2078 Format = true;
2079 }
2080 else if (Method) {
2081 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2082 if (S.GetFormatNSStringIdx(I, Idx)) {
2083 Format = true;
2084 break;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002085 }
2086 }
2087 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002088 if (!Format || NumArgs <= Idx)
2089 return;
2090
2091 Expr *FormatExpr = Args[Idx];
2092 if (ObjCStringLiteral *OSL =
2093 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2094 StringLiteral *FormatString = OSL->getString();
2095 if (S.FormatStringHasSArg(FormatString)) {
2096 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2097 << "%s" << 0 << 0;
2098 if (Method)
2099 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2100 << Method->getDeclName();
2101 }
2102 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002103}
2104
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002105/// \brief Build an Objective-C class message expression.
2106///
2107/// This routine takes care of both normal class messages and
2108/// class messages to the superclass.
2109///
2110/// \param ReceiverTypeInfo Type source information that describes the
2111/// receiver of this message. This may be NULL, in which case we are
2112/// sending to the superclass and \p SuperLoc must be a valid source
2113/// location.
2114
2115/// \param ReceiverType The type of the object receiving the
2116/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2117/// type as that refers to. For a superclass send, this is the type of
2118/// the superclass.
2119///
2120/// \param SuperLoc The location of the "super" keyword in a
2121/// superclass message.
2122///
2123/// \param Sel The selector to which the message is being sent.
2124///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002125/// \param Method The method that this class message is invoking, if
2126/// already known.
2127///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002128/// \param LBracLoc The location of the opening square bracket ']'.
2129///
James Dennettffad8b72012-06-22 08:10:18 +00002130/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002131///
James Dennettffad8b72012-06-22 08:10:18 +00002132/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002133ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002134 QualType ReceiverType,
2135 SourceLocation SuperLoc,
2136 Selector Sel,
2137 ObjCMethodDecl *Method,
2138 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002139 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002140 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002141 MultiExprArg ArgsIn,
2142 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002143 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002144 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002145 if (LBracLoc.isInvalid()) {
2146 Diag(Loc, diag::err_missing_open_square_message_send)
2147 << FixItHint::CreateInsertion(Loc, "[");
2148 LBracLoc = Loc;
2149 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002150 SourceLocation SelLoc;
2151 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2152 SelLoc = SelectorLocs.front();
2153 else
2154 SelLoc = Loc;
2155
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002156 if (ReceiverType->isDependentType()) {
2157 // If the receiver type is dependent, we can't type-check anything
2158 // at this point. Build a dependent expression.
2159 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002160 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002161 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002162 return ObjCMessageExpr::Create(
2163 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2164 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2165 isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002166 }
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002167
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002168 // Find the class to which we are sending this message.
Craig Topperc3ec1492014-05-26 06:22:03 +00002169 ObjCInterfaceDecl *Class = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00002170 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2171 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002172 Diag(Loc, diag::err_invalid_receiver_class_message)
2173 << ReceiverType;
2174 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002175 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002176 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002177 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002178 if (!getLangOpts().CPlusPlus)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002179 (void)DiagnoseUseOfDecl(Class, SelLoc);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002180 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002181 if (!Method) {
Douglas Gregor4123a862011-11-14 22:10:01 +00002182 SourceRange TypeRange
2183 = SuperLoc.isValid()? SourceRange(SuperLoc)
2184 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002185 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002186 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002187 ? diag::err_arc_receiver_forward_class
2188 : diag::warn_receiver_forward_class),
2189 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002190 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorb5186b12010-04-22 17:01:48 +00002191 Method = LookupFactoryMethodInGlobalPool(Sel,
2192 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002193 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002194 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2195 << Method->getDeclName();
2196 }
2197 if (!Method)
2198 Method = Class->lookupClassMethod(Sel);
2199
2200 // If we have an implementation in scope, check "private" methods.
2201 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002202 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002203
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002204 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002205 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002206 }
Mike Stump11289f42009-09-09 15:08:12 +00002207
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002208 // Check the argument types and determine the result type.
2209 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002210 ExprValueKind VK = VK_RValue;
2211
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002212 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002213 Expr **Args = ArgsIn.data();
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002214 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2215 Sel, SelectorLocs,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00002216 Method, true,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002217 SuperLoc.isValid(), LBracLoc, RBracLoc,
2218 SourceRange(),
Douglas Gregor33823722011-06-11 01:09:30 +00002219 ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002220 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002221
Alp Toker314cc812014-01-25 16:55:45 +00002222 if (Method && !Method->getReturnType()->isVoidType() &&
2223 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002224 diag::err_illegal_message_expr_incomplete_type))
2225 return ExprError();
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002226
Fariborz Jahaniane8b45502014-08-22 19:52:49 +00002227 // Warn about explicit call of +initialize on its own class. But not on 'super'.
Fariborz Jahanian42292282014-08-25 21:27:38 +00002228 if (Method && Method->getMethodFamily() == OMF_initialize) {
2229 if (!SuperLoc.isValid()) {
2230 const ObjCInterfaceDecl *ID =
2231 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2232 if (ID == Class) {
2233 Diag(Loc, diag::warn_direct_initialize_call);
2234 Diag(Method->getLocation(), diag::note_method_declared_at)
2235 << Method->getDeclName();
2236 }
2237 }
2238 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2239 // [super initialize] is allowed only within an +initialize implementation
2240 if (CurMeth->getMethodFamily() != OMF_initialize) {
2241 Diag(Loc, diag::warn_direct_super_initialize_call);
2242 Diag(Method->getLocation(), diag::note_method_declared_at)
2243 << Method->getDeclName();
2244 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2245 << CurMeth->getDeclName();
2246 }
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002247 }
2248 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002249
2250 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2251
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002252 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002253 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002254 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002255 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002256 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002257 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002258 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002259 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002260 else {
John McCall7decc9e2010-11-18 06:31:45 +00002261 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002262 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002263 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002264 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002265 if (!isImplicit)
2266 checkCocoaAPI(*this, Result);
2267 }
Douglas Gregoraae38d62010-05-22 05:17:18 +00002268 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002269}
2270
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002271// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002272// ArgExprs is optional - if it is present, the number of expressions
2273// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002274ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002275 ParsedType Receiver,
2276 Selector Sel,
2277 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002278 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002279 SourceLocation RBracLoc,
2280 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002281 TypeSourceInfo *ReceiverTypeInfo;
2282 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2283 if (ReceiverType.isNull())
2284 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002285
Mike Stump11289f42009-09-09 15:08:12 +00002286
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002287 if (!ReceiverTypeInfo)
2288 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2289
2290 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002291 /*SuperLoc=*/SourceLocation(), Sel,
2292 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2293 Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002294}
2295
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002296ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2297 QualType ReceiverType,
2298 SourceLocation Loc,
2299 Selector Sel,
2300 ObjCMethodDecl *Method,
2301 MultiExprArg Args) {
2302 return BuildInstanceMessage(Receiver, ReceiverType,
2303 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2304 Sel, Method, Loc, Loc, Loc, Args,
2305 /*isImplicit=*/true);
2306}
2307
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002308/// \brief Build an Objective-C instance message expression.
2309///
2310/// This routine takes care of both normal instance messages and
2311/// instance messages to the superclass instance.
2312///
2313/// \param Receiver The expression that computes the object that will
2314/// receive this message. This may be empty, in which case we are
2315/// sending to the superclass instance and \p SuperLoc must be a valid
2316/// source location.
2317///
2318/// \param ReceiverType The (static) type of the object receiving the
2319/// message. When a \p Receiver expression is provided, this is the
2320/// same type as that expression. For a superclass instance send, this
2321/// is a pointer to the type of the superclass.
2322///
2323/// \param SuperLoc The location of the "super" keyword in a
2324/// superclass instance message.
2325///
2326/// \param Sel The selector to which the message is being sent.
2327///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002328/// \param Method The method that this instance message is invoking, if
2329/// already known.
2330///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002331/// \param LBracLoc The location of the opening square bracket ']'.
2332///
James Dennettffad8b72012-06-22 08:10:18 +00002333/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002334///
James Dennettffad8b72012-06-22 08:10:18 +00002335/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002336ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002337 QualType ReceiverType,
2338 SourceLocation SuperLoc,
2339 Selector Sel,
2340 ObjCMethodDecl *Method,
2341 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002342 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002343 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002344 MultiExprArg ArgsIn,
2345 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002346 // The location of the receiver.
2347 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002348 SourceRange RecRange =
2349 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2350 SourceLocation SelLoc;
2351 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2352 SelLoc = SelectorLocs.front();
2353 else
2354 SelLoc = Loc;
2355
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002356 if (LBracLoc.isInvalid()) {
2357 Diag(Loc, diag::err_missing_open_square_message_send)
2358 << FixItHint::CreateInsertion(Loc, "[");
2359 LBracLoc = Loc;
2360 }
2361
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002362 // If we have a receiver expression, perform appropriate promotions
2363 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002364 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002365 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002366 ExprResult Result;
2367 if (Receiver->getType() == Context.UnknownAnyTy)
2368 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2369 else
2370 Result = CheckPlaceholderExpr(Receiver);
2371 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002372 Receiver = Result.get();
John McCall4124c492011-10-17 18:40:02 +00002373 }
2374
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002375 if (Receiver->isTypeDependent()) {
2376 // If the receiver is type-dependent, we can't type-check anything
2377 // at this point. Build a dependent expression.
2378 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002379 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002380 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002381 return ObjCMessageExpr::Create(
2382 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2383 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2384 RBracLoc, isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002385 }
2386
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002387 // If necessary, apply function/array conversion to the receiver.
2388 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002389 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2390 if (Result.isInvalid())
2391 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002392 Receiver = Result.get();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002393 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002394
2395 // If the receiver is an ObjC pointer, a block pointer, or an
2396 // __attribute__((NSObject)) pointer, we don't need to do any
2397 // special conversion in order to look up a receiver.
2398 if (ReceiverType->isObjCRetainableType()) {
2399 // do nothing
2400 } else if (!getLangOpts().ObjCAutoRefCount &&
2401 !Context.getObjCIdType().isNull() &&
2402 (ReceiverType->isPointerType() ||
2403 ReceiverType->isIntegerType())) {
2404 // Implicitly convert integers and pointers to 'id' but emit a warning.
2405 // But not in ARC.
2406 Diag(Loc, diag::warn_bad_receiver_type)
2407 << ReceiverType
2408 << Receiver->getSourceRange();
2409 if (ReceiverType->isPointerType()) {
2410 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002411 CK_CPointerToObjCPointerCast).get();
John McCall80c93a02013-03-01 09:20:14 +00002412 } else {
2413 // TODO: specialized warning on null receivers?
2414 bool IsNull = Receiver->isNullPointerConstant(Context,
2415 Expr::NPC_ValueDependentIsNull);
2416 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2417 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002418 Kind).get();
John McCall80c93a02013-03-01 09:20:14 +00002419 }
2420 ReceiverType = Receiver->getType();
2421 } else if (getLangOpts().CPlusPlus) {
Douglas Gregor4b60a152013-11-07 22:34:54 +00002422 // The receiver must be a complete type.
2423 if (RequireCompleteType(Loc, Receiver->getType(),
2424 diag::err_incomplete_receiver_type))
2425 return ExprError();
2426
John McCall80c93a02013-03-01 09:20:14 +00002427 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2428 if (result.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002429 Receiver = result.get();
John McCall80c93a02013-03-01 09:20:14 +00002430 ReceiverType = Receiver->getType();
2431 }
2432 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002433 }
2434
John McCall80c93a02013-03-01 09:20:14 +00002435 // There's a somewhat weird interaction here where we assume that we
2436 // won't actually have a method unless we also don't need to do some
2437 // of the more detailed type-checking on the receiver.
2438
Douglas Gregorb5186b12010-04-22 17:01:48 +00002439 if (!Method) {
2440 // Handle messages to id.
Fariborz Jahanian32e59ba2010-08-10 18:10:50 +00002441 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002442 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002443 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2444 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002445 SourceRange(LBracLoc, RBracLoc),
2446 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002447 if (!Method)
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002448 Method = LookupFactoryMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002449 SourceRange(LBracLoc,RBracLoc),
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002450 receiverIsId);
Fariborz Jahanian05e77f82014-11-07 23:51:15 +00002451 if (Method) {
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002452 if (ObjCMethodDecl *BestMethod =
Fariborz Jahaniand288fad2014-08-13 23:38:04 +00002453 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002454 Method = BestMethod;
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00002455 if (!AreMultipleMethodsInGlobalPool(Sel, Method->isInstanceMethod()))
Fariborz Jahanian05e77f82014-11-07 23:51:15 +00002456 DiagnoseUseOfDecl(Method, SelLoc);
2457 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002458 } else if (ReceiverType->isObjCClassType() ||
2459 ReceiverType->isObjCQualifiedClassType()) {
2460 // Handle messages to Class.
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002461 // We allow sending a message to a qualified Class ("Class<foo>"), which
2462 // is ok as long as one of the protocols implements the selector (if not, warn).
2463 if (const ObjCObjectPointerType *QClassTy
2464 = ReceiverType->getAsObjCQualifiedClassType()) {
2465 // Search protocols for class methods.
2466 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2467 if (!Method) {
2468 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2469 // warn if instance method found for a Class message.
2470 if (Method) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002471 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002472 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002473 Diag(Method->getLocation(), diag::note_method_declared_at)
2474 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002475 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002476 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002477 } else {
2478 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2479 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2480 // First check the public methods in the class interface.
2481 Method = ClassDecl->lookupClassMethod(Sel);
2482
2483 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002484 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002485 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002486 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002487 return ExprError();
2488 }
2489 if (!Method) {
2490 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002491 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002492 Method = LookupFactoryMethodInGlobalPool(Sel,
2493 SourceRange(LBracLoc, RBracLoc),
2494 true);
2495 if (!Method) {
2496 // If no class (factory) method was found, check if an _instance_
2497 // method of the same name exists in the root class only.
2498 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002499 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002500 true);
2501 if (Method)
2502 if (const ObjCInterfaceDecl *ID =
2503 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2504 if (ID->getSuperClass())
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002505 Diag(SelLoc, diag::warn_root_inst_method_not_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002506 << Sel << SourceRange(LBracLoc, RBracLoc);
2507 }
2508 }
Fariborz Jahaniand288fad2014-08-13 23:38:04 +00002509 if (Method)
2510 if (ObjCMethodDecl *BestMethod =
2511 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
2512 Method = BestMethod;
Douglas Gregor9a129192010-04-21 00:45:42 +00002513 }
2514 }
2515 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002516 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002517 ObjCInterfaceDecl *ClassDecl = nullptr;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002518
2519 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2520 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002521 // And as long as message is not deprecated/unavailable (warn if it is).
Douglas Gregorb5186b12010-04-22 17:01:48 +00002522 if (const ObjCObjectPointerType *QIdTy
2523 = ReceiverType->getAsObjCQualifiedIdType()) {
2524 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002525 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2526 if (!Method)
2527 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002528 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002529 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002530 } else if (const ObjCObjectPointerType *OCIType
2531 = ReceiverType->getAsObjCInterfacePointerType()) {
2532 // We allow sending a message to a pointer to an interface (an object).
2533 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002534
Douglas Gregor4123a862011-11-14 22:10:01 +00002535 // Try to complete the type. Under ARC, this is a hard error from which
2536 // we don't try to recover.
Craig Topperc3ec1492014-05-26 06:22:03 +00002537 const ObjCInterfaceDecl *forwardClass = nullptr;
Douglas Gregor4123a862011-11-14 22:10:01 +00002538 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002539 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002540 ? diag::err_arc_receiver_forward_instance
2541 : diag::warn_receiver_forward_instance,
2542 Receiver? Receiver->getSourceRange()
2543 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002544 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002545 return ExprError();
2546
2547 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanianc934de62012-02-03 01:02:44 +00002548 Diag(Receiver ? Receiver->getLocStart()
2549 : SuperLoc, diag::note_receiver_is_id);
Craig Topperc3ec1492014-05-26 06:22:03 +00002550 Method = nullptr;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002551 } else {
2552 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002553 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002554
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002555 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002556 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002557 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2558
Douglas Gregorb5186b12010-04-22 17:01:48 +00002559 if (!Method) {
2560 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002561 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002562
David Blaikiebbafb8a2012-03-11 07:00:24 +00002563 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002564 Diag(SelLoc, diag::err_arc_may_not_respond)
2565 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002566 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002567 return ExprError();
2568 }
2569
Douglas Gregor486b74e2011-09-27 16:10:05 +00002570 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002571 // If we still haven't found a method, look in the global pool. This
2572 // behavior isn't very desirable, however we need it for GCC
2573 // compatibility. FIXME: should we deviate??
2574 if (OCIType->qual_empty()) {
2575 Method = LookupInstanceMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002576 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002577 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002578 Diag(SelLoc, diag::warn_maynot_respond)
2579 << OCIType->getInterfaceDecl()->getIdentifier()
2580 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002581 }
2582 }
2583 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002584 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002585 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002586 } else {
John McCall80c93a02013-03-01 09:20:14 +00002587 // Reject other random receiver types (e.g. structs).
2588 Diag(Loc, diag::err_bad_receiver_type)
2589 << ReceiverType << Receiver->getSourceRange();
2590 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002591 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002592 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002593 }
Mike Stump11289f42009-09-09 15:08:12 +00002594
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002595 FunctionScopeInfo *DIFunctionScopeInfo =
2596 (Method && Method->getMethodFamily() == OMF_init)
Craig Topperc3ec1492014-05-26 06:22:03 +00002597 ? getEnclosingFunction() : nullptr;
2598
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002599 if (DIFunctionScopeInfo &&
2600 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002601 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2602 bool isDesignatedInitChain = false;
2603 if (SuperLoc.isValid()) {
2604 if (const ObjCObjectPointerType *
2605 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2606 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
Argyrios Kyrtzidisd664a342013-12-13 03:48:17 +00002607 // Either we know this is a designated initializer or we
2608 // conservatively assume it because we don't know for sure.
2609 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2610 ID->isDesignatedInitializer(Sel)) {
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002611 isDesignatedInitChain = true;
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002612 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002613 }
2614 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002615 }
2616 }
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002617 if (!isDesignatedInitChain) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002618 const ObjCMethodDecl *InitMethod = nullptr;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002619 bool isDesignated =
2620 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2621 assert(isDesignated && InitMethod);
2622 (void)isDesignated;
2623 Diag(SelLoc, SuperLoc.isValid() ?
2624 diag::warn_objc_designated_init_non_designated_init_call :
2625 diag::warn_objc_designated_init_non_super_designated_init_call);
2626 Diag(InitMethod->getLocation(),
2627 diag::note_objc_designated_init_marked_here);
2628 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002629 }
2630
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002631 if (DIFunctionScopeInfo &&
2632 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002633 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2634 if (SuperLoc.isValid()) {
2635 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2636 } else {
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002637 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002638 }
2639 }
2640
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002641 // Check the message arguments.
2642 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002643 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002644 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002645 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00002646 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2647 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002648 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2649 Sel, SelectorLocs, Method,
Douglas Gregor33823722011-06-11 01:09:30 +00002650 ClassMessage, SuperLoc.isValid(),
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002651 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002652 return ExprError();
Alp Toker314cc812014-01-25 16:55:45 +00002653
2654 if (Method && !Method->getReturnType()->isVoidType() &&
2655 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002656 diag::err_illegal_message_expr_incomplete_type))
2657 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00002658
John McCall31168b02011-06-15 23:02:42 +00002659 // In ARC, forbid the user from sending messages to
2660 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002661 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002662 ObjCMethodFamily family =
2663 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2664 switch (family) {
2665 case OMF_init:
2666 if (Method)
2667 checkInitMethod(Method, ReceiverType);
2668
2669 case OMF_None:
2670 case OMF_alloc:
2671 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00002672 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002673 case OMF_mutableCopy:
2674 case OMF_new:
2675 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002676 case OMF_initialize:
John McCall31168b02011-06-15 23:02:42 +00002677 break;
2678
2679 case OMF_dealloc:
2680 case OMF_retain:
2681 case OMF_release:
2682 case OMF_autorelease:
2683 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002684 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2685 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00002686 break;
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002687
2688 case OMF_performSelector:
2689 if (Method && NumArgs >= 1) {
2690 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2691 Selector ArgSel = SelExp->getSelector();
2692 ObjCMethodDecl *SelMethod =
2693 LookupInstanceMethodInGlobalPool(ArgSel,
2694 SelExp->getSourceRange());
2695 if (!SelMethod)
2696 SelMethod =
2697 LookupFactoryMethodInGlobalPool(ArgSel,
2698 SelExp->getSourceRange());
2699 if (SelMethod) {
2700 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2701 switch (SelFamily) {
2702 case OMF_alloc:
2703 case OMF_copy:
2704 case OMF_mutableCopy:
2705 case OMF_new:
2706 case OMF_self:
2707 case OMF_init:
2708 // Issue error, unless ns_returns_not_retained.
2709 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2710 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002711 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002712 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002713 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2714 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002715 }
2716 break;
2717 default:
2718 // +0 call. OK. unless ns_returns_retained.
2719 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2720 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002721 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002722 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002723 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2724 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002725 }
2726 break;
2727 }
2728 }
2729 } else {
2730 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002731 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002732 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2733 }
2734 }
2735 break;
John McCall31168b02011-06-15 23:02:42 +00002736 }
2737 }
2738
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002739 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2740
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002741 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00002742 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002743 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002744 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002745 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002746 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002747 makeArrayRef(Args, NumArgs), RBracLoc,
2748 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002749 else {
John McCall7decc9e2010-11-18 06:31:45 +00002750 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002751 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002752 makeArrayRef(Args, NumArgs), RBracLoc,
2753 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002754 if (!isImplicit)
2755 checkCocoaAPI(*this, Result);
2756 }
John McCall31168b02011-06-15 23:02:42 +00002757
David Blaikiebbafb8a2012-03-11 07:00:24 +00002758 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahanian9277ff42014-06-17 23:35:13 +00002759 // Do not warn about IBOutlet weak property receivers being set to null
2760 // as this cannot asynchronously happen.
2761 bool WarnWeakReceiver = true;
2762 if (isImplicit && Method)
2763 if (const ObjCPropertyDecl *PropertyDecl = Method->findPropertyDecl())
2764 WarnWeakReceiver = !PropertyDecl->hasAttr<IBOutletAttr>();
2765 if (WarnWeakReceiver)
2766 DiagnoseARCUseOfWeakReceiver(*this, Receiver);
Fariborz Jahanian6bd22262012-04-04 20:05:25 +00002767
John McCall31168b02011-06-15 23:02:42 +00002768 // In ARC, annotate delegate init calls.
2769 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00002770 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00002771 // Only consider init calls *directly* in init implementations,
2772 // not within blocks.
2773 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2774 if (method && method->getMethodFamily() == OMF_init) {
2775 // The implicit assignment to self means we also don't want to
2776 // consume the result.
2777 Result->setDelegateInitCall(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002778 return Result;
John McCall31168b02011-06-15 23:02:42 +00002779 }
2780 }
2781
2782 // In ARC, check for message sends which are likely to introduce
2783 // retain cycles.
2784 checkRetainCycles(Result);
Jordan Rose22487652012-10-11 16:06:21 +00002785
2786 if (!isImplicit && Method) {
2787 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2788 bool IsWeak =
2789 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2790 if (!IsWeak && Sel.isUnarySelector())
2791 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002792 if (IsWeak &&
2793 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
2794 getCurFunction()->recordUseOfWeak(Result, Prop);
Jordan Rose22487652012-10-11 16:06:21 +00002795 }
2796 }
John McCall31168b02011-06-15 23:02:42 +00002797 }
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00002798
Douglas Gregoraae38d62010-05-22 05:17:18 +00002799 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002800}
2801
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002802static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2803 if (ObjCSelectorExpr *OSE =
2804 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2805 Selector Sel = OSE->getSelector();
2806 SourceLocation Loc = OSE->getAtLoc();
2807 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
2808 = S.ReferencedSelectors.find(Sel);
2809 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
2810 S.ReferencedSelectors.erase(Pos);
2811 }
2812}
2813
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002814// ActOnInstanceMessage - used for both unary and keyword messages.
2815// ArgExprs is optional - if it is present, the number of expressions
2816// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002817ExprResult Sema::ActOnInstanceMessage(Scope *S,
2818 Expr *Receiver,
2819 Selector Sel,
2820 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002821 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00002822 SourceLocation RBracLoc,
2823 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002824 if (!Receiver)
2825 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002826
2827 // A ParenListExpr can show up while doing error recovery with invalid code.
2828 if (isa<ParenListExpr>(Receiver)) {
2829 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
2830 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002831 Receiver = Result.get();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002832 }
Fariborz Jahanian17748062013-01-22 19:05:17 +00002833
2834 if (RespondsToSelectorSel.isNull()) {
2835 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
2836 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
2837 }
2838 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002839 RemoveSelectorFromWarningCache(*this, Args[0]);
Craig Topperc3ec1492014-05-26 06:22:03 +00002840
John McCallb268a282010-08-23 23:25:46 +00002841 return BuildInstanceMessage(Receiver, Receiver->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002842 /*SuperLoc=*/SourceLocation(), Sel,
2843 /*Method=*/nullptr, LBracLoc, SelectorLocs,
2844 RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002845}
Chris Lattner2a3569b2008-04-07 05:30:13 +00002846
John McCall31168b02011-06-15 23:02:42 +00002847enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00002848 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00002849 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00002850
2851 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00002852 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00002853
2854 /// id*, id***, void (^*)(),
2855 ACTC_indirectRetainable,
2856
2857 /// void* might be a normal C type, or it might a CF type.
2858 ACTC_voidPtr,
2859
2860 /// struct A*
2861 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00002862};
John McCalle4fe2452011-10-01 01:01:08 +00002863static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2864 return (ACTC == ACTC_retainable ||
2865 ACTC == ACTC_coreFoundation ||
2866 ACTC == ACTC_voidPtr);
2867}
2868static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2869 return ACTC == ACTC_none ||
2870 ACTC == ACTC_voidPtr ||
2871 ACTC == ACTC_coreFoundation;
2872}
2873
John McCall31168b02011-06-15 23:02:42 +00002874static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00002875 bool isIndirect = false;
John McCall31168b02011-06-15 23:02:42 +00002876
2877 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00002878 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00002879 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002880 isIndirect = true;
2881 }
John McCall31168b02011-06-15 23:02:42 +00002882
2883 // Drill through pointers and arrays recursively.
2884 while (true) {
2885 if (const PointerType *ptr = type->getAs<PointerType>()) {
2886 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002887
2888 // The first level of pointer may be the innermost pointer on a CF type.
2889 if (!isIndirect) {
2890 if (type->isVoidType()) return ACTC_voidPtr;
2891 if (type->isRecordType()) return ACTC_coreFoundation;
2892 }
John McCall31168b02011-06-15 23:02:42 +00002893 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2894 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2895 } else {
2896 break;
2897 }
John McCalle4fe2452011-10-01 01:01:08 +00002898 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00002899 }
2900
John McCalle4fe2452011-10-01 01:01:08 +00002901 if (isIndirect) {
2902 if (type->isObjCARCBridgableType())
2903 return ACTC_indirectRetainable;
2904 return ACTC_none;
2905 }
2906
2907 if (type->isObjCARCBridgableType())
2908 return ACTC_retainable;
2909
2910 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00002911}
2912
2913namespace {
John McCalle4fe2452011-10-01 01:01:08 +00002914 /// A result from the cast checker.
2915 enum ACCResult {
2916 /// Cannot be casted.
2917 ACC_invalid,
2918
2919 /// Can be safely retained or not retained.
2920 ACC_bottom,
2921
2922 /// Can be casted at +0.
2923 ACC_plusZero,
2924
2925 /// Can be casted at +1.
2926 ACC_plusOne
2927 };
2928 ACCResult merge(ACCResult left, ACCResult right) {
2929 if (left == right) return left;
2930 if (left == ACC_bottom) return right;
2931 if (right == ACC_bottom) return left;
2932 return ACC_invalid;
2933 }
2934
2935 /// A checker which white-lists certain expressions whose conversion
2936 /// to or from retainable type would otherwise be forbidden in ARC.
2937 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2938 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2939
John McCall31168b02011-06-15 23:02:42 +00002940 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00002941 ARCConversionTypeClass SourceClass;
2942 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002943 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00002944
2945 static bool isCFType(QualType type) {
2946 // Someday this can use ns_bridged. For now, it has to do this.
2947 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00002948 }
John McCalle4fe2452011-10-01 01:01:08 +00002949
2950 public:
2951 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002952 ARCConversionTypeClass target, bool diagnose)
2953 : Context(Context), SourceClass(source), TargetClass(target),
2954 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00002955
2956 using super::Visit;
2957 ACCResult Visit(Expr *e) {
2958 return super::Visit(e->IgnoreParens());
2959 }
2960
2961 ACCResult VisitStmt(Stmt *s) {
2962 return ACC_invalid;
2963 }
2964
2965 /// Null pointer constants can be casted however you please.
2966 ACCResult VisitExpr(Expr *e) {
2967 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2968 return ACC_bottom;
2969 return ACC_invalid;
2970 }
2971
2972 /// Objective-C string literals can be safely casted.
2973 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2974 // If we're casting to any retainable type, go ahead. Global
2975 // strings are immune to retains, so this is bottom.
2976 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2977
2978 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002979 }
2980
John McCalle4fe2452011-10-01 01:01:08 +00002981 /// Look through certain implicit and explicit casts.
2982 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002983 switch (e->getCastKind()) {
2984 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00002985 return ACC_bottom;
2986
John McCall31168b02011-06-15 23:02:42 +00002987 case CK_NoOp:
2988 case CK_LValueToRValue:
2989 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002990 case CK_CPointerToObjCPointerCast:
2991 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002992 case CK_AnyPointerToBlockPointerCast:
2993 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00002994
John McCall31168b02011-06-15 23:02:42 +00002995 default:
John McCalle4fe2452011-10-01 01:01:08 +00002996 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002997 }
2998 }
John McCalle4fe2452011-10-01 01:01:08 +00002999
3000 /// Look through unary extension.
3001 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003002 return Visit(e->getSubExpr());
3003 }
John McCalle4fe2452011-10-01 01:01:08 +00003004
3005 /// Ignore the LHS of a comma operator.
3006 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003007 return Visit(e->getRHS());
3008 }
John McCalle4fe2452011-10-01 01:01:08 +00003009
3010 /// Conditional operators are okay if both sides are okay.
3011 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3012 ACCResult left = Visit(e->getTrueExpr());
3013 if (left == ACC_invalid) return ACC_invalid;
3014 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00003015 }
John McCalle4fe2452011-10-01 01:01:08 +00003016
John McCallfe96e0b2011-11-06 09:01:30 +00003017 /// Look through pseudo-objects.
3018 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3019 // If we're getting here, we should always have a result.
3020 return Visit(e->getResultExpr());
3021 }
3022
John McCalle4fe2452011-10-01 01:01:08 +00003023 /// Statement expressions are okay if their result expression is okay.
3024 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003025 return Visit(e->getSubStmt()->body_back());
3026 }
John McCall31168b02011-06-15 23:02:42 +00003027
John McCalle4fe2452011-10-01 01:01:08 +00003028 /// Some declaration references are okay.
3029 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
3030 // References to global constants from system headers are okay.
3031 // These are things like 'kCFStringTransformToLatin'. They are
3032 // can also be assumed to be immune to retains.
3033 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
3034 if (isAnyRetainable(TargetClass) &&
3035 isAnyRetainable(SourceClass) &&
3036 var &&
3037 var->getStorageClass() == SC_Extern &&
3038 var->getType().isConstQualified() &&
3039 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
3040 return ACC_bottom;
3041 }
3042
3043 // Nothing else.
3044 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00003045 }
John McCalle4fe2452011-10-01 01:01:08 +00003046
3047 /// Some calls are okay.
3048 ACCResult VisitCallExpr(CallExpr *e) {
3049 if (FunctionDecl *fn = e->getDirectCallee())
3050 if (ACCResult result = checkCallToFunction(fn))
3051 return result;
3052
3053 return super::VisitCallExpr(e);
3054 }
3055
3056 ACCResult checkCallToFunction(FunctionDecl *fn) {
3057 // Require a CF*Ref return type.
Alp Toker314cc812014-01-25 16:55:45 +00003058 if (!isCFType(fn->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003059 return ACC_invalid;
3060
3061 if (!isAnyRetainable(TargetClass))
3062 return ACC_invalid;
3063
3064 // Honor an explicit 'not retained' attribute.
3065 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3066 return ACC_plusZero;
3067
3068 // Honor an explicit 'retained' attribute, except that for
3069 // now we're not going to permit implicit handling of +1 results,
3070 // because it's a bit frightening.
3071 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003072 return Diagnose ? ACC_plusOne
3073 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003074
3075 // Recognize this specific builtin function, which is used by CFSTR.
3076 unsigned builtinID = fn->getBuiltinID();
3077 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3078 return ACC_bottom;
3079
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003080 // Otherwise, don't do anything implicit with an unaudited function.
3081 if (!fn->hasAttr<CFAuditedTransferAttr>())
3082 return ACC_invalid;
3083
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003084 // Otherwise, it's +0 unless it follows the create convention.
3085 if (ento::coreFoundation::followsCreateRule(fn))
3086 return Diagnose ? ACC_plusOne
3087 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003088
John McCalle4fe2452011-10-01 01:01:08 +00003089 return ACC_plusZero;
3090 }
3091
3092 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3093 return checkCallToMethod(e->getMethodDecl());
3094 }
3095
3096 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3097 ObjCMethodDecl *method;
3098 if (e->isExplicitProperty())
3099 method = e->getExplicitProperty()->getGetterMethodDecl();
3100 else
3101 method = e->getImplicitPropertyGetter();
3102 return checkCallToMethod(method);
3103 }
3104
3105 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3106 if (!method) return ACC_invalid;
3107
3108 // Check for message sends to functions returning CF types. We
3109 // just obey the Cocoa conventions with these, even though the
3110 // return type is CF.
Alp Toker314cc812014-01-25 16:55:45 +00003111 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003112 return ACC_invalid;
3113
3114 // If the method is explicitly marked not-retained, it's +0.
3115 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3116 return ACC_plusZero;
3117
3118 // If the method is explicitly marked as returning retained, or its
3119 // selector follows a +1 Cocoa convention, treat it as +1.
3120 if (method->hasAttr<CFReturnsRetainedAttr>())
3121 return ACC_plusOne;
3122
3123 switch (method->getSelector().getMethodFamily()) {
3124 case OMF_alloc:
3125 case OMF_copy:
3126 case OMF_mutableCopy:
3127 case OMF_new:
3128 return ACC_plusOne;
3129
3130 default:
3131 // Otherwise, treat it as +0.
3132 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00003133 }
3134 }
John McCalle4fe2452011-10-01 01:01:08 +00003135 };
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00003136}
3137
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003138bool Sema::isKnownName(StringRef name) {
3139 if (name.empty())
3140 return false;
3141 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003142 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003143 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003144}
3145
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003146static void addFixitForObjCARCConversion(Sema &S,
3147 DiagnosticBuilder &DiagB,
3148 Sema::CheckedConversionKind CCK,
3149 SourceLocation afterLParen,
3150 QualType castType,
3151 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003152 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003153 const char *bridgeKeyword,
3154 const char *CFBridgeName) {
3155 // We handle C-style and implicit casts here.
3156 switch (CCK) {
3157 case Sema::CCK_ImplicitConversion:
3158 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003159 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003160 break;
3161 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003162 return;
3163 }
3164
3165 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003166 if (CCK == Sema::CCK_OtherCast) {
3167 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3168 SourceRange range(NCE->getOperatorLoc(),
3169 NCE->getAngleBrackets().getEnd());
3170 SmallString<32> BridgeCall;
3171
3172 SourceManager &SM = S.getSourceManager();
3173 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3174 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3175 BridgeCall += ' ';
3176
3177 BridgeCall += CFBridgeName;
3178 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3179 }
3180 return;
3181 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003182 Expr *castedE = castExpr;
3183 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3184 castedE = CCE->getSubExpr();
3185 castedE = castedE->IgnoreImpCasts();
3186 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00003187
3188 SmallString<32> BridgeCall;
3189
3190 SourceManager &SM = S.getSourceManager();
3191 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3192 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3193 BridgeCall += ' ';
3194
3195 BridgeCall += CFBridgeName;
3196
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003197 if (isa<ParenExpr>(castedE)) {
3198 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003199 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003200 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00003201 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003202 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003203 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003204 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3205 S.PP.getLocForEndOfToken(range.getEnd()),
3206 ")"));
3207 }
3208 return;
3209 }
3210
3211 if (CCK == Sema::CCK_CStyleCast) {
3212 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003213 } else if (CCK == Sema::CCK_OtherCast) {
3214 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3215 std::string castCode = "(";
3216 castCode += bridgeKeyword;
3217 castCode += castType.getAsString();
3218 castCode += ")";
3219 SourceRange Range(NCE->getOperatorLoc(),
3220 NCE->getAngleBrackets().getEnd());
3221 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3222 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003223 } else {
3224 std::string castCode = "(";
3225 castCode += bridgeKeyword;
3226 castCode += castType.getAsString();
3227 castCode += ")";
3228 Expr *castedE = castExpr->IgnoreImpCasts();
3229 SourceRange range = castedE->getSourceRange();
3230 if (isa<ParenExpr>(castedE)) {
3231 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3232 castCode));
3233 } else {
3234 castCode += "(";
3235 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3236 castCode));
3237 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3238 S.PP.getLocForEndOfToken(range.getEnd()),
3239 ")"));
3240 }
3241 }
3242}
3243
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003244template <typename T>
3245static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3246 TypedefNameDecl *TDNDecl = TD->getDecl();
3247 QualType QT = TDNDecl->getUnderlyingType();
3248 if (QT->isPointerType()) {
3249 QT = QT->getPointeeType();
3250 if (const RecordType *RT = QT->getAs<RecordType>())
Fariborz Jahanian9af6a782014-06-11 19:10:46 +00003251 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
Aaron Ballman2084f8f2013-12-19 13:20:36 +00003252 return RD->getAttr<T>();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003253 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003254 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003255}
3256
3257static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3258 TypedefNameDecl *&TDNDecl) {
3259 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3260 TDNDecl = TD->getDecl();
3261 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3262 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3263 return ObjCBAttr;
3264 T = TDNDecl->getUnderlyingType();
3265 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003266 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003267}
3268
John McCall4124c492011-10-17 18:40:02 +00003269static void
3270diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3271 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003272 Expr *castExpr, Expr *realCast,
3273 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003274 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003275 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003276 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00003277
John McCall4124c492011-10-17 18:40:02 +00003278 if (S.makeUnavailableInSystemHeader(loc,
John McCalle4fe2452011-10-01 01:01:08 +00003279 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCall31168b02011-06-15 23:02:42 +00003280 return;
John McCall4124c492011-10-17 18:40:02 +00003281
3282 QualType castExprType = castExpr->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003283 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003284 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3285 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3286 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
Fariborz Jahanian1ad83a32014-06-18 23:22:38 +00003287 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003288 return;
John McCall31168b02011-06-15 23:02:42 +00003289
John McCall640767f2011-06-17 06:50:50 +00003290 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003291 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003292 case ACTC_none:
3293 case ACTC_coreFoundation:
3294 case ACTC_voidPtr:
3295 srcKind = (castExprType->isPointerType() ? 1 : 0);
3296 break;
3297 case ACTC_retainable:
3298 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3299 break;
3300 case ACTC_indirectRetainable:
3301 srcKind = 4;
3302 break;
John McCall31168b02011-06-15 23:02:42 +00003303 }
3304
John McCall4124c492011-10-17 18:40:02 +00003305 // Check whether this could be fixed with a bridge cast.
3306 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3307 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003308
John McCall4124c492011-10-17 18:40:02 +00003309 // Bridge from an ARC type to a CF type.
3310 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003311
John McCall4124c492011-10-17 18:40:02 +00003312 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3313 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3314 << 2 // of C pointer type
3315 << castExprType
3316 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3317 << castType
3318 << castRange
3319 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003320 bool br = S.isKnownName("CFBridgingRelease");
Jordan Rose4502b532012-07-31 01:07:43 +00003321 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003322 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003323 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003324 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003325 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003326 DiagnosticBuilder DiagB =
3327 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3328 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Craig Topperc3ec1492014-05-26 06:22:03 +00003329
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003330 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003331 castType, castExpr, realCast, "__bridge ",
3332 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003333 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003334 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003335 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003336 DiagnosticBuilder DiagB =
3337 (CCK == Sema::CCK_OtherCast && !br) ?
3338 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3339 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3340 diag::note_arc_bridge_transfer)
3341 << castExprType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003342
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003343 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003344 castType, castExpr, realCast, "__bridge_transfer ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003345 br ? "CFBridgingRelease" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003346 }
John McCall4124c492011-10-17 18:40:02 +00003347
3348 return;
3349 }
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003350
John McCall4124c492011-10-17 18:40:02 +00003351 // Bridge from a CF type to an ARC type.
3352 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003353 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003354 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3355 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3356 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3357 << castExprType
3358 << 2 // to C pointer type
3359 << castType
3360 << castRange
3361 << castExpr->getSourceRange();
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003362 ACCResult CreateRule =
3363 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003364 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003365 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003366 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003367 DiagnosticBuilder DiagB =
3368 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3369 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003370 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003371 castType, castExpr, realCast, "__bridge ",
3372 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003373 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003374 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003375 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003376 DiagnosticBuilder DiagB =
3377 (CCK == Sema::CCK_OtherCast && !br) ?
3378 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3379 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3380 diag::note_arc_bridge_retained)
3381 << castType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003382
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003383 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003384 castType, castExpr, realCast, "__bridge_retained ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003385 br ? "CFBridgingRetain" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003386 }
John McCall4124c492011-10-17 18:40:02 +00003387
3388 return;
John McCall31168b02011-06-15 23:02:42 +00003389 }
3390
John McCall4124c492011-10-17 18:40:02 +00003391 S.Diag(loc, diag::err_arc_mismatched_cast)
3392 << (CCK != Sema::CCK_ImplicitConversion)
3393 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003394 << castRange << castExpr->getSourceRange();
3395}
3396
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003397template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003398static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3399 bool &HadTheAttribute, bool warn) {
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003400 QualType T = castExpr->getType();
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003401 HadTheAttribute = false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003402 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3403 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003404 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003405 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003406 HadTheAttribute = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003407 NamedDecl *Target = nullptr;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003408 // Check for an existing type with this name.
3409 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3410 Sema::LookupOrdinaryName);
3411 if (S.LookupName(R, S.TUScope)) {
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003412 Target = R.getFoundDecl();
3413 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3414 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3415 if (const ObjCObjectPointerType *InterfacePointerType =
3416 castType->getAsObjCInterfacePointerType()) {
3417 ObjCInterfaceDecl *CastClass
3418 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003419 if ((CastClass == ExprClass) ||
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003420 (CastClass && ExprClass->isSuperClassOf(CastClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003421 return true;
3422 if (warn)
3423 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3424 << T << Target->getName() << castType->getPointeeType();
3425 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003426 } else if (castType->isObjCIdType() ||
3427 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3428 castType, ExprClass)))
3429 // ok to cast to 'id'.
3430 // casting to id<p-list> is ok if bridge type adopts all of
3431 // p-list protocols.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003432 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003433 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003434 if (warn) {
3435 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3436 << T << Target->getName() << castType;
3437 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3438 S.Diag(Target->getLocStart(), diag::note_declared_at);
3439 }
3440 return false;
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003441 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003442 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003443 }
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003444 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
Aaron Ballmanc0550742014-01-03 02:07:43 +00003445 << castExpr->getType() << Parm;
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003446 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3447 if (Target)
3448 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003449 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003450 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003451 return false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003452 }
3453 T = TDNDecl->getUnderlyingType();
3454 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003455 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003456}
3457
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003458template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003459static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3460 bool &HadTheAttribute, bool warn) {
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003461 QualType T = castType;
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003462 HadTheAttribute = false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003463 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3464 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003465 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003466 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003467 HadTheAttribute = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003468 NamedDecl *Target = nullptr;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003469 // Check for an existing type with this name.
3470 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3471 Sema::LookupOrdinaryName);
3472 if (S.LookupName(R, S.TUScope)) {
3473 Target = R.getFoundDecl();
3474 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3475 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3476 if (const ObjCObjectPointerType *InterfacePointerType =
3477 castExpr->getType()->getAsObjCInterfacePointerType()) {
3478 ObjCInterfaceDecl *ExprClass
3479 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003480 if ((CastClass == ExprClass) ||
3481 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003482 return true;
3483 if (warn) {
3484 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3485 << castExpr->getType()->getPointeeType() << T;
3486 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3487 }
3488 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003489 } else if (castExpr->getType()->isObjCIdType() ||
3490 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3491 castExpr->getType(), CastClass)))
3492 // ok to cast an 'id' expression to a CFtype.
3493 // ok to cast an 'id<plist>' expression to CFtype provided plist
3494 // adopts all of CFtype's ObjetiveC's class plist.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003495 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003496 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003497 if (warn) {
3498 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3499 << castExpr->getType() << castType;
3500 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3501 S.Diag(Target->getLocStart(), diag::note_declared_at);
3502 }
3503 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003504 }
3505 }
3506 }
3507 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3508 << castExpr->getType() << castType;
3509 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3510 if (Target)
3511 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003512 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003513 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003514 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003515 }
3516 T = TDNDecl->getUnderlyingType();
3517 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003518 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003519}
3520
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003521void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003522 if (!getLangOpts().ObjC1)
3523 return;
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003524 // warn in presence of __bridge casting to or from a toll free bridge cast.
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003525 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3526 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003527 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003528 bool HasObjCBridgeAttr;
3529 bool ObjCBridgeAttrWillNotWarn =
3530 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3531 false);
3532 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3533 return;
3534 bool HasObjCBridgeMutableAttr;
3535 bool ObjCBridgeMutableAttrWillNotWarn =
3536 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3537 HasObjCBridgeMutableAttr, false);
3538 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3539 return;
3540
3541 if (HasObjCBridgeAttr)
3542 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3543 true);
3544 else if (HasObjCBridgeMutableAttr)
3545 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3546 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003547 }
3548 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003549 bool HasObjCBridgeAttr;
3550 bool ObjCBridgeAttrWillNotWarn =
3551 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3552 false);
3553 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3554 return;
3555 bool HasObjCBridgeMutableAttr;
3556 bool ObjCBridgeMutableAttrWillNotWarn =
3557 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3558 HasObjCBridgeMutableAttr, false);
3559 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3560 return;
3561
3562 if (HasObjCBridgeAttr)
3563 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3564 true);
3565 else if (HasObjCBridgeMutableAttr)
3566 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3567 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003568 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003569}
3570
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003571void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3572 QualType SrcType = castExpr->getType();
3573 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3574 if (PRE->isExplicitProperty()) {
3575 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3576 SrcType = PDecl->getType();
3577 }
3578 else if (PRE->isImplicitProperty()) {
3579 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3580 SrcType = Getter->getReturnType();
3581
3582 }
3583 }
3584
3585 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3586 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3587 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3588 return;
3589 CheckObjCBridgeRelatedConversions(castExpr->getLocStart(),
3590 castType, SrcType, castExpr);
3591 return;
3592}
3593
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00003594bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3595 CastKind &Kind) {
3596 if (!getLangOpts().ObjC1)
3597 return false;
3598 ARCConversionTypeClass exprACTC =
3599 classifyTypeForARCConversion(castExpr->getType());
3600 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3601 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3602 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3603 CheckTollFreeBridgeCast(castType, castExpr);
3604 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3605 : CK_CPointerToObjCPointerCast;
3606 return true;
3607 }
3608 return false;
3609}
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003610
3611bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3612 QualType DestType, QualType SrcType,
3613 ObjCInterfaceDecl *&RelatedClass,
3614 ObjCMethodDecl *&ClassMethod,
3615 ObjCMethodDecl *&InstanceMethod,
3616 TypedefNameDecl *&TDNDecl,
3617 bool CfToNs) {
3618 QualType T = CfToNs ? SrcType : DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003619 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3620 if (!ObjCBAttr)
3621 return false;
3622
3623 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3624 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3625 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3626 if (!RCId)
3627 return false;
Craig Topperc3ec1492014-05-26 06:22:03 +00003628 NamedDecl *Target = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003629 // Check for an existing type with this name.
3630 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3631 Sema::LookupOrdinaryName);
3632 if (!LookupName(R, TUScope)) {
3633 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003634 << SrcType << DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003635 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3636 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003637 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003638 Target = R.getFoundDecl();
3639 if (Target && isa<ObjCInterfaceDecl>(Target))
3640 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3641 else {
3642 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3643 << SrcType << DestType;
3644 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3645 if (Target)
3646 Diag(Target->getLocStart(), diag::note_declared_at);
3647 return false;
3648 }
3649
3650 // Check for an existing class method with the given selector name.
3651 if (CfToNs && CMId) {
3652 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3653 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3654 if (!ClassMethod) {
3655 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003656 << SrcType << DestType << Sel << false;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003657 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3658 return false;
3659 }
3660 }
3661
3662 // Check for an existing instance method with the given selector name.
3663 if (!CfToNs && IMId) {
3664 Selector Sel = Context.Selectors.getNullarySelector(IMId);
3665 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3666 if (!InstanceMethod) {
3667 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003668 << SrcType << DestType << Sel << true;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003669 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3670 return false;
3671 }
3672 }
3673 return true;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003674}
3675
3676bool
3677Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003678 QualType DestType, QualType SrcType,
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003679 Expr *&SrcExpr) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003680 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3681 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3682 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3683 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3684 if (!CfToNs && !NsToCf)
3685 return false;
3686
3687 ObjCInterfaceDecl *RelatedClass;
Craig Topperc3ec1492014-05-26 06:22:03 +00003688 ObjCMethodDecl *ClassMethod = nullptr;
3689 ObjCMethodDecl *InstanceMethod = nullptr;
3690 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003691 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
3692 ClassMethod, InstanceMethod, TDNDecl, CfToNs))
3693 return false;
3694
3695 if (CfToNs) {
3696 // Implicit conversion from CF to ObjC object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003697 if (ClassMethod) {
3698 std::string ExpressionString = "[";
3699 ExpressionString += RelatedClass->getNameAsString();
3700 ExpressionString += " ";
3701 ExpressionString += ClassMethod->getSelector().getAsString();
3702 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3703 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003704 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003705 << SrcType << DestType << ClassMethod->getSelector() << false
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003706 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3707 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003708 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3709 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3710
3711 QualType receiverType =
3712 Context.getObjCInterfaceType(RelatedClass);
3713 // Argument.
3714 Expr *args[] = { SrcExpr };
3715 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
3716 ClassMethod->getLocation(),
3717 ClassMethod->getSelector(), ClassMethod,
3718 MultiExprArg(args, 1));
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003719 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003720 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003721 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003722 }
3723 else {
3724 // Implicit conversion from ObjC type to CF object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003725 if (InstanceMethod) {
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003726 std::string ExpressionString;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003727 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003728 if (InstanceMethod->isPropertyAccessor())
3729 if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
3730 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
3731 ExpressionString = ".";
3732 ExpressionString += PDecl->getNameAsString();
3733 Diag(Loc, diag::err_objc_bridged_related_known_method)
3734 << SrcType << DestType << InstanceMethod->getSelector() << true
3735 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3736 }
3737 if (ExpressionString.empty()) {
3738 // Provide a fixit: [ObjectExpr InstanceMethod]
3739 ExpressionString = " ";
3740 ExpressionString += InstanceMethod->getSelector().getAsString();
3741 ExpressionString += "]";
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003742
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003743 Diag(Loc, diag::err_objc_bridged_related_known_method)
3744 << SrcType << DestType << InstanceMethod->getSelector() << true
3745 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3746 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3747 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003748 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3749 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3750
3751 ExprResult msg =
3752 BuildInstanceMessageImplicit(SrcExpr, SrcType,
3753 InstanceMethod->getLocation(),
3754 InstanceMethod->getSelector(),
3755 InstanceMethod, None);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003756 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003757 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003758 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003759 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003760 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003761}
3762
John McCall4124c492011-10-17 18:40:02 +00003763Sema::ARCConversionResult
3764Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003765 Expr *&castExpr, CheckedConversionKind CCK,
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00003766 bool DiagnoseCFAudited,
3767 BinaryOperatorKind Opc) {
John McCall4124c492011-10-17 18:40:02 +00003768 QualType castExprType = castExpr->getType();
3769
3770 // For the purposes of the classification, we assume reference types
3771 // will bind to temporaries.
3772 QualType effCastType = castType;
3773 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3774 effCastType = ref->getPointeeType();
3775
3776 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3777 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003778 if (exprACTC == castACTC) {
3779 // check for viablity and report error if casting an rvalue to a
3780 // life-time qualifier.
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003781 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003782 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003783 (castType != castExprType)) {
3784 const Type *DT = castType.getTypePtr();
3785 QualType QDT = castType;
3786 // We desugar some types but not others. We ignore those
3787 // that cannot happen in a cast; i.e. auto, and those which
3788 // should not be de-sugared; i.e typedef.
3789 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3790 QDT = PT->desugar();
3791 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3792 QDT = TP->desugar();
3793 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3794 QDT = AT->desugar();
3795 if (QDT != castType &&
3796 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3797 SourceLocation loc =
3798 (castRange.isValid() ? castRange.getBegin()
3799 : castExpr->getExprLoc());
3800 Diag(loc, diag::err_arc_nolifetime_behavior);
3801 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003802 }
3803 return ACR_okay;
3804 }
3805
John McCall4124c492011-10-17 18:40:02 +00003806 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
3807
3808 // Allow all of these types to be cast to integer types (but not
3809 // vice-versa).
3810 if (castACTC == ACTC_none && castType->isIntegralType(Context))
3811 return ACR_okay;
3812
3813 // Allow casts between pointers to lifetime types (e.g., __strong id*)
3814 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
3815 // must be explicit.
3816 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
3817 return ACR_okay;
3818 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
3819 CCK != CCK_ImplicitConversion)
3820 return ACR_okay;
3821
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003822 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00003823 // For invalid casts, fall through.
3824 case ACC_invalid:
3825 break;
3826
3827 // Do nothing for both bottom and +0.
3828 case ACC_bottom:
3829 case ACC_plusZero:
3830 return ACR_okay;
3831
3832 // If the result is +1, consume it here.
3833 case ACC_plusOne:
3834 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3835 CK_ARCConsumeObject, castExpr,
Craig Topperc3ec1492014-05-26 06:22:03 +00003836 nullptr, VK_RValue);
John McCall4124c492011-10-17 18:40:02 +00003837 ExprNeedsCleanups = true;
3838 return ACR_okay;
3839 }
3840
3841 // If this is a non-implicit cast from id or block type to a
3842 // CoreFoundation type, delay complaining in case the cast is used
3843 // in an acceptable context.
3844 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3845 CCK != CCK_ImplicitConversion)
3846 return ACR_unbridged;
3847
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003848 // Do not issue bridge cast" diagnostic when implicit casting a cstring
3849 // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
3850 // suitable fix-it.
Fariborz Jahanian283bf892013-12-18 21:04:43 +00003851 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
3852 ConversionToObjCStringLiteralCheck(castType, castExpr))
3853 return ACR_okay;
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003854
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003855 // Do not issue "bridge cast" diagnostic when implicit casting
3856 // a retainable object to a CF type parameter belonging to an audited
3857 // CF API function. Let caller issue a normal type mismatched diagnostic
3858 // instead.
3859 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
3860 castACTC != ACTC_coreFoundation)
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00003861 if (!(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
3862 (Opc == BO_NE || Opc == BO_EQ)))
3863 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3864 castExpr, castExpr, exprACTC, CCK);
John McCall4124c492011-10-17 18:40:02 +00003865 return ACR_okay;
3866}
3867
3868/// Given that we saw an expression with the ARCUnbridgedCastTy
3869/// placeholder type, complain bitterly.
3870void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3871 // We expect the spurious ImplicitCastExpr to already have been stripped.
3872 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3873 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3874
3875 SourceRange castRange;
3876 QualType castType;
3877 CheckedConversionKind CCK;
3878
3879 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3880 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3881 castType = cast->getTypeAsWritten();
3882 CCK = CCK_CStyleCast;
3883 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3884 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3885 castType = cast->getTypeAsWritten();
3886 CCK = CCK_OtherCast;
3887 } else {
3888 castType = cast->getType();
3889 CCK = CCK_ImplicitConversion;
3890 }
3891
3892 ARCConversionTypeClass castACTC =
3893 classifyTypeForARCConversion(castType.getNonReferenceType());
3894
3895 Expr *castExpr = realCast->getSubExpr();
3896 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3897
3898 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003899 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00003900}
3901
3902/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3903/// type, remove the placeholder cast.
3904Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3905 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3906
3907 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3908 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3909 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3910 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3911 assert(uo->getOpcode() == UO_Extension);
3912 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3913 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3914 sub->getValueKind(), sub->getObjectKind(),
3915 uo->getOperatorLoc());
3916 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3917 assert(!gse->isResultDependent());
3918
3919 unsigned n = gse->getNumAssocs();
3920 SmallVector<Expr*, 4> subExprs(n);
3921 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3922 for (unsigned i = 0; i != n; ++i) {
3923 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3924 Expr *sub = gse->getAssocExpr(i);
3925 if (i == gse->getResultIndex())
3926 sub = stripARCUnbridgedCast(sub);
3927 subExprs[i] = sub;
3928 }
3929
3930 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3931 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003932 subTypes, subExprs,
3933 gse->getDefaultLoc(),
John McCall4124c492011-10-17 18:40:02 +00003934 gse->getRParenLoc(),
3935 gse->containsUnexpandedParameterPack(),
3936 gse->getResultIndex());
3937 } else {
3938 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3939 return cast<ImplicitCastExpr>(e)->getSubExpr();
3940 }
3941}
3942
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003943bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3944 QualType exprType) {
3945 QualType canCastType =
3946 Context.getCanonicalType(castType).getUnqualifiedType();
3947 QualType canExprType =
3948 Context.getCanonicalType(exprType).getUnqualifiedType();
3949 if (isa<ObjCObjectPointerType>(canCastType) &&
3950 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3951 canExprType->isObjCObjectPointerType()) {
3952 if (const ObjCObjectPointerType *ObjT =
3953 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00003954 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
3955 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003956 }
3957 return true;
3958}
3959
John McCall4db5c3c2011-07-07 06:58:02 +00003960/// Look for an ObjCReclaimReturnedObject cast and destroy it.
3961static Expr *maybeUndoReclaimObject(Expr *e) {
3962 // For now, we just undo operands that are *immediately* reclaim
3963 // expressions, which prevents the vast majority of potential
3964 // problems here. To catch them all, we'd need to rebuild arbitrary
3965 // value-propagating subexpressions --- we can't reliably rebuild
3966 // in-place because of expression sharing.
3967 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall2d637d22011-09-10 06:18:15 +00003968 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall4db5c3c2011-07-07 06:58:02 +00003969 return ice->getSubExpr();
3970
3971 return e;
3972}
3973
John McCall31168b02011-06-15 23:02:42 +00003974ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3975 ObjCBridgeCastKind Kind,
3976 SourceLocation BridgeKeywordLoc,
3977 TypeSourceInfo *TSInfo,
3978 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00003979 ExprResult SubResult = UsualUnaryConversions(SubExpr);
3980 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003981 SubExpr = SubResult.get();
John McCalleb075542011-08-26 00:48:42 +00003982
John McCall31168b02011-06-15 23:02:42 +00003983 QualType T = TSInfo->getType();
3984 QualType FromType = SubExpr->getType();
3985
John McCall9320b872011-09-09 05:25:32 +00003986 CastKind CK;
3987
John McCall31168b02011-06-15 23:02:42 +00003988 bool MustConsume = false;
3989 if (T->isDependentType() || SubExpr->isTypeDependent()) {
3990 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00003991 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00003992 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3993 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00003994 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3995 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00003996 switch (Kind) {
3997 case OBC_Bridge:
3998 break;
3999
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004000 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004001 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00004002 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4003 << 2
4004 << FromType
4005 << (T->isBlockPointerType()? 1 : 0)
4006 << T
4007 << SubExpr->getSourceRange()
4008 << Kind;
4009 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4010 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4011 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004012 << FromType << br
John McCall31168b02011-06-15 23:02:42 +00004013 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004014 br ? "CFBridgingRelease "
4015 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00004016
4017 Kind = OBC_Bridge;
4018 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004019 }
John McCall31168b02011-06-15 23:02:42 +00004020
4021 case OBC_BridgeTransfer:
4022 // We must consume the Objective-C object produced by the cast.
4023 MustConsume = true;
4024 break;
4025 }
4026 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4027 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00004028 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00004029 switch (Kind) {
Fariborz Jahanian214567c2014-10-28 17:26:21 +00004030 case OBC_Bridge:
4031 // Reclaiming a value that's going to be __bridge-casted to CF
4032 // is very dangerous, so we don't do it.
4033 SubExpr = maybeUndoReclaimObject(SubExpr);
4034 break;
John McCall31168b02011-06-15 23:02:42 +00004035
4036 case OBC_BridgeRetained:
4037 // Produce the object before casting it.
4038 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00004039 CK_ARCProduceObject,
Craig Topperc3ec1492014-05-26 06:22:03 +00004040 SubExpr, nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004041 break;
4042
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004043 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004044 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00004045 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4046 << (FromType->isBlockPointerType()? 1 : 0)
4047 << FromType
4048 << 2
4049 << T
4050 << SubExpr->getSourceRange()
4051 << Kind;
4052
4053 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4054 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4055 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004056 << T << br
4057 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4058 br ? "CFBridgingRetain " : "__bridge_retained");
John McCall31168b02011-06-15 23:02:42 +00004059
4060 Kind = OBC_Bridge;
4061 break;
4062 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004063 }
John McCall31168b02011-06-15 23:02:42 +00004064 } else {
4065 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4066 << FromType << T << Kind
4067 << SubExpr->getSourceRange()
4068 << TSInfo->getTypeLoc().getSourceRange();
4069 return ExprError();
4070 }
4071
John McCall9320b872011-09-09 05:25:32 +00004072 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00004073 BridgeKeywordLoc,
4074 TSInfo, SubExpr);
4075
4076 if (MustConsume) {
4077 ExprNeedsCleanups = true;
John McCall2d637d22011-09-10 06:18:15 +00004078 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
Craig Topperc3ec1492014-05-26 06:22:03 +00004079 nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004080 }
4081
4082 return Result;
4083}
4084
4085ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4086 SourceLocation LParenLoc,
4087 ObjCBridgeCastKind Kind,
4088 SourceLocation BridgeKeywordLoc,
4089 ParsedType Type,
4090 SourceLocation RParenLoc,
4091 Expr *SubExpr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004092 TypeSourceInfo *TSInfo = nullptr;
John McCall31168b02011-06-15 23:02:42 +00004093 QualType T = GetTypeFromParser(Type, &TSInfo);
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00004094 if (Kind == OBC_Bridge)
4095 CheckTollFreeBridgeCast(T, SubExpr);
John McCall31168b02011-06-15 23:02:42 +00004096 if (!TSInfo)
4097 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4098 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
4099 SubExpr);
4100}