blob: d316c13f941598c9aae77526ab17a823fb814a60 [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) {
Fariborz Jahanian50c925f2010-10-19 17:19:29 +000096 IdentifierInfo *NSIdent=0;
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,
136 0, SourceLocation());
137 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 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000185 return 0;
186 }
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,
211 0, 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);
215 return 0;
216 }
217 } else if (!S.NSNumberDecl->hasDefinition()) {
218 S.Diag(Loc, diag::err_undeclared_nsnumber);
219 return 0;
220 }
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.
Alp Toker314cc812014-01-25 16:55:45 +0000231 TypeSourceInfo *ReturnTInfo = 0;
232 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"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000243 NumberType, /*TInfo=*/0, SC_None,
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000244 0);
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))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000249 return 0;
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.
Patrick Beard2565c592012-05-01 21:47:19 +0000294 ParmVarDecl *ParamDecl = Method->param_begin()[0];
295 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
296 ParamDecl);
297 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
298 SourceLocation(),
299 Owned(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 =
447 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, NULL, SR);
448 return Owned(BoxedExpr);
449 }
450 ObjCMethodDecl *BoxingMethod = NULL;
451 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,
Patrick Beard0caa3942012-04-19 00:25:12 +0000476 0, SourceLocation());
477 } 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.
Alp Toker314cc812014-01-25 16:55:45 +0000498 TypeSourceInfo *ReturnTInfo = 0;
499 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),
Patrick Beard0caa3942012-04-19 00:25:12 +0000513 /*TInfo=*/0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000514 SC_None, 0);
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 }
558
559 // 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.
Patrick Beard2565c592012-05-01 21:47:19 +0000584 ParmVarDecl *ParamDecl = BoxingMethod->param_begin()[0];
585 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
586 ParamDecl);
587 ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
588 SourceLocation(),
589 Owned(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.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000627 return Owned(ObjCSubscriptRefExpr::Create(Context,
628 BaseExpr,
629 IndexExpr,
630 Context.PseudoObjectTy,
631 getterMethod,
632 setterMethod, RB));
633
634}
635
636ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
637 // Look up the NSArray class, if we haven't done so already.
638 if (!NSArrayDecl) {
639 NamedDecl *IF = LookupSingleName(TUScope,
640 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
641 SR.getBegin(),
642 LookupOrdinaryName);
643 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000644 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000645 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
646 Context.getTranslationUnitDecl(),
647 SourceLocation(),
648 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
649 0, SourceLocation());
650
651 if (!NSArrayDecl) {
652 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
653 return ExprError();
654 }
655 }
656
657 // Find the arrayWithObjects:count: method, if we haven't done so already.
658 QualType IdT = Context.getObjCIdType();
659 if (!ArrayWithObjectsMethod) {
660 Selector
661 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
Jordy Rose08e500c2012-05-12 17:32:44 +0000662 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
663 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Alp Toker314cc812014-01-25 16:55:45 +0000664 TypeSourceInfo *ReturnTInfo = 0;
665 Method = ObjCMethodDecl::Create(
666 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
667 Context.getTranslationUnitDecl(), false /*Instance*/,
668 false /*isVariadic*/,
669 /*isPropertyAccessor=*/false,
670 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
671 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000672 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000673 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000674 SourceLocation(),
675 SourceLocation(),
676 &Context.Idents.get("objects"),
677 Context.getPointerType(IdT),
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000678 /*TInfo=*/0, SC_None, 0);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000679 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000680 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000681 SourceLocation(),
682 SourceLocation(),
683 &Context.Idents.get("cnt"),
684 Context.UnsignedLongTy,
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000685 /*TInfo=*/0, SC_None, 0);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000686 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000687 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000688 }
689
Jordy Rose08e500c2012-05-12 17:32:44 +0000690 if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000691 return ExprError();
Jordy Rose08e500c2012-05-12 17:32:44 +0000692
Jordy Rose4af44872012-05-12 17:32:56 +0000693 // Dig out the type that all elements should be converted to.
694 QualType T = Method->param_begin()[0]->getType();
695 const PointerType *PtrT = T->getAs<PointerType>();
696 if (!PtrT ||
697 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
698 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
699 << Sel;
700 Diag(Method->param_begin()[0]->getLocation(),
701 diag::note_objc_literal_method_param)
702 << 0 << T
703 << Context.getPointerType(IdT.withConst());
704 return ExprError();
705 }
706
707 // Check that the 'count' parameter is integral.
708 if (!Method->param_begin()[1]->getType()->isIntegerType()) {
709 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
710 << Sel;
711 Diag(Method->param_begin()[1]->getLocation(),
712 diag::note_objc_literal_method_param)
713 << 1
714 << Method->param_begin()[1]->getType()
715 << "integral";
716 return ExprError();
717 }
718
719 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rose08e500c2012-05-12 17:32:44 +0000720 ArrayWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000721 }
722
Jordy Rose4af44872012-05-12 17:32:56 +0000723 QualType ObjectsType = ArrayWithObjectsMethod->param_begin()[0]->getType();
724 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000725
726 // Check that each of the elements provided is valid in a collection literal,
727 // performing conversions as necessary.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000728 Expr **ElementsBuffer = Elements.data();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000729 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
730 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
731 ElementsBuffer[I],
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000732 RequiredType, true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000733 if (Converted.isInvalid())
734 return ExprError();
735
736 ElementsBuffer[I] = Converted.get();
737 }
738
739 QualType Ty
740 = Context.getObjCObjectPointerType(
741 Context.getObjCInterfaceType(NSArrayDecl));
742
743 return MaybeBindToTemporary(
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000744 ObjCArrayLiteral::Create(Context, Elements, Ty,
745 ArrayWithObjectsMethod, SR));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000746}
747
748ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
749 ObjCDictionaryElement *Elements,
750 unsigned NumElements) {
751 // Look up the NSDictionary class, if we haven't done so already.
752 if (!NSDictionaryDecl) {
753 NamedDecl *IF = LookupSingleName(TUScope,
754 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
755 SR.getBegin(), LookupOrdinaryName);
756 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000757 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000758 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
759 Context.getTranslationUnitDecl(),
760 SourceLocation(),
761 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
762 0, SourceLocation());
763
764 if (!NSDictionaryDecl) {
765 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
766 return ExprError();
767 }
768 }
769
770 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
771 // so already.
772 QualType IdT = Context.getObjCIdType();
773 if (!DictionaryWithObjectsMethod) {
774 Selector Sel = NSAPIObj->getNSDictionarySelector(
Jordy Roseaca01f92012-05-12 17:32:52 +0000775 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
Jordy Rose08e500c2012-05-12 17:32:44 +0000776 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
777 if (!Method && getLangOpts().DebuggerObjCLiteral) {
778 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000779 SourceLocation(), SourceLocation(), Sel,
780 IdT,
781 0 /*TypeSourceInfo */,
782 Context.getTranslationUnitDecl(),
783 false /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000784 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000785 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
786 ObjCMethodDecl::Required,
787 false);
788 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000789 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000790 SourceLocation(),
791 SourceLocation(),
792 &Context.Idents.get("objects"),
793 Context.getPointerType(IdT),
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000794 /*TInfo=*/0, SC_None, 0);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000795 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000796 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000797 SourceLocation(),
798 SourceLocation(),
799 &Context.Idents.get("keys"),
800 Context.getPointerType(IdT),
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000801 /*TInfo=*/0, SC_None, 0);
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,
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000808 /*TInfo=*/0, SC_None, 0);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000809 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000810 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000811 }
812
Jordy Rose08e500c2012-05-12 17:32:44 +0000813 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
814 Method))
815 return ExprError();
816
Jordy Rose4af44872012-05-12 17:32:56 +0000817 // Dig out the type that all values should be converted to.
818 QualType ValueT = Method->param_begin()[0]->getType();
819 const PointerType *PtrValue = ValueT->getAs<PointerType>();
820 if (!PtrValue ||
821 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000822 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000823 << Sel;
824 Diag(Method->param_begin()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000825 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000826 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000827 << Context.getPointerType(IdT.withConst());
828 return ExprError();
829 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000830
Jordy Rose4af44872012-05-12 17:32:56 +0000831 // Dig out the type that all keys should be converted to.
832 QualType KeyT = Method->param_begin()[1]->getType();
833 const PointerType *PtrKey = KeyT->getAs<PointerType>();
834 if (!PtrKey ||
835 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
836 IdT)) {
837 bool err = true;
838 if (PtrKey) {
839 if (QIDNSCopying.isNull()) {
840 // key argument of selector is id<NSCopying>?
841 if (ObjCProtocolDecl *NSCopyingPDecl =
842 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
843 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
844 QIDNSCopying =
845 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
846 (ObjCProtocolDecl**) PQ,1);
847 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
848 }
849 }
850 if (!QIDNSCopying.isNull())
851 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
852 QIDNSCopying);
853 }
854
855 if (err) {
856 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
857 << Sel;
858 Diag(Method->param_begin()[1]->getLocation(),
859 diag::note_objc_literal_method_param)
860 << 1 << KeyT
861 << Context.getPointerType(IdT.withConst());
862 return ExprError();
863 }
864 }
865
866 // Check that the 'count' parameter is integral.
867 QualType CountType = Method->param_begin()[2]->getType();
868 if (!CountType->isIntegerType()) {
869 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
870 << Sel;
871 Diag(Method->param_begin()[2]->getLocation(),
872 diag::note_objc_literal_method_param)
873 << 2 << CountType
874 << "integral";
875 return ExprError();
876 }
877
878 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
879 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000880 }
881
Jordy Rose4af44872012-05-12 17:32:56 +0000882 QualType ValuesT = DictionaryWithObjectsMethod->param_begin()[0]->getType();
883 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
884 QualType KeysT = DictionaryWithObjectsMethod->param_begin()[1]->getType();
885 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
886
Ted Kremeneke65b0862012-03-06 20:05:56 +0000887 // Check that each of the keys and values provided is valid in a collection
888 // literal, performing conversions as necessary.
889 bool HasPackExpansions = false;
890 for (unsigned I = 0, N = NumElements; I != N; ++I) {
891 // Check the key.
892 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
893 KeyT);
894 if (Key.isInvalid())
895 return ExprError();
896
897 // Check the value.
898 ExprResult Value
899 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
900 if (Value.isInvalid())
901 return ExprError();
902
903 Elements[I].Key = Key.get();
904 Elements[I].Value = Value.get();
905
906 if (Elements[I].EllipsisLoc.isInvalid())
907 continue;
908
909 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
910 !Elements[I].Value->containsUnexpandedParameterPack()) {
911 Diag(Elements[I].EllipsisLoc,
912 diag::err_pack_expansion_without_parameter_packs)
913 << SourceRange(Elements[I].Key->getLocStart(),
914 Elements[I].Value->getLocEnd());
915 return ExprError();
916 }
917
918 HasPackExpansions = true;
919 }
920
921
922 QualType Ty
923 = Context.getObjCObjectPointerType(
Robert Wilhelm88e02492013-08-19 07:57:02 +0000924 Context.getObjCInterfaceType(NSDictionaryDecl));
925 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
926 Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty,
927 DictionaryWithObjectsMethod, SR));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000928}
929
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000930ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregorabd9e962010-04-20 15:39:42 +0000931 TypeSourceInfo *EncodedTypeInfo,
Anders Carlsson315d2292009-06-07 18:45:35 +0000932 SourceLocation RParenLoc) {
Douglas Gregorabd9e962010-04-20 15:39:42 +0000933 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlsson315d2292009-06-07 18:45:35 +0000934 QualType StrTy;
Mike Stump11289f42009-09-09 15:08:12 +0000935 if (EncodedType->isDependentType())
Anders Carlsson315d2292009-06-07 18:45:35 +0000936 StrTy = Context.DependentTy;
937 else {
Fariborz Jahaniand9bc6c32011-06-16 22:34:44 +0000938 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
939 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000940 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000941 diag::err_incomplete_type_objc_at_encode,
942 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000943 return ExprError();
944
Anders Carlsson315d2292009-06-07 18:45:35 +0000945 std::string Str;
946 Context.getObjCEncodingForType(EncodedType, Str);
947
948 // The type of @encode is the same as the type of the corresponding string,
949 // which is an array type.
950 StrTy = Context.CharTy;
951 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +0000952 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlsson315d2292009-06-07 18:45:35 +0000953 StrTy.addConst();
954 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
955 ArrayType::Normal, 0);
956 }
Mike Stump11289f42009-09-09 15:08:12 +0000957
Douglas Gregorabd9e962010-04-20 15:39:42 +0000958 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlsson315d2292009-06-07 18:45:35 +0000959}
960
John McCallfaf5fb42010-08-26 23:41:50 +0000961ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
962 SourceLocation EncodeLoc,
963 SourceLocation LParenLoc,
964 ParsedType ty,
965 SourceLocation RParenLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000966 // FIXME: Preserve type source info ?
Douglas Gregorabd9e962010-04-20 15:39:42 +0000967 TypeSourceInfo *TInfo;
968 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
969 if (!TInfo)
970 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
971 PP.getLocForEndOfToken(LParenLoc));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000972
Douglas Gregorabd9e962010-04-20 15:39:42 +0000973 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000974}
975
Fariborz Jahanian44be1542014-03-12 18:34:01 +0000976static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
977 SourceLocation AtLoc,
978 ObjCMethodDecl *Method,
979 ObjCMethodList &MethList) {
980 ObjCMethodList *M = &MethList;
981 bool Warned = false;
982 for (M = M->getNext(); M; M=M->getNext()) {
983 ObjCMethodDecl *MatchingMethodDecl = M->Method;
984 if (MatchingMethodDecl == Method ||
985 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
986 MatchingMethodDecl->getSelector() != Method->getSelector())
987 continue;
988 if (!S.MatchTwoMethodDeclarations(Method,
989 MatchingMethodDecl, Sema::MMS_loose)) {
990 if (!Warned) {
991 Warned = true;
992 S.Diag(AtLoc, diag::warning_multiple_selectors)
993 << Method->getSelector();
994 S.Diag(Method->getLocation(), diag::note_method_declared_at)
995 << Method->getDeclName();
996 }
997 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
998 << MatchingMethodDecl->getDeclName();
999 }
1000 }
1001 return Warned;
1002}
1003
1004static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
1005 ObjCMethodDecl *Method) {
Fariborz Jahanian1c433292014-03-27 21:59:01 +00001006 if (S.Diags.getDiagnosticLevel(diag::warning_multiple_selectors,
1007 SourceLocation())
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001008 == DiagnosticsEngine::Ignored)
1009 return;
1010 bool Warned = false;
1011 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1012 e = S.MethodPool.end(); b != e; b++) {
1013 // first, instance methods
1014 ObjCMethodList &InstMethList = b->second.first;
1015 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc,
1016 Method, InstMethList))
1017 Warned = true;
1018
1019 // second, class methods
1020 ObjCMethodList &ClsMethList = b->second.second;
1021 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc,
1022 Method, ClsMethList) ||
1023 Warned)
1024 return;
1025 }
1026}
1027
John McCallfaf5fb42010-08-26 23:41:50 +00001028ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1029 SourceLocation AtLoc,
1030 SourceLocation SelLoc,
1031 SourceLocation LParenLoc,
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001032 SourceLocation RParenLoc) {
1033 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1034 SourceRange(LParenLoc, RParenLoc), false, false);
1035 if (!Method)
1036 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian0571d9b2009-06-16 16:25:00 +00001037 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00001038 if (!Method) {
1039 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1040 Selector MatchedSel = OM->getSelector();
1041 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1042 RParenLoc.getLocWithOffset(-1));
1043 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1044 << Sel << MatchedSel
1045 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1046
1047 } else
1048 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001049 } else
1050 DiagnoseMismatchedSelectors(*this, AtLoc, Method);
Fariborz Jahanian9a881012011-07-13 19:05:43 +00001051
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001052 if (!Method ||
1053 Method->getImplementationControl() != ObjCMethodDecl::Optional) {
1054 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
1055 = ReferencedSelectors.find(Sel);
1056 if (Pos == ReferencedSelectors.end())
1057 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian9a881012011-07-13 19:05:43 +00001058 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001059
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001060 // In ARC, forbid the user from using @selector for
John McCall31168b02011-06-15 23:02:42 +00001061 // retain/release/autorelease/dealloc/retainCount.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001062 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001063 switch (Sel.getMethodFamily()) {
1064 case OMF_retain:
1065 case OMF_release:
1066 case OMF_autorelease:
1067 case OMF_retainCount:
1068 case OMF_dealloc:
1069 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1070 Sel << SourceRange(LParenLoc, RParenLoc);
1071 break;
1072
1073 case OMF_None:
1074 case OMF_alloc:
1075 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00001076 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00001077 case OMF_init:
1078 case OMF_mutableCopy:
1079 case OMF_new:
1080 case OMF_self:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001081 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001082 break;
1083 }
1084 }
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001085 QualType Ty = Context.getObjCSelType();
Daniel Dunbar45858d22010-02-03 20:11:42 +00001086 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001087}
1088
John McCallfaf5fb42010-08-26 23:41:50 +00001089ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1090 SourceLocation AtLoc,
1091 SourceLocation ProtoLoc,
1092 SourceLocation LParenLoc,
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001093 SourceLocation ProtoIdLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00001094 SourceLocation RParenLoc) {
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001095 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001096 if (!PDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001097 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001098 return true;
1099 }
Mike Stump11289f42009-09-09 15:08:12 +00001100
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001101 QualType Ty = Context.getObjCProtoType();
1102 if (Ty.isNull())
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001103 return true;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001104 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001105 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001106}
1107
John McCall5f2d5562011-02-03 09:00:02 +00001108/// Try to capture an implicit reference to 'self'.
Eli Friedman24af8502012-02-03 22:47:37 +00001109ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1110 DeclContext *DC = getFunctionLevelDeclContext();
John McCall5f2d5562011-02-03 09:00:02 +00001111
1112 // If we're not in an ObjC method, error out. Note that, unlike the
1113 // C++ case, we don't require an instance method --- class methods
1114 // still have a 'self', and we really do still need to capture it!
1115 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1116 if (!method)
1117 return 0;
1118
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001119 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall5f2d5562011-02-03 09:00:02 +00001120
1121 return method;
1122}
1123
Douglas Gregor64910ca2011-09-09 20:05:21 +00001124static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1125 if (T == Context.getObjCInstanceType())
1126 return Context.getObjCIdType();
1127
1128 return T;
1129}
1130
Douglas Gregor33823722011-06-11 01:09:30 +00001131QualType Sema::getMessageSendResultType(QualType ReceiverType,
1132 ObjCMethodDecl *Method,
1133 bool isClassMessage, bool isSuperMessage) {
1134 assert(Method && "Must have a method");
1135 if (!Method->hasRelatedResultType())
1136 return Method->getSendResultType();
1137
1138 // If a method has a related return type:
1139 // - if the method found is an instance method, but the message send
1140 // was a class message send, T is the declared return type of the method
1141 // found
1142 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor64910ca2011-09-09 20:05:21 +00001143 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001144
1145 // - if the receiver is super, T is a pointer to the class of the
1146 // enclosing method definition
1147 if (isSuperMessage) {
1148 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1149 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1150 return Context.getObjCObjectPointerType(
1151 Context.getObjCInterfaceType(Class));
1152 }
1153
1154 // - if the receiver is the name of a class U, T is a pointer to U
1155 if (ReceiverType->getAs<ObjCInterfaceType>() ||
1156 ReceiverType->isObjCQualifiedInterfaceType())
1157 return Context.getObjCObjectPointerType(ReceiverType);
1158 // - if the receiver is of type Class or qualified Class type,
1159 // T is the declared return type of the method.
1160 if (ReceiverType->isObjCClassType() ||
1161 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor64910ca2011-09-09 20:05:21 +00001162 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001163
1164 // - if the receiver is id, qualified id, Class, or qualified Class, T
1165 // is the receiver type, otherwise
1166 // - T is the type of the receiver expression.
1167 return ReceiverType;
1168}
John McCall5f2d5562011-02-03 09:00:02 +00001169
John McCall5ec7e7d2013-03-19 07:04:25 +00001170/// Look for an ObjC method whose result type exactly matches the given type.
1171static const ObjCMethodDecl *
1172findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1173 QualType instancetype) {
Alp Toker314cc812014-01-25 16:55:45 +00001174 if (MD->getReturnType() == instancetype)
1175 return MD;
John McCall5ec7e7d2013-03-19 07:04:25 +00001176
1177 // For these purposes, a method in an @implementation overrides a
1178 // declaration in the @interface.
1179 if (const ObjCImplDecl *impl =
1180 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1181 const ObjCContainerDecl *iface;
1182 if (const ObjCCategoryImplDecl *catImpl =
1183 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1184 iface = catImpl->getCategoryDecl();
1185 } else {
1186 iface = impl->getClassInterface();
1187 }
1188
1189 const ObjCMethodDecl *ifaceMD =
1190 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1191 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1192 }
1193
1194 SmallVector<const ObjCMethodDecl *, 4> overrides;
1195 MD->getOverriddenMethods(overrides);
1196 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1197 if (const ObjCMethodDecl *result =
1198 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1199 return result;
1200 }
1201
1202 return 0;
1203}
1204
1205void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1206 // Only complain if we're in an ObjC method and the required return
1207 // type doesn't match the method's declared return type.
1208 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1209 if (!MD || !MD->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +00001210 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
John McCall5ec7e7d2013-03-19 07:04:25 +00001211 return;
1212
1213 // Look for a method overridden by this method which explicitly uses
1214 // 'instancetype'.
1215 if (const ObjCMethodDecl *overridden =
1216 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
1217 SourceLocation loc;
1218 SourceRange range;
Alp Toker314cc812014-01-25 16:55:45 +00001219 if (TypeSourceInfo *TSI = overridden->getReturnTypeSourceInfo()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00001220 range = TSI->getTypeLoc().getSourceRange();
1221 loc = range.getBegin();
1222 }
1223 if (loc.isInvalid())
1224 loc = overridden->getLocation();
1225 Diag(loc, diag::note_related_result_type_explicit)
1226 << /*current method*/ 1 << range;
1227 return;
1228 }
1229
1230 // Otherwise, if we have an interesting method family, note that.
1231 // This should always trigger if the above didn't.
1232 if (ObjCMethodFamily family = MD->getMethodFamily())
1233 Diag(MD->getLocation(), diag::note_related_result_type_family)
1234 << /*current method*/ 1
1235 << family;
1236}
1237
Douglas Gregor33823722011-06-11 01:09:30 +00001238void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1239 E = E->IgnoreParenImpCasts();
1240 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1241 if (!MsgSend)
1242 return;
1243
1244 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1245 if (!Method)
1246 return;
1247
1248 if (!Method->hasRelatedResultType())
1249 return;
Alp Toker314cc812014-01-25 16:55:45 +00001250
1251 if (Context.hasSameUnqualifiedType(
1252 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
Douglas Gregor33823722011-06-11 01:09:30 +00001253 return;
Alp Toker314cc812014-01-25 16:55:45 +00001254
1255 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
Douglas Gregorbab8a962011-09-08 01:46:34 +00001256 Context.getObjCInstanceType()))
1257 return;
1258
Douglas Gregor33823722011-06-11 01:09:30 +00001259 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1260 << Method->isInstanceMethod() << Method->getSelector()
1261 << MsgSend->getType();
1262}
1263
1264bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001265 MultiExprArg Args,
1266 Selector Sel,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001267 ArrayRef<SourceLocation> SelectorLocs,
1268 ObjCMethodDecl *Method,
Douglas Gregor33823722011-06-11 01:09:30 +00001269 bool isClassMessage, bool isSuperMessage,
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001270 SourceLocation lbrac, SourceLocation rbrac,
John McCall7decc9e2010-11-18 06:31:45 +00001271 QualType &ReturnType, ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001272 SourceLocation SelLoc;
1273 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1274 SelLoc = SelectorLocs.front();
1275 else
1276 SelLoc = lbrac;
1277
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001278 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001279 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001280 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001281 if (Args[i]->isTypeDependent())
1282 continue;
1283
John McCallcc5788c2013-03-04 07:34:02 +00001284 ExprResult result;
1285 if (getLangOpts().DebuggerSupport) {
1286 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001287 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001288 } else {
1289 result = DefaultArgumentPromotion(Args[i]);
1290 }
1291 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001292 return true;
John McCallcc5788c2013-03-04 07:34:02 +00001293 Args[i] = result.take();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001294 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001295
John McCall31168b02011-06-15 23:02:42 +00001296 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001297 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001298 DiagID = diag::err_arc_method_not_found;
1299 else
1300 DiagID = isClassMessage ? diag::warn_class_method_not_found
1301 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001302 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001303 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahanian06499232013-06-18 17:10:58 +00001304 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001305 if (getLangOpts().ObjCAutoRefCount)
1306 DiagID = diag::error_method_not_found_with_typo;
1307 else
1308 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1309 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001310 Selector MatchedSel = OMD->getSelector();
1311 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001312 Diag(SelLoc, DiagID)
1313 << Sel<< isClassMessage << MatchedSel
Fariborz Jahanian75481672013-06-17 17:10:54 +00001314 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1315 }
1316 else
1317 Diag(SelLoc, DiagID)
1318 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001319 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001320 // Find the class to which we are sending this message.
1321 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian478536b2013-05-15 15:27:35 +00001322 if (ObjCInterfaceDecl *Class =
1323 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl())
1324 Diag(Class->getLocation(), diag::note_receiver_class_declared);
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001325 }
1326 }
John McCall3f4138c2011-07-13 17:56:40 +00001327
1328 // In debuggers, we want to use __unknown_anytype for these
1329 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001330 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001331 ReturnType = Context.UnknownAnyTy;
1332 } else {
1333 ReturnType = Context.getObjCIdType();
1334 }
John McCall7decc9e2010-11-18 06:31:45 +00001335 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001336 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001337 }
Mike Stump11289f42009-09-09 15:08:12 +00001338
Douglas Gregor33823722011-06-11 01:09:30 +00001339 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1340 isSuperMessage);
Alp Toker314cc812014-01-25 16:55:45 +00001341 VK = Expr::getValueKindForType(Method->getReturnType());
Mike Stump11289f42009-09-09 15:08:12 +00001342
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001343 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001344 // Method might have more arguments than selector indicates. This is due
1345 // to addition of c-style arguments in method.
1346 if (Method->param_size() > Sel.getNumArgs())
1347 NumNamedArgs = Method->param_size();
1348 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001349 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001350 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001351 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001352 return false;
1353 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001354
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001355 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001356 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001357 // We can't do any type-checking on a type-dependent argument.
1358 if (Args[i]->isTypeDependent())
1359 continue;
1360
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001361 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001362
John McCall4124c492011-10-17 18:40:02 +00001363 ParmVarDecl *param = Method->param_begin()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001364 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001365
John McCall4124c492011-10-17 18:40:02 +00001366 // Strip the unbridged-cast placeholder expression off unless it's
1367 // a consumed argument.
1368 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1369 !param->hasAttr<CFConsumedAttr>())
1370 argExpr = stripARCUnbridgedCast(argExpr);
1371
John McCallea0a39e2012-11-14 00:49:39 +00001372 // If the parameter is __unknown_anytype, infer its type
1373 // from the argument.
1374 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001375 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001376 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001377 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001378 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001379 } else {
1380 Args[i] = argE.take();
John McCallea0a39e2012-11-14 00:49:39 +00001381
John McCallcc5788c2013-03-04 07:34:02 +00001382 // Update the parameter type in-place.
1383 param->setType(paramType);
1384 }
1385 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001386 }
1387
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001388 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall4124c492011-10-17 18:40:02 +00001389 param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001390 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001391 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001392
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001393 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall4124c492011-10-17 18:40:02 +00001394 param);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001395 ExprResult ArgE = PerformCopyInitialization(Entity, SelLoc, Owned(argExpr));
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001396 if (ArgE.isInvalid())
1397 IsError = true;
1398 else
1399 Args[i] = ArgE.takeAs<Expr>();
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001400 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001401
1402 // Promote additional arguments to variadic methods.
1403 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001404 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001405 if (Args[i]->isTypeDependent())
1406 continue;
1407
Jordy Roseaca01f92012-05-12 17:32:52 +00001408 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
1409 0);
John Wiegley01296292011-04-08 18:41:53 +00001410 IsError |= Arg.isInvalid();
1411 Args[i] = Arg.take();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001412 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001413 } else {
1414 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001415 if (Args.size() != NumNamedArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00001416 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001417 diag::err_typecheck_call_too_many_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001418 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001419 << Method->getSourceRange()
Chris Lattner3b054132008-11-19 05:08:23 +00001420 << SourceRange(Args[NumNamedArgs]->getLocStart(),
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001421 Args.back()->getLocEnd());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001422 }
1423 }
1424
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001425 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001426
1427 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001428 IsError |= CheckObjCMethodCall(
Robert Wilhelm88e02492013-08-19 07:57:02 +00001429 Method, SelLoc, makeArrayRef<const Expr *>(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001430
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001431 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001432}
1433
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001434bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001435 // 'self' is objc 'self' in an objc method only.
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001436 ObjCMethodDecl *Method =
1437 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1438 return isSelfExpr(RExpr, Method);
1439}
1440
1441bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
John McCallfe96e0b2011-11-06 09:01:30 +00001442 if (!method) return false;
1443
John McCall31168b02011-06-15 23:02:42 +00001444 receiver = receiver->IgnoreParenLValueCasts();
1445 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001446 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001447 return true;
1448 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001449}
1450
John McCall526ab472011-10-25 17:37:35 +00001451/// LookupMethodInType - Look up a method in an ObjCObjectType.
1452ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1453 bool isInstance) {
1454 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1455 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1456 // Look it up in the main interface (and categories, etc.)
1457 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1458 return method;
1459
1460 // Okay, look for "private" methods declared in any
1461 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001462 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1463 return method;
John McCall526ab472011-10-25 17:37:35 +00001464 }
1465
1466 // Check qualifiers.
Aaron Ballman1683f7b2014-03-17 15:55:30 +00001467 for (const auto *I : objType->quals())
1468 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
John McCall526ab472011-10-25 17:37:35 +00001469 return method;
1470
1471 return 0;
1472}
1473
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001474/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1475/// list of a qualified objective pointer type.
1476ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1477 const ObjCObjectPointerType *OPT,
1478 bool Instance)
1479{
1480 ObjCMethodDecl *MD = 0;
Aaron Ballman83731462014-03-17 16:14:00 +00001481 for (const auto *PROTO : OPT->quals()) {
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001482 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1483 return MD;
1484 }
1485 }
1486 return 0;
1487}
1488
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001489static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1490 if (!Receiver)
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001491 return;
1492
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001493 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver))
1494 Receiver = OVE->getSourceExpr();
1495
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001496 Expr *RExpr = Receiver->IgnoreParenImpCasts();
1497 SourceLocation Loc = RExpr->getLocStart();
1498 QualType T = RExpr->getType();
Jordan Rose2bd991a2012-10-10 16:42:54 +00001499 const ObjCPropertyDecl *PDecl = 0;
1500 const ObjCMethodDecl *GDecl = 0;
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001501 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1502 RExpr = POE->getSyntacticForm();
1503 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1504 if (PRE->isImplicitProperty()) {
1505 GDecl = PRE->getImplicitPropertyGetter();
1506 if (GDecl) {
Alp Toker314cc812014-01-25 16:55:45 +00001507 T = GDecl->getReturnType();
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001508 }
1509 }
1510 else {
1511 PDecl = PRE->getExplicitProperty();
1512 if (PDecl) {
1513 T = PDecl->getType();
1514 }
1515 }
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001516 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001517 }
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001518 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) {
1519 // See if receiver is a method which envokes a synthesized getter
1520 // backing a 'weak' property.
1521 ObjCMethodDecl *Method = ME->getMethodDecl();
Jordan Rose2bd991a2012-10-10 16:42:54 +00001522 if (Method && Method->getSelector().getNumArgs() == 0) {
1523 PDecl = Method->findPropertyDecl();
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001524 if (PDecl)
1525 T = PDecl->getType();
1526 }
1527 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001528
Jordan Rose13d6b712012-09-28 22:21:42 +00001529 if (T.getObjCLifetime() != Qualifiers::OCL_Weak) {
1530 if (!PDecl)
1531 return;
1532 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak))
1533 return;
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001534 }
Jordan Rose13d6b712012-09-28 22:21:42 +00001535
1536 S.Diag(Loc, diag::warn_receiver_is_weak)
1537 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1538
1539 if (PDecl)
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001540 S.Diag(PDecl->getLocation(), diag::note_property_declare);
Jordan Rose13d6b712012-09-28 22:21:42 +00001541 else if (GDecl)
1542 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
1543
1544 S.Diag(Loc, diag::note_arc_assign_to_strong);
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001545}
1546
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001547/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1548/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001549ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001550HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001551 Expr *BaseExpr, SourceLocation OpLoc,
1552 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001553 SourceLocation MemberLoc,
1554 SourceLocation SuperLoc, QualType SuperType,
1555 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001556 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1557 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001558
Benjamin Kramer365082d2012-05-19 16:34:46 +00001559 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001560 Diag(MemberLoc, diag::err_invalid_property_name)
1561 << MemberName << QualType(OPT, 0);
1562 return ExprError();
1563 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001564
1565 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregord6459312011-04-20 18:19:55 +00001566
Douglas Gregor4123a862011-11-14 22:10:01 +00001567 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1568 : BaseExpr->getSourceRange();
1569 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001570 diag::err_property_not_found_forward_class,
1571 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001572 return ExprError();
Douglas Gregor4123a862011-11-14 22:10:01 +00001573
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001574 // Search for a declared property first.
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001575 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001576 // Check whether we can reference this property.
1577 if (DiagnoseUseOfDecl(PD, MemberLoc))
1578 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001579 if (Super)
John McCall526ab472011-10-25 17:37:35 +00001580 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001581 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001582 MemberLoc,
1583 SuperLoc, SuperType));
1584 else
John McCall526ab472011-10-25 17:37:35 +00001585 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001586 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001587 MemberLoc, BaseExpr));
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001588 }
1589 // Check protocols on qualified interfaces.
Aaron Ballman83731462014-03-17 16:14:00 +00001590 for (const auto *I : OPT->quals())
1591 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001592 // Check whether we can reference this property.
1593 if (DiagnoseUseOfDecl(PD, MemberLoc))
1594 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001595
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001596 if (Super)
John McCall526ab472011-10-25 17:37:35 +00001597 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1598 Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001599 VK_LValue,
1600 OK_ObjCProperty,
1601 MemberLoc,
1602 SuperLoc, SuperType));
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001603 else
John McCall526ab472011-10-25 17:37:35 +00001604 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1605 Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001606 VK_LValue,
1607 OK_ObjCProperty,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001608 MemberLoc,
1609 BaseExpr));
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001610 }
1611 // If that failed, look for an "implicit" property by seeing if the nullary
1612 // selector is implemented.
1613
1614 // FIXME: The logic for looking up nullary and unary selectors should be
1615 // shared with the code in ActOnInstanceMessage.
1616
1617 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1618 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001619
1620 // May be founf in property's qualified list.
1621 if (!Getter)
1622 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001623
1624 // If this reference is in an @implementation, check for 'private' methods.
1625 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001626 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001627
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001628 if (Getter) {
1629 // Check if we can reference this property.
1630 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1631 return ExprError();
1632 }
1633 // If we found a getter then this may be a valid dot-reference, we
1634 // will look for the matching setter, in case it is needed.
1635 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001636 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1637 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001638 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001639
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001640 // May be founf in property's qualified list.
1641 if (!Setter)
1642 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1643
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001644 if (!Setter) {
1645 // If this reference is in an @implementation, also check for 'private'
1646 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001647 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001648 }
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001649
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001650 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1651 return ExprError();
1652
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001653 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001654 if (Super)
John McCallb7bd14f2010-12-02 01:19:52 +00001655 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001656 Context.PseudoObjectTy,
1657 VK_LValue, OK_ObjCProperty,
John McCallb7bd14f2010-12-02 01:19:52 +00001658 MemberLoc,
1659 SuperLoc, SuperType));
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001660 else
John McCallb7bd14f2010-12-02 01:19:52 +00001661 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001662 Context.PseudoObjectTy,
1663 VK_LValue, OK_ObjCProperty,
John McCallb7bd14f2010-12-02 01:19:52 +00001664 MemberLoc, BaseExpr));
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001665
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001666 }
1667
1668 // Attempt to correct for typos in property names.
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001669 DeclFilterCCC<ObjCPropertyDecl> Validator;
1670 if (TypoCorrection Corrected = CorrectTypo(
Richard Smithf9b15102013-08-17 00:46:16 +00001671 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
1672 NULL, Validator, IFace, false, OPT)) {
1673 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1674 << MemberName << QualType(OPT, 0));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001675 DeclarationName TypoResult = Corrected.getCorrection();
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001676 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1677 TypoResult, MemberLoc,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001678 SuperLoc, SuperType, Super);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001679 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001680 ObjCInterfaceDecl *ClassDeclared;
1681 if (ObjCIvarDecl *Ivar =
1682 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1683 QualType T = Ivar->getType();
1684 if (const ObjCObjectPointerType * OBJPT =
1685 T->getAsObjCInterfacePointerType()) {
Douglas Gregor4123a862011-11-14 22:10:01 +00001686 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001687 diag::err_property_not_as_forward_class,
1688 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001689 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001690 }
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001691 Diag(MemberLoc,
1692 diag::err_ivar_access_using_property_syntax_suggest)
1693 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1694 << FixItHint::CreateReplacement(OpLoc, "->");
1695 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001696 }
Chris Lattner90c58fa2010-04-11 07:51:10 +00001697
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001698 Diag(MemberLoc, diag::err_property_not_found)
1699 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001700 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001701 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001702 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001703 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001704}
1705
1706
1707
John McCalldadc5752010-08-24 06:29:42 +00001708ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001709ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1710 IdentifierInfo &propertyName,
1711 SourceLocation receiverNameLoc,
1712 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001713
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001714 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001715 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1716 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001717
1718 bool IsSuper = false;
Chris Lattnera36ec422010-04-11 08:28:14 +00001719 if (IFace == 0) {
1720 // If the "receiver" is 'super' in a method, handle it as an expression-like
1721 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001722 if (receiverNamePtr->isStr("super")) {
Douglas Gregor33823722011-06-11 01:09:30 +00001723 IsSuper = true;
1724
Eli Friedman24af8502012-02-03 22:47:37 +00001725 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001726 if (CurMethod->isInstanceMethod()) {
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00001727 ObjCInterfaceDecl *Super =
1728 CurMethod->getClassInterface()->getSuperClass();
1729 if (!Super) {
1730 // The current class does not have a superclass.
1731 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1732 << CurMethod->getClassInterface()->getIdentifier();
1733 return ExprError();
1734 }
1735 QualType T = Context.getObjCInterfaceType(Super);
Chris Lattnera36ec422010-04-11 08:28:14 +00001736 T = Context.getObjCObjectPointerType(T);
Chris Lattnera36ec422010-04-11 08:28:14 +00001737
1738 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001739 /*BaseExpr*/0,
1740 SourceLocation()/*OpLoc*/,
1741 &propertyName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001742 propertyNameLoc,
1743 receiverNameLoc, T, true);
Chris Lattnera36ec422010-04-11 08:28:14 +00001744 }
Mike Stump11289f42009-09-09 15:08:12 +00001745
Chris Lattnera36ec422010-04-11 08:28:14 +00001746 // Otherwise, if this is a class method, try dispatching to our
1747 // superclass.
1748 IFace = CurMethod->getClassInterface()->getSuperClass();
1749 }
John McCall5f2d5562011-02-03 09:00:02 +00001750 }
Chris Lattnera36ec422010-04-11 08:28:14 +00001751
1752 if (IFace == 0) {
Alp Tokerec543272013-12-24 09:48:30 +00001753 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1754 << tok::l_paren;
Chris Lattnera36ec422010-04-11 08:28:14 +00001755 return ExprError();
1756 }
1757 }
1758
1759 // Search for a declared property first.
Steve Naroff9527bbf2009-03-09 21:12:44 +00001760 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001761 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001762
1763 // If this reference is in an @implementation, check for 'private' methods.
1764 if (!Getter)
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001765 Getter = IFace->lookupPrivateClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001766
1767 if (Getter) {
1768 // FIXME: refactor/share with ActOnMemberReference().
1769 // Check if we can reference this property.
1770 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1771 return ExprError();
1772 }
Mike Stump11289f42009-09-09 15:08:12 +00001773
Steve Naroff9527bbf2009-03-09 21:12:44 +00001774 // Look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00001775 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001776 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1777 PP.getSelectorTable(),
1778 &propertyName);
Mike Stump11289f42009-09-09 15:08:12 +00001779
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001780 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001781 if (!Setter) {
1782 // If this reference is in an @implementation, also check for 'private'
1783 // methods.
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001784 Setter = IFace->lookupPrivateClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001785 }
1786 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00001787 if (!Setter)
1788 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001789
1790 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1791 return ExprError();
1792
1793 if (Getter || Setter) {
Douglas Gregor33823722011-06-11 01:09:30 +00001794 if (IsSuper)
1795 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001796 Context.PseudoObjectTy,
1797 VK_LValue, OK_ObjCProperty,
Douglas Gregor33823722011-06-11 01:09:30 +00001798 propertyNameLoc,
1799 receiverNameLoc,
1800 Context.getObjCInterfaceType(IFace)));
1801
John McCallb7bd14f2010-12-02 01:19:52 +00001802 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001803 Context.PseudoObjectTy,
1804 VK_LValue, OK_ObjCProperty,
John McCallb7bd14f2010-12-02 01:19:52 +00001805 propertyNameLoc,
1806 receiverNameLoc, IFace));
Steve Naroff9527bbf2009-03-09 21:12:44 +00001807 }
1808 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1809 << &propertyName << Context.getObjCInterfaceType(IFace));
1810}
1811
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001812namespace {
1813
1814class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1815 public:
1816 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1817 // Determine whether "super" is acceptable in the current context.
1818 if (Method && Method->getClassInterface())
1819 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1820 }
1821
Craig Toppere14c0f82014-03-12 04:55:44 +00001822 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001823 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1824 candidate.isKeyword("super");
1825 }
1826};
1827
1828}
1829
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001830Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001831 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001832 SourceLocation NameLoc,
1833 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001834 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00001835 ParsedType &ReceiverType) {
1836 ReceiverType = ParsedType();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001837
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001838 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00001839 // messaging super. If the identifier is "super" and there is a
1840 // trailing dot, it's an instance message.
1841 if (IsSuper && S->isInObjcMethodScope())
1842 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001843
1844 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1845 LookupName(Result, S);
1846
1847 switch (Result.getResultKind()) {
1848 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00001849 // Normal name lookup didn't find anything. If we're in an
1850 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00001851 // FIXME: This is a hack. Ivar lookup should be part of normal
1852 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00001853 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00001854 if (!Method->getClassInterface()) {
1855 // Fall back: let the parser try to parse it as an instance message.
1856 return ObjCInstanceMessage;
1857 }
1858
Douglas Gregorca7136b2010-04-19 20:09:36 +00001859 ObjCInterfaceDecl *ClassDeclared;
1860 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1861 ClassDeclared))
1862 return ObjCInstanceMessage;
1863 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00001864
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001865 // Break out; we'll perform typo correction below.
1866 break;
1867
1868 case LookupResult::NotFoundInCurrentInstantiation:
1869 case LookupResult::FoundOverloaded:
1870 case LookupResult::FoundUnresolvedValue:
1871 case LookupResult::Ambiguous:
1872 Result.suppressDiagnostics();
1873 return ObjCInstanceMessage;
1874
1875 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00001876 // If the identifier is a class or not, and there is a trailing dot,
1877 // it's an instance message.
1878 if (HasTrailingDot)
1879 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001880 // We found something. If it's a type, then we have a class
1881 // message. Otherwise, it's an instance message.
1882 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001883 QualType T;
1884 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1885 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001886 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00001887 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001888 DiagnoseUseOfDecl(Type, NameLoc);
1889 }
1890 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00001891 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001892
Douglas Gregore5798dc2010-04-21 20:38:13 +00001893 // We have a class message, and T is the type we're
1894 // messaging. Build source-location information for it.
1895 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00001896 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00001897 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001898 }
1899 }
1900
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001901 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00001902 if (TypoCorrection Corrected =
1903 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1904 NULL, Validator, NULL, false, NULL, false)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001905 if (Corrected.isKeyword()) {
1906 // If we've found the keyword "super" (the only keyword that would be
1907 // returned by CorrectTypo), this is a send to super.
Richard Smithf9b15102013-08-17 00:46:16 +00001908 diagnoseTypo(Corrected,
1909 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001910 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001911 } else if (ObjCInterfaceDecl *Class =
Richard Smithf9b15102013-08-17 00:46:16 +00001912 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001913 // If we found a declaration, correct when it refers to an Objective-C
1914 // class.
Richard Smithf9b15102013-08-17 00:46:16 +00001915 diagnoseTypo(Corrected,
1916 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001917 QualType T = Context.getObjCInterfaceType(Class);
1918 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1919 ReceiverType = CreateParsedType(T, TSInfo);
1920 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001921 }
1922 }
Richard Smithf9b15102013-08-17 00:46:16 +00001923
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001924 // Fall back: let the parser try to parse it as an instance message.
1925 return ObjCInstanceMessage;
1926}
Steve Naroff9527bbf2009-03-09 21:12:44 +00001927
John McCalldadc5752010-08-24 06:29:42 +00001928ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001929 SourceLocation SuperLoc,
1930 Selector Sel,
1931 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00001932 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001933 SourceLocation RBracLoc,
1934 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001935 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00001936 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00001937 if (!Method) {
1938 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1939 return ExprError();
1940 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001941
Douglas Gregor4fdba132010-04-21 20:01:04 +00001942 ObjCInterfaceDecl *Class = Method->getClassInterface();
1943 if (!Class) {
1944 Diag(SuperLoc, diag::error_no_super_class_message)
1945 << Method->getDeclName();
1946 return ExprError();
1947 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001948
Douglas Gregor4fdba132010-04-21 20:01:04 +00001949 ObjCInterfaceDecl *Super = Class->getSuperClass();
1950 if (!Super) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001951 // The current class does not have a superclass.
Ted Kremenek499897b2011-01-23 17:21:34 +00001952 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1953 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001954 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00001955 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001956
Douglas Gregor4fdba132010-04-21 20:01:04 +00001957 // We are in a method whose class has a superclass, so 'super'
1958 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00001959 if (Method->getSelector() == Sel)
1960 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00001961
Jordan Rose2afd6612012-10-19 16:05:26 +00001962 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00001963 // Since we are in an instance method, this is an instance
1964 // message to the superclass instance.
1965 QualType SuperTy = Context.getObjCInterfaceType(Super);
1966 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCallb268a282010-08-23 23:25:46 +00001967 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001968 Sel, /*Method=*/0,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001969 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001970 }
Douglas Gregor4fdba132010-04-21 20:01:04 +00001971
1972 // Since we are in a class method, this is a class message to
1973 // the superclass.
1974 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1975 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001976 SuperLoc, Sel, /*Method=*/0,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001977 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001978}
1979
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001980
1981ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1982 bool isSuperReceiver,
1983 SourceLocation Loc,
1984 Selector Sel,
1985 ObjCMethodDecl *Method,
1986 MultiExprArg Args) {
1987 TypeSourceInfo *receiverTypeInfo = 0;
1988 if (!ReceiverType.isNull())
1989 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1990
1991 return BuildClassMessage(receiverTypeInfo, ReceiverType,
1992 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1993 Sel, Method, Loc, Loc, Loc, Args,
1994 /*isImplicit=*/true);
1995
1996}
1997
Ted Kremeneke65b0862012-03-06 20:05:56 +00001998static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
1999 unsigned DiagID,
2000 bool (*refactor)(const ObjCMessageExpr *,
2001 const NSAPI &, edit::Commit &)) {
2002 SourceLocation MsgLoc = Msg->getExprLoc();
2003 if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
2004 return;
2005
2006 SourceManager &SM = S.SourceMgr;
2007 edit::Commit ECommit(SM, S.LangOpts);
2008 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2009 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2010 << Msg->getSelector() << Msg->getSourceRange();
2011 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2012 if (!ECommit.isCommitable())
2013 return;
2014 for (edit::Commit::edit_iterator
2015 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2016 const edit::Commit::Edit &Edit = *I;
2017 switch (Edit.Kind) {
2018 case edit::Commit::Act_Insert:
2019 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2020 Edit.Text,
2021 Edit.BeforePrev));
2022 break;
2023 case edit::Commit::Act_InsertFromRange:
2024 Builder.AddFixItHint(
2025 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2026 Edit.getInsertFromRange(SM),
2027 Edit.BeforePrev));
2028 break;
2029 case edit::Commit::Act_Remove:
2030 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2031 break;
2032 }
2033 }
2034 }
2035}
2036
2037static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2038 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2039 edit::rewriteObjCRedundantCallWithLiteral);
2040}
2041
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002042/// \brief Build an Objective-C class message expression.
2043///
2044/// This routine takes care of both normal class messages and
2045/// class messages to the superclass.
2046///
2047/// \param ReceiverTypeInfo Type source information that describes the
2048/// receiver of this message. This may be NULL, in which case we are
2049/// sending to the superclass and \p SuperLoc must be a valid source
2050/// location.
2051
2052/// \param ReceiverType The type of the object receiving the
2053/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2054/// type as that refers to. For a superclass send, this is the type of
2055/// the superclass.
2056///
2057/// \param SuperLoc The location of the "super" keyword in a
2058/// superclass message.
2059///
2060/// \param Sel The selector to which the message is being sent.
2061///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002062/// \param Method The method that this class message is invoking, if
2063/// already known.
2064///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002065/// \param LBracLoc The location of the opening square bracket ']'.
2066///
James Dennettffad8b72012-06-22 08:10:18 +00002067/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002068///
James Dennettffad8b72012-06-22 08:10:18 +00002069/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002070ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002071 QualType ReceiverType,
2072 SourceLocation SuperLoc,
2073 Selector Sel,
2074 ObjCMethodDecl *Method,
2075 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002076 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002077 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002078 MultiExprArg ArgsIn,
2079 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002080 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002081 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002082 if (LBracLoc.isInvalid()) {
2083 Diag(Loc, diag::err_missing_open_square_message_send)
2084 << FixItHint::CreateInsertion(Loc, "[");
2085 LBracLoc = Loc;
2086 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002087 SourceLocation SelLoc;
2088 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2089 SelLoc = SelectorLocs.front();
2090 else
2091 SelLoc = Loc;
2092
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002093 if (ReceiverType->isDependentType()) {
2094 // If the receiver type is dependent, we can't type-check anything
2095 // at this point. Build a dependent expression.
2096 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002097 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002098 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCall7decc9e2010-11-18 06:31:45 +00002099 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
2100 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002101 Sel, SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002102 makeArrayRef(Args, NumArgs),RBracLoc,
2103 isImplicit));
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002104 }
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002105
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002106 // Find the class to which we are sending this message.
2107 ObjCInterfaceDecl *Class = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002108 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2109 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002110 Diag(Loc, diag::err_invalid_receiver_class_message)
2111 << ReceiverType;
2112 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002113 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002114 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002115 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002116 if (!getLangOpts().CPlusPlus)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002117 (void)DiagnoseUseOfDecl(Class, SelLoc);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002118 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002119 if (!Method) {
Douglas Gregor4123a862011-11-14 22:10:01 +00002120 SourceRange TypeRange
2121 = SuperLoc.isValid()? SourceRange(SuperLoc)
2122 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002123 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002124 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002125 ? diag::err_arc_receiver_forward_class
2126 : diag::warn_receiver_forward_class),
2127 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002128 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorb5186b12010-04-22 17:01:48 +00002129 Method = LookupFactoryMethodInGlobalPool(Sel,
2130 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002131 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002132 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2133 << Method->getDeclName();
2134 }
2135 if (!Method)
2136 Method = Class->lookupClassMethod(Sel);
2137
2138 // If we have an implementation in scope, check "private" methods.
2139 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002140 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002141
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002142 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002143 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002144 }
Mike Stump11289f42009-09-09 15:08:12 +00002145
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002146 // Check the argument types and determine the result type.
2147 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002148 ExprValueKind VK = VK_RValue;
2149
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002150 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002151 Expr **Args = ArgsIn.data();
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002152 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2153 Sel, SelectorLocs,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00002154 Method, true,
Douglas Gregor33823722011-06-11 01:09:30 +00002155 SuperLoc.isValid(), LBracLoc, RBracLoc,
2156 ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002157 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002158
Alp Toker314cc812014-01-25 16:55:45 +00002159 if (Method && !Method->getReturnType()->isVoidType() &&
2160 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002161 diag::err_illegal_message_expr_incomplete_type))
2162 return ExprError();
2163
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002164 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002165 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002166 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002167 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002168 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002169 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002170 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002171 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002172 else {
John McCall7decc9e2010-11-18 06:31:45 +00002173 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002174 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002175 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002176 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002177 if (!isImplicit)
2178 checkCocoaAPI(*this, Result);
2179 }
Douglas Gregoraae38d62010-05-22 05:17:18 +00002180 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002181}
2182
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002183// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002184// ArgExprs is optional - if it is present, the number of expressions
2185// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002186ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002187 ParsedType Receiver,
2188 Selector Sel,
2189 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002190 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002191 SourceLocation RBracLoc,
2192 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002193 TypeSourceInfo *ReceiverTypeInfo;
2194 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2195 if (ReceiverType.isNull())
2196 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002197
Mike Stump11289f42009-09-09 15:08:12 +00002198
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002199 if (!ReceiverTypeInfo)
2200 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2201
2202 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorb5186b12010-04-22 17:01:48 +00002203 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002204 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002205}
2206
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002207ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2208 QualType ReceiverType,
2209 SourceLocation Loc,
2210 Selector Sel,
2211 ObjCMethodDecl *Method,
2212 MultiExprArg Args) {
2213 return BuildInstanceMessage(Receiver, ReceiverType,
2214 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2215 Sel, Method, Loc, Loc, Loc, Args,
2216 /*isImplicit=*/true);
2217}
2218
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002219/// \brief Build an Objective-C instance message expression.
2220///
2221/// This routine takes care of both normal instance messages and
2222/// instance messages to the superclass instance.
2223///
2224/// \param Receiver The expression that computes the object that will
2225/// receive this message. This may be empty, in which case we are
2226/// sending to the superclass instance and \p SuperLoc must be a valid
2227/// source location.
2228///
2229/// \param ReceiverType The (static) type of the object receiving the
2230/// message. When a \p Receiver expression is provided, this is the
2231/// same type as that expression. For a superclass instance send, this
2232/// is a pointer to the type of the superclass.
2233///
2234/// \param SuperLoc The location of the "super" keyword in a
2235/// superclass instance message.
2236///
2237/// \param Sel The selector to which the message is being sent.
2238///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002239/// \param Method The method that this instance message is invoking, if
2240/// already known.
2241///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002242/// \param LBracLoc The location of the opening square bracket ']'.
2243///
James Dennettffad8b72012-06-22 08:10:18 +00002244/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002245///
James Dennettffad8b72012-06-22 08:10:18 +00002246/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002247ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002248 QualType ReceiverType,
2249 SourceLocation SuperLoc,
2250 Selector Sel,
2251 ObjCMethodDecl *Method,
2252 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002253 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002254 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002255 MultiExprArg ArgsIn,
2256 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002257 // The location of the receiver.
2258 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002259 SourceRange RecRange =
2260 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2261 SourceLocation SelLoc;
2262 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2263 SelLoc = SelectorLocs.front();
2264 else
2265 SelLoc = Loc;
2266
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002267 if (LBracLoc.isInvalid()) {
2268 Diag(Loc, diag::err_missing_open_square_message_send)
2269 << FixItHint::CreateInsertion(Loc, "[");
2270 LBracLoc = Loc;
2271 }
2272
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002273 // If we have a receiver expression, perform appropriate promotions
2274 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002275 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002276 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002277 ExprResult Result;
2278 if (Receiver->getType() == Context.UnknownAnyTy)
2279 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2280 else
2281 Result = CheckPlaceholderExpr(Receiver);
2282 if (Result.isInvalid()) return ExprError();
2283 Receiver = Result.take();
John McCall4124c492011-10-17 18:40:02 +00002284 }
2285
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002286 if (Receiver->isTypeDependent()) {
2287 // If the receiver is type-dependent, we can't type-check anything
2288 // at this point. Build a dependent expression.
2289 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002290 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002291 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2292 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00002293 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002294 SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002295 makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002296 RBracLoc, isImplicit));
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002297 }
2298
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002299 // If necessary, apply function/array conversion to the receiver.
2300 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002301 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2302 if (Result.isInvalid())
2303 return ExprError();
2304 Receiver = Result.take();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002305 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002306
2307 // If the receiver is an ObjC pointer, a block pointer, or an
2308 // __attribute__((NSObject)) pointer, we don't need to do any
2309 // special conversion in order to look up a receiver.
2310 if (ReceiverType->isObjCRetainableType()) {
2311 // do nothing
2312 } else if (!getLangOpts().ObjCAutoRefCount &&
2313 !Context.getObjCIdType().isNull() &&
2314 (ReceiverType->isPointerType() ||
2315 ReceiverType->isIntegerType())) {
2316 // Implicitly convert integers and pointers to 'id' but emit a warning.
2317 // But not in ARC.
2318 Diag(Loc, diag::warn_bad_receiver_type)
2319 << ReceiverType
2320 << Receiver->getSourceRange();
2321 if (ReceiverType->isPointerType()) {
2322 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2323 CK_CPointerToObjCPointerCast).take();
2324 } else {
2325 // TODO: specialized warning on null receivers?
2326 bool IsNull = Receiver->isNullPointerConstant(Context,
2327 Expr::NPC_ValueDependentIsNull);
2328 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2329 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2330 Kind).take();
2331 }
2332 ReceiverType = Receiver->getType();
2333 } else if (getLangOpts().CPlusPlus) {
Douglas Gregor4b60a152013-11-07 22:34:54 +00002334 // The receiver must be a complete type.
2335 if (RequireCompleteType(Loc, Receiver->getType(),
2336 diag::err_incomplete_receiver_type))
2337 return ExprError();
2338
John McCall80c93a02013-03-01 09:20:14 +00002339 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2340 if (result.isUsable()) {
2341 Receiver = result.take();
2342 ReceiverType = Receiver->getType();
2343 }
2344 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002345 }
2346
John McCall80c93a02013-03-01 09:20:14 +00002347 // There's a somewhat weird interaction here where we assume that we
2348 // won't actually have a method unless we also don't need to do some
2349 // of the more detailed type-checking on the receiver.
2350
Douglas Gregorb5186b12010-04-22 17:01:48 +00002351 if (!Method) {
2352 // Handle messages to id.
Fariborz Jahanian32e59ba2010-08-10 18:10:50 +00002353 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002354 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002355 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2356 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002357 SourceRange(LBracLoc, RBracLoc),
2358 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002359 if (!Method)
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002360 Method = LookupFactoryMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002361 SourceRange(LBracLoc,RBracLoc),
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002362 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002363 } else if (ReceiverType->isObjCClassType() ||
2364 ReceiverType->isObjCQualifiedClassType()) {
2365 // Handle messages to Class.
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002366 // We allow sending a message to a qualified Class ("Class<foo>"), which
2367 // is ok as long as one of the protocols implements the selector (if not, warn).
2368 if (const ObjCObjectPointerType *QClassTy
2369 = ReceiverType->getAsObjCQualifiedClassType()) {
2370 // Search protocols for class methods.
2371 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2372 if (!Method) {
2373 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2374 // warn if instance method found for a Class message.
2375 if (Method) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002376 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002377 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002378 Diag(Method->getLocation(), diag::note_method_declared_at)
2379 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002380 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002381 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002382 } else {
2383 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2384 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2385 // First check the public methods in the class interface.
2386 Method = ClassDecl->lookupClassMethod(Sel);
2387
2388 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002389 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002390 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002391 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002392 return ExprError();
2393 }
2394 if (!Method) {
2395 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002396 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002397 Method = LookupFactoryMethodInGlobalPool(Sel,
2398 SourceRange(LBracLoc, RBracLoc),
2399 true);
2400 if (!Method) {
2401 // If no class (factory) method was found, check if an _instance_
2402 // method of the same name exists in the root class only.
2403 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002404 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002405 true);
2406 if (Method)
2407 if (const ObjCInterfaceDecl *ID =
2408 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2409 if (ID->getSuperClass())
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002410 Diag(SelLoc, diag::warn_root_inst_method_not_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002411 << Sel << SourceRange(LBracLoc, RBracLoc);
2412 }
2413 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002414 }
2415 }
2416 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002417 } else {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002418 ObjCInterfaceDecl* ClassDecl = 0;
2419
2420 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2421 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002422 // And as long as message is not deprecated/unavailable (warn if it is).
Douglas Gregorb5186b12010-04-22 17:01:48 +00002423 if (const ObjCObjectPointerType *QIdTy
2424 = ReceiverType->getAsObjCQualifiedIdType()) {
2425 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002426 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2427 if (!Method)
2428 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002429 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002430 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002431 } else if (const ObjCObjectPointerType *OCIType
2432 = ReceiverType->getAsObjCInterfacePointerType()) {
2433 // We allow sending a message to a pointer to an interface (an object).
2434 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002435
Douglas Gregor4123a862011-11-14 22:10:01 +00002436 // Try to complete the type. Under ARC, this is a hard error from which
2437 // we don't try to recover.
2438 const ObjCInterfaceDecl *forwardClass = 0;
2439 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002440 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002441 ? diag::err_arc_receiver_forward_instance
2442 : diag::warn_receiver_forward_instance,
2443 Receiver? Receiver->getSourceRange()
2444 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002445 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002446 return ExprError();
2447
2448 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanianc934de62012-02-03 01:02:44 +00002449 Diag(Receiver ? Receiver->getLocStart()
2450 : SuperLoc, diag::note_receiver_is_id);
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002451 Method = 0;
2452 } else {
2453 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002454 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002455
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002456 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002457 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002458 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2459
Douglas Gregorb5186b12010-04-22 17:01:48 +00002460 if (!Method) {
2461 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002462 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002463
David Blaikiebbafb8a2012-03-11 07:00:24 +00002464 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002465 Diag(SelLoc, diag::err_arc_may_not_respond)
2466 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002467 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002468 return ExprError();
2469 }
2470
Douglas Gregor486b74e2011-09-27 16:10:05 +00002471 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002472 // If we still haven't found a method, look in the global pool. This
2473 // behavior isn't very desirable, however we need it for GCC
2474 // compatibility. FIXME: should we deviate??
2475 if (OCIType->qual_empty()) {
2476 Method = LookupInstanceMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002477 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002478 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002479 Diag(SelLoc, diag::warn_maynot_respond)
2480 << OCIType->getInterfaceDecl()->getIdentifier()
2481 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002482 }
2483 }
2484 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002485 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002486 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002487 } else {
John McCall80c93a02013-03-01 09:20:14 +00002488 // Reject other random receiver types (e.g. structs).
2489 Diag(Loc, diag::err_bad_receiver_type)
2490 << ReceiverType << Receiver->getSourceRange();
2491 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002492 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002493 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002494 }
Mike Stump11289f42009-09-09 15:08:12 +00002495
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002496 FunctionScopeInfo *DIFunctionScopeInfo =
2497 (Method && Method->getMethodFamily() == OMF_init)
2498 ? getEnclosingFunction() : 0;
2499
2500 if (DIFunctionScopeInfo &&
2501 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002502 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2503 bool isDesignatedInitChain = false;
2504 if (SuperLoc.isValid()) {
2505 if (const ObjCObjectPointerType *
2506 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2507 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
Argyrios Kyrtzidisd664a342013-12-13 03:48:17 +00002508 // Either we know this is a designated initializer or we
2509 // conservatively assume it because we don't know for sure.
2510 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2511 ID->isDesignatedInitializer(Sel)) {
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002512 isDesignatedInitChain = true;
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002513 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002514 }
2515 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002516 }
2517 }
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002518 if (!isDesignatedInitChain) {
2519 const ObjCMethodDecl *InitMethod = 0;
2520 bool isDesignated =
2521 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2522 assert(isDesignated && InitMethod);
2523 (void)isDesignated;
2524 Diag(SelLoc, SuperLoc.isValid() ?
2525 diag::warn_objc_designated_init_non_designated_init_call :
2526 diag::warn_objc_designated_init_non_super_designated_init_call);
2527 Diag(InitMethod->getLocation(),
2528 diag::note_objc_designated_init_marked_here);
2529 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002530 }
2531
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002532 if (DIFunctionScopeInfo &&
2533 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002534 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2535 if (SuperLoc.isValid()) {
2536 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2537 } else {
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002538 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002539 }
2540 }
2541
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002542 // Check the message arguments.
2543 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002544 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002545 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002546 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00002547 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2548 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002549 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2550 Sel, SelectorLocs, Method,
Douglas Gregor33823722011-06-11 01:09:30 +00002551 ClassMessage, SuperLoc.isValid(),
John McCall7decc9e2010-11-18 06:31:45 +00002552 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002553 return ExprError();
Alp Toker314cc812014-01-25 16:55:45 +00002554
2555 if (Method && !Method->getReturnType()->isVoidType() &&
2556 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002557 diag::err_illegal_message_expr_incomplete_type))
2558 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00002559
John McCall31168b02011-06-15 23:02:42 +00002560 // In ARC, forbid the user from sending messages to
2561 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002562 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002563 ObjCMethodFamily family =
2564 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2565 switch (family) {
2566 case OMF_init:
2567 if (Method)
2568 checkInitMethod(Method, ReceiverType);
2569
2570 case OMF_None:
2571 case OMF_alloc:
2572 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00002573 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002574 case OMF_mutableCopy:
2575 case OMF_new:
2576 case OMF_self:
2577 break;
2578
2579 case OMF_dealloc:
2580 case OMF_retain:
2581 case OMF_release:
2582 case OMF_autorelease:
2583 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002584 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2585 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00002586 break;
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002587
2588 case OMF_performSelector:
2589 if (Method && NumArgs >= 1) {
2590 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2591 Selector ArgSel = SelExp->getSelector();
2592 ObjCMethodDecl *SelMethod =
2593 LookupInstanceMethodInGlobalPool(ArgSel,
2594 SelExp->getSourceRange());
2595 if (!SelMethod)
2596 SelMethod =
2597 LookupFactoryMethodInGlobalPool(ArgSel,
2598 SelExp->getSourceRange());
2599 if (SelMethod) {
2600 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2601 switch (SelFamily) {
2602 case OMF_alloc:
2603 case OMF_copy:
2604 case OMF_mutableCopy:
2605 case OMF_new:
2606 case OMF_self:
2607 case OMF_init:
2608 // Issue error, unless ns_returns_not_retained.
2609 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2610 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002611 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002612 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002613 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2614 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002615 }
2616 break;
2617 default:
2618 // +0 call. OK. unless ns_returns_retained.
2619 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2620 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002621 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002622 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002623 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2624 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002625 }
2626 break;
2627 }
2628 }
2629 } else {
2630 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002631 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002632 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2633 }
2634 }
2635 break;
John McCall31168b02011-06-15 23:02:42 +00002636 }
2637 }
2638
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002639 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00002640 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002641 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002642 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002643 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002644 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002645 makeArrayRef(Args, NumArgs), RBracLoc,
2646 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002647 else {
John McCall7decc9e2010-11-18 06:31:45 +00002648 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002649 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002650 makeArrayRef(Args, NumArgs), RBracLoc,
2651 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002652 if (!isImplicit)
2653 checkCocoaAPI(*this, Result);
2654 }
John McCall31168b02011-06-15 23:02:42 +00002655
David Blaikiebbafb8a2012-03-11 07:00:24 +00002656 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahaniand155c782012-04-19 23:49:39 +00002657 DiagnoseARCUseOfWeakReceiver(*this, Receiver);
Fariborz Jahanian6bd22262012-04-04 20:05:25 +00002658
John McCall31168b02011-06-15 23:02:42 +00002659 // In ARC, annotate delegate init calls.
2660 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00002661 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00002662 // Only consider init calls *directly* in init implementations,
2663 // not within blocks.
2664 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2665 if (method && method->getMethodFamily() == OMF_init) {
2666 // The implicit assignment to self means we also don't want to
2667 // consume the result.
2668 Result->setDelegateInitCall(true);
2669 return Owned(Result);
2670 }
2671 }
2672
2673 // In ARC, check for message sends which are likely to introduce
2674 // retain cycles.
2675 checkRetainCycles(Result);
Jordan Rose22487652012-10-11 16:06:21 +00002676
2677 if (!isImplicit && Method) {
2678 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2679 bool IsWeak =
2680 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2681 if (!IsWeak && Sel.isUnarySelector())
2682 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
2683
2684 if (IsWeak) {
2685 DiagnosticsEngine::Level Level =
2686 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
2687 LBracLoc);
2688 if (Level != DiagnosticsEngine::Ignored)
2689 getCurFunction()->recordUseOfWeak(Result, Prop);
2690
2691 }
2692 }
2693 }
John McCall31168b02011-06-15 23:02:42 +00002694 }
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00002695
Douglas Gregoraae38d62010-05-22 05:17:18 +00002696 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002697}
2698
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002699static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2700 if (ObjCSelectorExpr *OSE =
2701 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2702 Selector Sel = OSE->getSelector();
2703 SourceLocation Loc = OSE->getAtLoc();
2704 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
2705 = S.ReferencedSelectors.find(Sel);
2706 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
2707 S.ReferencedSelectors.erase(Pos);
2708 }
2709}
2710
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002711// ActOnInstanceMessage - used for both unary and keyword messages.
2712// ArgExprs is optional - if it is present, the number of expressions
2713// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002714ExprResult Sema::ActOnInstanceMessage(Scope *S,
2715 Expr *Receiver,
2716 Selector Sel,
2717 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002718 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00002719 SourceLocation RBracLoc,
2720 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002721 if (!Receiver)
2722 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002723
2724 // A ParenListExpr can show up while doing error recovery with invalid code.
2725 if (isa<ParenListExpr>(Receiver)) {
2726 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
2727 if (Result.isInvalid()) return ExprError();
2728 Receiver = Result.take();
2729 }
Fariborz Jahanian17748062013-01-22 19:05:17 +00002730
2731 if (RespondsToSelectorSel.isNull()) {
2732 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
2733 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
2734 }
2735 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002736 RemoveSelectorFromWarningCache(*this, Args[0]);
2737
John McCallb268a282010-08-23 23:25:46 +00002738 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorb5186b12010-04-22 17:01:48 +00002739 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002740 LBracLoc, SelectorLocs, RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002741}
Chris Lattner2a3569b2008-04-07 05:30:13 +00002742
John McCall31168b02011-06-15 23:02:42 +00002743enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00002744 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00002745 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00002746
2747 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00002748 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00002749
2750 /// id*, id***, void (^*)(),
2751 ACTC_indirectRetainable,
2752
2753 /// void* might be a normal C type, or it might a CF type.
2754 ACTC_voidPtr,
2755
2756 /// struct A*
2757 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00002758};
John McCalle4fe2452011-10-01 01:01:08 +00002759static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2760 return (ACTC == ACTC_retainable ||
2761 ACTC == ACTC_coreFoundation ||
2762 ACTC == ACTC_voidPtr);
2763}
2764static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2765 return ACTC == ACTC_none ||
2766 ACTC == ACTC_voidPtr ||
2767 ACTC == ACTC_coreFoundation;
2768}
2769
John McCall31168b02011-06-15 23:02:42 +00002770static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00002771 bool isIndirect = false;
John McCall31168b02011-06-15 23:02:42 +00002772
2773 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00002774 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00002775 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002776 isIndirect = true;
2777 }
John McCall31168b02011-06-15 23:02:42 +00002778
2779 // Drill through pointers and arrays recursively.
2780 while (true) {
2781 if (const PointerType *ptr = type->getAs<PointerType>()) {
2782 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002783
2784 // The first level of pointer may be the innermost pointer on a CF type.
2785 if (!isIndirect) {
2786 if (type->isVoidType()) return ACTC_voidPtr;
2787 if (type->isRecordType()) return ACTC_coreFoundation;
2788 }
John McCall31168b02011-06-15 23:02:42 +00002789 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2790 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2791 } else {
2792 break;
2793 }
John McCalle4fe2452011-10-01 01:01:08 +00002794 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00002795 }
2796
John McCalle4fe2452011-10-01 01:01:08 +00002797 if (isIndirect) {
2798 if (type->isObjCARCBridgableType())
2799 return ACTC_indirectRetainable;
2800 return ACTC_none;
2801 }
2802
2803 if (type->isObjCARCBridgableType())
2804 return ACTC_retainable;
2805
2806 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00002807}
2808
2809namespace {
John McCalle4fe2452011-10-01 01:01:08 +00002810 /// A result from the cast checker.
2811 enum ACCResult {
2812 /// Cannot be casted.
2813 ACC_invalid,
2814
2815 /// Can be safely retained or not retained.
2816 ACC_bottom,
2817
2818 /// Can be casted at +0.
2819 ACC_plusZero,
2820
2821 /// Can be casted at +1.
2822 ACC_plusOne
2823 };
2824 ACCResult merge(ACCResult left, ACCResult right) {
2825 if (left == right) return left;
2826 if (left == ACC_bottom) return right;
2827 if (right == ACC_bottom) return left;
2828 return ACC_invalid;
2829 }
2830
2831 /// A checker which white-lists certain expressions whose conversion
2832 /// to or from retainable type would otherwise be forbidden in ARC.
2833 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2834 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2835
John McCall31168b02011-06-15 23:02:42 +00002836 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00002837 ARCConversionTypeClass SourceClass;
2838 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002839 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00002840
2841 static bool isCFType(QualType type) {
2842 // Someday this can use ns_bridged. For now, it has to do this.
2843 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00002844 }
John McCalle4fe2452011-10-01 01:01:08 +00002845
2846 public:
2847 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002848 ARCConversionTypeClass target, bool diagnose)
2849 : Context(Context), SourceClass(source), TargetClass(target),
2850 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00002851
2852 using super::Visit;
2853 ACCResult Visit(Expr *e) {
2854 return super::Visit(e->IgnoreParens());
2855 }
2856
2857 ACCResult VisitStmt(Stmt *s) {
2858 return ACC_invalid;
2859 }
2860
2861 /// Null pointer constants can be casted however you please.
2862 ACCResult VisitExpr(Expr *e) {
2863 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2864 return ACC_bottom;
2865 return ACC_invalid;
2866 }
2867
2868 /// Objective-C string literals can be safely casted.
2869 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2870 // If we're casting to any retainable type, go ahead. Global
2871 // strings are immune to retains, so this is bottom.
2872 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2873
2874 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002875 }
2876
John McCalle4fe2452011-10-01 01:01:08 +00002877 /// Look through certain implicit and explicit casts.
2878 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002879 switch (e->getCastKind()) {
2880 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00002881 return ACC_bottom;
2882
John McCall31168b02011-06-15 23:02:42 +00002883 case CK_NoOp:
2884 case CK_LValueToRValue:
2885 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002886 case CK_CPointerToObjCPointerCast:
2887 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002888 case CK_AnyPointerToBlockPointerCast:
2889 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00002890
John McCall31168b02011-06-15 23:02:42 +00002891 default:
John McCalle4fe2452011-10-01 01:01:08 +00002892 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002893 }
2894 }
John McCalle4fe2452011-10-01 01:01:08 +00002895
2896 /// Look through unary extension.
2897 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002898 return Visit(e->getSubExpr());
2899 }
John McCalle4fe2452011-10-01 01:01:08 +00002900
2901 /// Ignore the LHS of a comma operator.
2902 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002903 return Visit(e->getRHS());
2904 }
John McCalle4fe2452011-10-01 01:01:08 +00002905
2906 /// Conditional operators are okay if both sides are okay.
2907 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2908 ACCResult left = Visit(e->getTrueExpr());
2909 if (left == ACC_invalid) return ACC_invalid;
2910 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00002911 }
John McCalle4fe2452011-10-01 01:01:08 +00002912
John McCallfe96e0b2011-11-06 09:01:30 +00002913 /// Look through pseudo-objects.
2914 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2915 // If we're getting here, we should always have a result.
2916 return Visit(e->getResultExpr());
2917 }
2918
John McCalle4fe2452011-10-01 01:01:08 +00002919 /// Statement expressions are okay if their result expression is okay.
2920 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002921 return Visit(e->getSubStmt()->body_back());
2922 }
John McCall31168b02011-06-15 23:02:42 +00002923
John McCalle4fe2452011-10-01 01:01:08 +00002924 /// Some declaration references are okay.
2925 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2926 // References to global constants from system headers are okay.
2927 // These are things like 'kCFStringTransformToLatin'. They are
2928 // can also be assumed to be immune to retains.
2929 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2930 if (isAnyRetainable(TargetClass) &&
2931 isAnyRetainable(SourceClass) &&
2932 var &&
2933 var->getStorageClass() == SC_Extern &&
2934 var->getType().isConstQualified() &&
2935 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2936 return ACC_bottom;
2937 }
2938
2939 // Nothing else.
2940 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00002941 }
John McCalle4fe2452011-10-01 01:01:08 +00002942
2943 /// Some calls are okay.
2944 ACCResult VisitCallExpr(CallExpr *e) {
2945 if (FunctionDecl *fn = e->getDirectCallee())
2946 if (ACCResult result = checkCallToFunction(fn))
2947 return result;
2948
2949 return super::VisitCallExpr(e);
2950 }
2951
2952 ACCResult checkCallToFunction(FunctionDecl *fn) {
2953 // Require a CF*Ref return type.
Alp Toker314cc812014-01-25 16:55:45 +00002954 if (!isCFType(fn->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00002955 return ACC_invalid;
2956
2957 if (!isAnyRetainable(TargetClass))
2958 return ACC_invalid;
2959
2960 // Honor an explicit 'not retained' attribute.
2961 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2962 return ACC_plusZero;
2963
2964 // Honor an explicit 'retained' attribute, except that for
2965 // now we're not going to permit implicit handling of +1 results,
2966 // because it's a bit frightening.
2967 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00002968 return Diagnose ? ACC_plusOne
2969 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00002970
2971 // Recognize this specific builtin function, which is used by CFSTR.
2972 unsigned builtinID = fn->getBuiltinID();
2973 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2974 return ACC_bottom;
2975
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00002976 // Otherwise, don't do anything implicit with an unaudited function.
2977 if (!fn->hasAttr<CFAuditedTransferAttr>())
2978 return ACC_invalid;
2979
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002980 // Otherwise, it's +0 unless it follows the create convention.
2981 if (ento::coreFoundation::followsCreateRule(fn))
2982 return Diagnose ? ACC_plusOne
2983 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00002984
John McCalle4fe2452011-10-01 01:01:08 +00002985 return ACC_plusZero;
2986 }
2987
2988 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
2989 return checkCallToMethod(e->getMethodDecl());
2990 }
2991
2992 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
2993 ObjCMethodDecl *method;
2994 if (e->isExplicitProperty())
2995 method = e->getExplicitProperty()->getGetterMethodDecl();
2996 else
2997 method = e->getImplicitPropertyGetter();
2998 return checkCallToMethod(method);
2999 }
3000
3001 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3002 if (!method) return ACC_invalid;
3003
3004 // Check for message sends to functions returning CF types. We
3005 // just obey the Cocoa conventions with these, even though the
3006 // return type is CF.
Alp Toker314cc812014-01-25 16:55:45 +00003007 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003008 return ACC_invalid;
3009
3010 // If the method is explicitly marked not-retained, it's +0.
3011 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3012 return ACC_plusZero;
3013
3014 // If the method is explicitly marked as returning retained, or its
3015 // selector follows a +1 Cocoa convention, treat it as +1.
3016 if (method->hasAttr<CFReturnsRetainedAttr>())
3017 return ACC_plusOne;
3018
3019 switch (method->getSelector().getMethodFamily()) {
3020 case OMF_alloc:
3021 case OMF_copy:
3022 case OMF_mutableCopy:
3023 case OMF_new:
3024 return ACC_plusOne;
3025
3026 default:
3027 // Otherwise, treat it as +0.
3028 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00003029 }
3030 }
John McCalle4fe2452011-10-01 01:01:08 +00003031 };
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00003032}
3033
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003034bool Sema::isKnownName(StringRef name) {
3035 if (name.empty())
3036 return false;
3037 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003038 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003039 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003040}
3041
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003042static void addFixitForObjCARCConversion(Sema &S,
3043 DiagnosticBuilder &DiagB,
3044 Sema::CheckedConversionKind CCK,
3045 SourceLocation afterLParen,
3046 QualType castType,
3047 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003048 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003049 const char *bridgeKeyword,
3050 const char *CFBridgeName) {
3051 // We handle C-style and implicit casts here.
3052 switch (CCK) {
3053 case Sema::CCK_ImplicitConversion:
3054 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003055 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003056 break;
3057 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003058 return;
3059 }
3060
3061 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003062 if (CCK == Sema::CCK_OtherCast) {
3063 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3064 SourceRange range(NCE->getOperatorLoc(),
3065 NCE->getAngleBrackets().getEnd());
3066 SmallString<32> BridgeCall;
3067
3068 SourceManager &SM = S.getSourceManager();
3069 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3070 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3071 BridgeCall += ' ';
3072
3073 BridgeCall += CFBridgeName;
3074 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3075 }
3076 return;
3077 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003078 Expr *castedE = castExpr;
3079 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3080 castedE = CCE->getSubExpr();
3081 castedE = castedE->IgnoreImpCasts();
3082 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00003083
3084 SmallString<32> BridgeCall;
3085
3086 SourceManager &SM = S.getSourceManager();
3087 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3088 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3089 BridgeCall += ' ';
3090
3091 BridgeCall += CFBridgeName;
3092
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003093 if (isa<ParenExpr>(castedE)) {
3094 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003095 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003096 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00003097 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003098 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003099 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003100 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3101 S.PP.getLocForEndOfToken(range.getEnd()),
3102 ")"));
3103 }
3104 return;
3105 }
3106
3107 if (CCK == Sema::CCK_CStyleCast) {
3108 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003109 } else if (CCK == Sema::CCK_OtherCast) {
3110 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3111 std::string castCode = "(";
3112 castCode += bridgeKeyword;
3113 castCode += castType.getAsString();
3114 castCode += ")";
3115 SourceRange Range(NCE->getOperatorLoc(),
3116 NCE->getAngleBrackets().getEnd());
3117 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3118 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003119 } else {
3120 std::string castCode = "(";
3121 castCode += bridgeKeyword;
3122 castCode += castType.getAsString();
3123 castCode += ")";
3124 Expr *castedE = castExpr->IgnoreImpCasts();
3125 SourceRange range = castedE->getSourceRange();
3126 if (isa<ParenExpr>(castedE)) {
3127 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3128 castCode));
3129 } else {
3130 castCode += "(";
3131 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3132 castCode));
3133 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3134 S.PP.getLocForEndOfToken(range.getEnd()),
3135 ")"));
3136 }
3137 }
3138}
3139
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003140template <typename T>
3141static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3142 TypedefNameDecl *TDNDecl = TD->getDecl();
3143 QualType QT = TDNDecl->getUnderlyingType();
3144 if (QT->isPointerType()) {
3145 QT = QT->getPointeeType();
3146 if (const RecordType *RT = QT->getAs<RecordType>())
3147 if (RecordDecl *RD = RT->getDecl())
Aaron Ballman2084f8f2013-12-19 13:20:36 +00003148 return RD->getAttr<T>();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003149 }
3150 return 0;
3151}
3152
3153static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3154 TypedefNameDecl *&TDNDecl) {
3155 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3156 TDNDecl = TD->getDecl();
3157 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3158 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3159 return ObjCBAttr;
3160 T = TDNDecl->getUnderlyingType();
3161 }
3162 return 0;
3163}
3164
John McCall4124c492011-10-17 18:40:02 +00003165static void
3166diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3167 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003168 Expr *castExpr, Expr *realCast,
3169 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003170 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003171 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003172 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00003173
John McCall4124c492011-10-17 18:40:02 +00003174 if (S.makeUnavailableInSystemHeader(loc,
John McCalle4fe2452011-10-01 01:01:08 +00003175 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCall31168b02011-06-15 23:02:42 +00003176 return;
John McCall4124c492011-10-17 18:40:02 +00003177
3178 QualType castExprType = castExpr->getType();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003179 TypedefNameDecl *TDNDecl = 0;
3180 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3181 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3182 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
3183 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
3184 return;
John McCall31168b02011-06-15 23:02:42 +00003185
John McCall640767f2011-06-17 06:50:50 +00003186 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003187 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003188 case ACTC_none:
3189 case ACTC_coreFoundation:
3190 case ACTC_voidPtr:
3191 srcKind = (castExprType->isPointerType() ? 1 : 0);
3192 break;
3193 case ACTC_retainable:
3194 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3195 break;
3196 case ACTC_indirectRetainable:
3197 srcKind = 4;
3198 break;
John McCall31168b02011-06-15 23:02:42 +00003199 }
3200
John McCall4124c492011-10-17 18:40:02 +00003201 // Check whether this could be fixed with a bridge cast.
3202 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3203 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003204
John McCall4124c492011-10-17 18:40:02 +00003205 // Bridge from an ARC type to a CF type.
3206 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003207
John McCall4124c492011-10-17 18:40:02 +00003208 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3209 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3210 << 2 // of C pointer type
3211 << castExprType
3212 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3213 << castType
3214 << castRange
3215 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003216 bool br = S.isKnownName("CFBridgingRelease");
Jordan Rose4502b532012-07-31 01:07:43 +00003217 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003218 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003219 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003220 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003221 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003222 DiagnosticBuilder DiagB =
3223 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3224 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3225
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003226 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003227 castType, castExpr, realCast, "__bridge ", 0);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003228 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003229 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003230 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003231 DiagnosticBuilder DiagB =
3232 (CCK == Sema::CCK_OtherCast && !br) ?
3233 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3234 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3235 diag::note_arc_bridge_transfer)
3236 << castExprType << br;
3237
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003238 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003239 castType, castExpr, realCast, "__bridge_transfer ",
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003240 br ? "CFBridgingRelease" : 0);
3241 }
John McCall4124c492011-10-17 18:40:02 +00003242
3243 return;
3244 }
3245
3246 // Bridge from a CF type to an ARC type.
3247 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003248 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003249 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3250 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3251 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3252 << castExprType
3253 << 2 // to C pointer type
3254 << castType
3255 << castRange
3256 << castExpr->getSourceRange();
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003257 ACCResult CreateRule =
3258 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003259 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003260 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003261 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003262 DiagnosticBuilder DiagB =
3263 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3264 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003265 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003266 castType, castExpr, realCast, "__bridge ", 0);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003267 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003268 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003269 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003270 DiagnosticBuilder DiagB =
3271 (CCK == Sema::CCK_OtherCast && !br) ?
3272 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3273 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3274 diag::note_arc_bridge_retained)
3275 << castType << br;
3276
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003277 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003278 castType, castExpr, realCast, "__bridge_retained ",
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003279 br ? "CFBridgingRetain" : 0);
3280 }
John McCall4124c492011-10-17 18:40:02 +00003281
3282 return;
John McCall31168b02011-06-15 23:02:42 +00003283 }
3284
John McCall4124c492011-10-17 18:40:02 +00003285 S.Diag(loc, diag::err_arc_mismatched_cast)
3286 << (CCK != Sema::CCK_ImplicitConversion)
3287 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003288 << castRange << castExpr->getSourceRange();
3289}
3290
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003291template <typename TB>
Fariborz Jahanian953d18a2014-04-22 17:42:01 +00003292static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3293 bool TollFreeBridgeCast) {
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003294 QualType T = castExpr->getType();
3295 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3296 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003297 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003298 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3299 NamedDecl *Target = 0;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003300 // Check for an existing type with this name.
3301 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3302 Sema::LookupOrdinaryName);
3303 if (S.LookupName(R, S.TUScope)) {
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003304 Target = R.getFoundDecl();
3305 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3306 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3307 if (const ObjCObjectPointerType *InterfacePointerType =
3308 castType->getAsObjCInterfacePointerType()) {
3309 ObjCInterfaceDecl *CastClass
3310 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003311 if ((CastClass == ExprClass) ||
Fariborz Jahanian953d18a2014-04-22 17:42:01 +00003312 (CastClass && ExprClass->isSuperClassOf(CastClass))) {
3313 if (!TollFreeBridgeCast && S.getLangOpts().ObjCAutoRefCount) {
3314 // bridge attribute is ok. However, under ARC, cast still requires
3315 // an explicit cast and should not compile under ARC.
3316 S.Diag(castExpr->getLocStart(), diag::err_objc_invalid_bridge)
3317 << T << Target->getName();
3318 }
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003319 return true;
Fariborz Jahanian953d18a2014-04-22 17:42:01 +00003320 }
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003321 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
Fariborz Jahanian509f31e2013-11-19 01:23:07 +00003322 << T << Target->getName() << castType->getPointeeType();
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003323 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003324 } else if (castType->isObjCIdType() ||
3325 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3326 castType, ExprClass)))
3327 // ok to cast to 'id'.
3328 // casting to id<p-list> is ok if bridge type adopts all of
3329 // p-list protocols.
3330 return true;
3331 else {
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003332 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
Fariborz Jahanian509f31e2013-11-19 01:23:07 +00003333 << T << Target->getName() << castType;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003334 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3335 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003336 return true;
3337 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003338 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003339 }
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003340 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
Aaron Ballmanc0550742014-01-03 02:07:43 +00003341 << castExpr->getType() << Parm;
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003342 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3343 if (Target)
3344 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003345 }
3346 return true;
3347 }
3348 T = TDNDecl->getUnderlyingType();
3349 }
3350 return false;
3351}
3352
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003353template <typename TB>
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003354static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr) {
3355 QualType T = castType;
3356 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3357 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003358 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003359 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3360 NamedDecl *Target = 0;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003361 // Check for an existing type with this name.
3362 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3363 Sema::LookupOrdinaryName);
3364 if (S.LookupName(R, S.TUScope)) {
3365 Target = R.getFoundDecl();
3366 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3367 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3368 if (const ObjCObjectPointerType *InterfacePointerType =
3369 castExpr->getType()->getAsObjCInterfacePointerType()) {
3370 ObjCInterfaceDecl *ExprClass
3371 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003372 if ((CastClass == ExprClass) ||
3373 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003374 return true;
3375 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
Fariborz Jahanian509f31e2013-11-19 01:23:07 +00003376 << castExpr->getType()->getPointeeType() << T;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003377 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3378 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003379 } else if (castExpr->getType()->isObjCIdType() ||
3380 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3381 castExpr->getType(), CastClass)))
3382 // ok to cast an 'id' expression to a CFtype.
3383 // ok to cast an 'id<plist>' expression to CFtype provided plist
3384 // adopts all of CFtype's ObjetiveC's class plist.
3385 return true;
3386 else {
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003387 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3388 << castExpr->getType() << castType;
3389 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003390 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003391 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003392 }
3393 }
3394 }
3395 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3396 << castExpr->getType() << castType;
3397 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3398 if (Target)
3399 S.Diag(Target->getLocStart(), diag::note_declared_at);
3400 }
3401 return true;
3402 }
3403 T = TDNDecl->getUnderlyingType();
3404 }
3405 return false;
3406}
3407
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003408void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003409 // warn in presence of __bridge casting to or from a toll free bridge cast.
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003410 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3411 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003412 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
Fariborz Jahanian953d18a2014-04-22 17:42:01 +00003413 (void)CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, true);
3414 (void)CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003415 }
3416 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
3417 (void)CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr);
3418 (void)CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr);
3419 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003420}
3421
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003422
3423bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3424 QualType DestType, QualType SrcType,
3425 ObjCInterfaceDecl *&RelatedClass,
3426 ObjCMethodDecl *&ClassMethod,
3427 ObjCMethodDecl *&InstanceMethod,
3428 TypedefNameDecl *&TDNDecl,
3429 bool CfToNs) {
3430 QualType T = CfToNs ? SrcType : DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003431 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3432 if (!ObjCBAttr)
3433 return false;
3434
3435 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3436 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3437 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3438 if (!RCId)
3439 return false;
3440 NamedDecl *Target = 0;
3441 // Check for an existing type with this name.
3442 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3443 Sema::LookupOrdinaryName);
3444 if (!LookupName(R, TUScope)) {
3445 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003446 << SrcType << DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003447 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3448 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003449 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003450 Target = R.getFoundDecl();
3451 if (Target && isa<ObjCInterfaceDecl>(Target))
3452 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3453 else {
3454 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3455 << SrcType << DestType;
3456 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3457 if (Target)
3458 Diag(Target->getLocStart(), diag::note_declared_at);
3459 return false;
3460 }
3461
3462 // Check for an existing class method with the given selector name.
3463 if (CfToNs && CMId) {
3464 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3465 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3466 if (!ClassMethod) {
3467 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003468 << SrcType << DestType << Sel << false;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003469 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3470 return false;
3471 }
3472 }
3473
3474 // Check for an existing instance method with the given selector name.
3475 if (!CfToNs && IMId) {
3476 Selector Sel = Context.Selectors.getNullarySelector(IMId);
3477 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3478 if (!InstanceMethod) {
3479 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003480 << SrcType << DestType << Sel << true;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003481 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3482 return false;
3483 }
3484 }
3485 return true;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003486}
3487
3488bool
3489Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003490 QualType DestType, QualType SrcType,
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003491 Expr *&SrcExpr) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003492 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3493 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3494 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3495 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3496 if (!CfToNs && !NsToCf)
3497 return false;
3498
3499 ObjCInterfaceDecl *RelatedClass;
3500 ObjCMethodDecl *ClassMethod = 0;
3501 ObjCMethodDecl *InstanceMethod = 0;
3502 TypedefNameDecl *TDNDecl = 0;
3503 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
3504 ClassMethod, InstanceMethod, TDNDecl, CfToNs))
3505 return false;
3506
3507 if (CfToNs) {
3508 // Implicit conversion from CF to ObjC object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003509 if (ClassMethod) {
3510 std::string ExpressionString = "[";
3511 ExpressionString += RelatedClass->getNameAsString();
3512 ExpressionString += " ";
3513 ExpressionString += ClassMethod->getSelector().getAsString();
3514 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3515 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003516 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003517 << SrcType << DestType << ClassMethod->getSelector() << false
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003518 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3519 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003520 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3521 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3522
3523 QualType receiverType =
3524 Context.getObjCInterfaceType(RelatedClass);
3525 // Argument.
3526 Expr *args[] = { SrcExpr };
3527 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
3528 ClassMethod->getLocation(),
3529 ClassMethod->getSelector(), ClassMethod,
3530 MultiExprArg(args, 1));
3531 SrcExpr = msg.take();
3532 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003533 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003534 }
3535 else {
3536 // Implicit conversion from ObjC type to CF object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003537 if (InstanceMethod) {
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003538 std::string ExpressionString;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003539 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003540 if (InstanceMethod->isPropertyAccessor())
3541 if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
3542 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
3543 ExpressionString = ".";
3544 ExpressionString += PDecl->getNameAsString();
3545 Diag(Loc, diag::err_objc_bridged_related_known_method)
3546 << SrcType << DestType << InstanceMethod->getSelector() << true
3547 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3548 }
3549 if (ExpressionString.empty()) {
3550 // Provide a fixit: [ObjectExpr InstanceMethod]
3551 ExpressionString = " ";
3552 ExpressionString += InstanceMethod->getSelector().getAsString();
3553 ExpressionString += "]";
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003554
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003555 Diag(Loc, diag::err_objc_bridged_related_known_method)
3556 << SrcType << DestType << InstanceMethod->getSelector() << true
3557 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3558 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3559 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003560 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3561 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3562
3563 ExprResult msg =
3564 BuildInstanceMessageImplicit(SrcExpr, SrcType,
3565 InstanceMethod->getLocation(),
3566 InstanceMethod->getSelector(),
3567 InstanceMethod, None);
3568 SrcExpr = msg.take();
3569 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003570 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003571 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003572 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003573}
3574
John McCall4124c492011-10-17 18:40:02 +00003575Sema::ARCConversionResult
3576Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003577 Expr *&castExpr, CheckedConversionKind CCK,
3578 bool DiagnoseCFAudited) {
John McCall4124c492011-10-17 18:40:02 +00003579 QualType castExprType = castExpr->getType();
3580
3581 // For the purposes of the classification, we assume reference types
3582 // will bind to temporaries.
3583 QualType effCastType = castType;
3584 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3585 effCastType = ref->getPointeeType();
3586
3587 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3588 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003589 if (exprACTC == castACTC) {
3590 // check for viablity and report error if casting an rvalue to a
3591 // life-time qualifier.
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003592 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003593 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003594 (castType != castExprType)) {
3595 const Type *DT = castType.getTypePtr();
3596 QualType QDT = castType;
3597 // We desugar some types but not others. We ignore those
3598 // that cannot happen in a cast; i.e. auto, and those which
3599 // should not be de-sugared; i.e typedef.
3600 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3601 QDT = PT->desugar();
3602 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3603 QDT = TP->desugar();
3604 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3605 QDT = AT->desugar();
3606 if (QDT != castType &&
3607 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3608 SourceLocation loc =
3609 (castRange.isValid() ? castRange.getBegin()
3610 : castExpr->getExprLoc());
3611 Diag(loc, diag::err_arc_nolifetime_behavior);
3612 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003613 }
3614 return ACR_okay;
3615 }
3616
John McCall4124c492011-10-17 18:40:02 +00003617 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
3618
3619 // Allow all of these types to be cast to integer types (but not
3620 // vice-versa).
3621 if (castACTC == ACTC_none && castType->isIntegralType(Context))
3622 return ACR_okay;
3623
3624 // Allow casts between pointers to lifetime types (e.g., __strong id*)
3625 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
3626 // must be explicit.
3627 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
3628 return ACR_okay;
3629 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
3630 CCK != CCK_ImplicitConversion)
3631 return ACR_okay;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003632
3633 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation &&
3634 (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast))
Fariborz Jahanian953d18a2014-04-22 17:42:01 +00003635 if (CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, false) ||
3636 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr, false))
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003637 return ACR_okay;
3638
3639 if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3640 (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast))
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003641 if (CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr) ||
3642 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr))
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003643 return ACR_okay;
3644
John McCall4124c492011-10-17 18:40:02 +00003645
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003646 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00003647 // For invalid casts, fall through.
3648 case ACC_invalid:
3649 break;
3650
3651 // Do nothing for both bottom and +0.
3652 case ACC_bottom:
3653 case ACC_plusZero:
3654 return ACR_okay;
3655
3656 // If the result is +1, consume it here.
3657 case ACC_plusOne:
3658 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3659 CK_ARCConsumeObject, castExpr,
3660 0, VK_RValue);
3661 ExprNeedsCleanups = true;
3662 return ACR_okay;
3663 }
3664
3665 // If this is a non-implicit cast from id or block type to a
3666 // CoreFoundation type, delay complaining in case the cast is used
3667 // in an acceptable context.
3668 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3669 CCK != CCK_ImplicitConversion)
3670 return ACR_unbridged;
3671
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003672 // Do not issue bridge cast" diagnostic when implicit casting a cstring
3673 // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
3674 // suitable fix-it.
Fariborz Jahanian283bf892013-12-18 21:04:43 +00003675 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
3676 ConversionToObjCStringLiteralCheck(castType, castExpr))
3677 return ACR_okay;
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003678
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003679 // Do not issue "bridge cast" diagnostic when implicit casting
3680 // a retainable object to a CF type parameter belonging to an audited
3681 // CF API function. Let caller issue a normal type mismatched diagnostic
3682 // instead.
3683 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
3684 castACTC != ACTC_coreFoundation)
3685 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3686 castExpr, castExpr, exprACTC, CCK);
John McCall4124c492011-10-17 18:40:02 +00003687 return ACR_okay;
3688}
3689
3690/// Given that we saw an expression with the ARCUnbridgedCastTy
3691/// placeholder type, complain bitterly.
3692void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3693 // We expect the spurious ImplicitCastExpr to already have been stripped.
3694 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3695 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3696
3697 SourceRange castRange;
3698 QualType castType;
3699 CheckedConversionKind CCK;
3700
3701 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3702 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3703 castType = cast->getTypeAsWritten();
3704 CCK = CCK_CStyleCast;
3705 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3706 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3707 castType = cast->getTypeAsWritten();
3708 CCK = CCK_OtherCast;
3709 } else {
3710 castType = cast->getType();
3711 CCK = CCK_ImplicitConversion;
3712 }
3713
3714 ARCConversionTypeClass castACTC =
3715 classifyTypeForARCConversion(castType.getNonReferenceType());
3716
3717 Expr *castExpr = realCast->getSubExpr();
3718 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3719
3720 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003721 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00003722}
3723
3724/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3725/// type, remove the placeholder cast.
3726Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3727 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3728
3729 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3730 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3731 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3732 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3733 assert(uo->getOpcode() == UO_Extension);
3734 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3735 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3736 sub->getValueKind(), sub->getObjectKind(),
3737 uo->getOperatorLoc());
3738 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3739 assert(!gse->isResultDependent());
3740
3741 unsigned n = gse->getNumAssocs();
3742 SmallVector<Expr*, 4> subExprs(n);
3743 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3744 for (unsigned i = 0; i != n; ++i) {
3745 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3746 Expr *sub = gse->getAssocExpr(i);
3747 if (i == gse->getResultIndex())
3748 sub = stripARCUnbridgedCast(sub);
3749 subExprs[i] = sub;
3750 }
3751
3752 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3753 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003754 subTypes, subExprs,
3755 gse->getDefaultLoc(),
John McCall4124c492011-10-17 18:40:02 +00003756 gse->getRParenLoc(),
3757 gse->containsUnexpandedParameterPack(),
3758 gse->getResultIndex());
3759 } else {
3760 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3761 return cast<ImplicitCastExpr>(e)->getSubExpr();
3762 }
3763}
3764
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003765bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3766 QualType exprType) {
3767 QualType canCastType =
3768 Context.getCanonicalType(castType).getUnqualifiedType();
3769 QualType canExprType =
3770 Context.getCanonicalType(exprType).getUnqualifiedType();
3771 if (isa<ObjCObjectPointerType>(canCastType) &&
3772 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3773 canExprType->isObjCObjectPointerType()) {
3774 if (const ObjCObjectPointerType *ObjT =
3775 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00003776 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
3777 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003778 }
3779 return true;
3780}
3781
John McCall4db5c3c2011-07-07 06:58:02 +00003782/// Look for an ObjCReclaimReturnedObject cast and destroy it.
3783static Expr *maybeUndoReclaimObject(Expr *e) {
3784 // For now, we just undo operands that are *immediately* reclaim
3785 // expressions, which prevents the vast majority of potential
3786 // problems here. To catch them all, we'd need to rebuild arbitrary
3787 // value-propagating subexpressions --- we can't reliably rebuild
3788 // in-place because of expression sharing.
3789 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall2d637d22011-09-10 06:18:15 +00003790 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall4db5c3c2011-07-07 06:58:02 +00003791 return ice->getSubExpr();
3792
3793 return e;
3794}
3795
John McCall31168b02011-06-15 23:02:42 +00003796ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3797 ObjCBridgeCastKind Kind,
3798 SourceLocation BridgeKeywordLoc,
3799 TypeSourceInfo *TSInfo,
3800 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00003801 ExprResult SubResult = UsualUnaryConversions(SubExpr);
3802 if (SubResult.isInvalid()) return ExprError();
3803 SubExpr = SubResult.take();
3804
John McCall31168b02011-06-15 23:02:42 +00003805 QualType T = TSInfo->getType();
3806 QualType FromType = SubExpr->getType();
3807
John McCall9320b872011-09-09 05:25:32 +00003808 CastKind CK;
3809
John McCall31168b02011-06-15 23:02:42 +00003810 bool MustConsume = false;
3811 if (T->isDependentType() || SubExpr->isTypeDependent()) {
3812 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00003813 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00003814 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3815 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00003816 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3817 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00003818 switch (Kind) {
3819 case OBC_Bridge:
3820 break;
3821
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003822 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003823 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00003824 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3825 << 2
3826 << FromType
3827 << (T->isBlockPointerType()? 1 : 0)
3828 << T
3829 << SubExpr->getSourceRange()
3830 << Kind;
3831 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3832 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3833 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003834 << FromType << br
John McCall31168b02011-06-15 23:02:42 +00003835 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003836 br ? "CFBridgingRelease "
3837 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00003838
3839 Kind = OBC_Bridge;
3840 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003841 }
John McCall31168b02011-06-15 23:02:42 +00003842
3843 case OBC_BridgeTransfer:
3844 // We must consume the Objective-C object produced by the cast.
3845 MustConsume = true;
3846 break;
3847 }
3848 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3849 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00003850 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00003851 switch (Kind) {
3852 case OBC_Bridge:
John McCall4db5c3c2011-07-07 06:58:02 +00003853 // Reclaiming a value that's going to be __bridge-casted to CF
3854 // is very dangerous, so we don't do it.
3855 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCall31168b02011-06-15 23:02:42 +00003856 break;
3857
3858 case OBC_BridgeRetained:
3859 // Produce the object before casting it.
3860 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00003861 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00003862 SubExpr, 0, VK_RValue);
3863 break;
3864
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003865 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003866 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00003867 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3868 << (FromType->isBlockPointerType()? 1 : 0)
3869 << FromType
3870 << 2
3871 << T
3872 << SubExpr->getSourceRange()
3873 << Kind;
3874
3875 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3876 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3877 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003878 << T << br
3879 << FixItHint::CreateReplacement(BridgeKeywordLoc,
3880 br ? "CFBridgingRetain " : "__bridge_retained");
John McCall31168b02011-06-15 23:02:42 +00003881
3882 Kind = OBC_Bridge;
3883 break;
3884 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003885 }
John McCall31168b02011-06-15 23:02:42 +00003886 } else {
3887 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3888 << FromType << T << Kind
3889 << SubExpr->getSourceRange()
3890 << TSInfo->getTypeLoc().getSourceRange();
3891 return ExprError();
3892 }
3893
John McCall9320b872011-09-09 05:25:32 +00003894 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00003895 BridgeKeywordLoc,
3896 TSInfo, SubExpr);
3897
3898 if (MustConsume) {
3899 ExprNeedsCleanups = true;
John McCall2d637d22011-09-10 06:18:15 +00003900 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
John McCall31168b02011-06-15 23:02:42 +00003901 0, VK_RValue);
3902 }
3903
3904 return Result;
3905}
3906
3907ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
3908 SourceLocation LParenLoc,
3909 ObjCBridgeCastKind Kind,
3910 SourceLocation BridgeKeywordLoc,
3911 ParsedType Type,
3912 SourceLocation RParenLoc,
3913 Expr *SubExpr) {
3914 TypeSourceInfo *TSInfo = 0;
3915 QualType T = GetTypeFromParser(Type, &TSInfo);
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003916 if (Kind == OBC_Bridge)
3917 CheckTollFreeBridgeCast(T, SubExpr);
John McCall31168b02011-06-15 23:02:42 +00003918 if (!TSInfo)
3919 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3920 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
3921 SubExpr);
3922}