blob: 8ca446a2f32aff7113ca1cd1df113d725cfd6556 [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) {
1006 unsigned DIAG = diag::warning_multiple_selectors;
1007 if (S.Diags.getDiagnosticLevel(DIAG, SourceLocation())
1008 == 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;
1481 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1482 E = OPT->qual_end(); I != E; ++I) {
1483 ObjCProtocolDecl *PROTO = (*I);
1484 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1485 return MD;
1486 }
1487 }
1488 return 0;
1489}
1490
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001491static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1492 if (!Receiver)
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001493 return;
1494
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001495 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver))
1496 Receiver = OVE->getSourceExpr();
1497
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001498 Expr *RExpr = Receiver->IgnoreParenImpCasts();
1499 SourceLocation Loc = RExpr->getLocStart();
1500 QualType T = RExpr->getType();
Jordan Rose2bd991a2012-10-10 16:42:54 +00001501 const ObjCPropertyDecl *PDecl = 0;
1502 const ObjCMethodDecl *GDecl = 0;
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001503 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1504 RExpr = POE->getSyntacticForm();
1505 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1506 if (PRE->isImplicitProperty()) {
1507 GDecl = PRE->getImplicitPropertyGetter();
1508 if (GDecl) {
Alp Toker314cc812014-01-25 16:55:45 +00001509 T = GDecl->getReturnType();
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001510 }
1511 }
1512 else {
1513 PDecl = PRE->getExplicitProperty();
1514 if (PDecl) {
1515 T = PDecl->getType();
1516 }
1517 }
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001518 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001519 }
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001520 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) {
1521 // See if receiver is a method which envokes a synthesized getter
1522 // backing a 'weak' property.
1523 ObjCMethodDecl *Method = ME->getMethodDecl();
Jordan Rose2bd991a2012-10-10 16:42:54 +00001524 if (Method && Method->getSelector().getNumArgs() == 0) {
1525 PDecl = Method->findPropertyDecl();
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001526 if (PDecl)
1527 T = PDecl->getType();
1528 }
1529 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001530
Jordan Rose13d6b712012-09-28 22:21:42 +00001531 if (T.getObjCLifetime() != Qualifiers::OCL_Weak) {
1532 if (!PDecl)
1533 return;
1534 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak))
1535 return;
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001536 }
Jordan Rose13d6b712012-09-28 22:21:42 +00001537
1538 S.Diag(Loc, diag::warn_receiver_is_weak)
1539 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1540
1541 if (PDecl)
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001542 S.Diag(PDecl->getLocation(), diag::note_property_declare);
Jordan Rose13d6b712012-09-28 22:21:42 +00001543 else if (GDecl)
1544 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
1545
1546 S.Diag(Loc, diag::note_arc_assign_to_strong);
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001547}
1548
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001549/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1550/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001551ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001552HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001553 Expr *BaseExpr, SourceLocation OpLoc,
1554 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001555 SourceLocation MemberLoc,
1556 SourceLocation SuperLoc, QualType SuperType,
1557 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001558 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1559 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001560
Benjamin Kramer365082d2012-05-19 16:34:46 +00001561 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001562 Diag(MemberLoc, diag::err_invalid_property_name)
1563 << MemberName << QualType(OPT, 0);
1564 return ExprError();
1565 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001566
1567 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregord6459312011-04-20 18:19:55 +00001568
Douglas Gregor4123a862011-11-14 22:10:01 +00001569 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1570 : BaseExpr->getSourceRange();
1571 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001572 diag::err_property_not_found_forward_class,
1573 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001574 return ExprError();
Douglas Gregor4123a862011-11-14 22:10:01 +00001575
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001576 // Search for a declared property first.
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001577 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001578 // Check whether we can reference this property.
1579 if (DiagnoseUseOfDecl(PD, MemberLoc))
1580 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001581 if (Super)
John McCall526ab472011-10-25 17:37:35 +00001582 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001583 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001584 MemberLoc,
1585 SuperLoc, SuperType));
1586 else
John McCall526ab472011-10-25 17:37:35 +00001587 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001588 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001589 MemberLoc, BaseExpr));
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001590 }
1591 // Check protocols on qualified interfaces.
1592 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1593 E = OPT->qual_end(); I != E; ++I)
1594 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
1595 // Check whether we can reference this property.
1596 if (DiagnoseUseOfDecl(PD, MemberLoc))
1597 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001598
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001599 if (Super)
John McCall526ab472011-10-25 17:37:35 +00001600 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1601 Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001602 VK_LValue,
1603 OK_ObjCProperty,
1604 MemberLoc,
1605 SuperLoc, SuperType));
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001606 else
John McCall526ab472011-10-25 17:37:35 +00001607 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1608 Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001609 VK_LValue,
1610 OK_ObjCProperty,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001611 MemberLoc,
1612 BaseExpr));
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001613 }
1614 // If that failed, look for an "implicit" property by seeing if the nullary
1615 // selector is implemented.
1616
1617 // FIXME: The logic for looking up nullary and unary selectors should be
1618 // shared with the code in ActOnInstanceMessage.
1619
1620 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1621 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001622
1623 // May be founf in property's qualified list.
1624 if (!Getter)
1625 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001626
1627 // If this reference is in an @implementation, check for 'private' methods.
1628 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001629 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001630
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001631 if (Getter) {
1632 // Check if we can reference this property.
1633 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1634 return ExprError();
1635 }
1636 // If we found a getter then this may be a valid dot-reference, we
1637 // will look for the matching setter, in case it is needed.
1638 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001639 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1640 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001641 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001642
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001643 // May be founf in property's qualified list.
1644 if (!Setter)
1645 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1646
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001647 if (!Setter) {
1648 // If this reference is in an @implementation, also check for 'private'
1649 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001650 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001651 }
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001652
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001653 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1654 return ExprError();
1655
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001656 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001657 if (Super)
John McCallb7bd14f2010-12-02 01:19:52 +00001658 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001659 Context.PseudoObjectTy,
1660 VK_LValue, OK_ObjCProperty,
John McCallb7bd14f2010-12-02 01:19:52 +00001661 MemberLoc,
1662 SuperLoc, SuperType));
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001663 else
John McCallb7bd14f2010-12-02 01:19:52 +00001664 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001665 Context.PseudoObjectTy,
1666 VK_LValue, OK_ObjCProperty,
John McCallb7bd14f2010-12-02 01:19:52 +00001667 MemberLoc, BaseExpr));
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001668
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001669 }
1670
1671 // Attempt to correct for typos in property names.
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001672 DeclFilterCCC<ObjCPropertyDecl> Validator;
1673 if (TypoCorrection Corrected = CorrectTypo(
Richard Smithf9b15102013-08-17 00:46:16 +00001674 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
1675 NULL, Validator, IFace, false, OPT)) {
1676 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1677 << MemberName << QualType(OPT, 0));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001678 DeclarationName TypoResult = Corrected.getCorrection();
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001679 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1680 TypoResult, MemberLoc,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001681 SuperLoc, SuperType, Super);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001682 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001683 ObjCInterfaceDecl *ClassDeclared;
1684 if (ObjCIvarDecl *Ivar =
1685 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1686 QualType T = Ivar->getType();
1687 if (const ObjCObjectPointerType * OBJPT =
1688 T->getAsObjCInterfacePointerType()) {
Douglas Gregor4123a862011-11-14 22:10:01 +00001689 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001690 diag::err_property_not_as_forward_class,
1691 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001692 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001693 }
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001694 Diag(MemberLoc,
1695 diag::err_ivar_access_using_property_syntax_suggest)
1696 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1697 << FixItHint::CreateReplacement(OpLoc, "->");
1698 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001699 }
Chris Lattner90c58fa2010-04-11 07:51:10 +00001700
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001701 Diag(MemberLoc, diag::err_property_not_found)
1702 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001703 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001704 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001705 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001706 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001707}
1708
1709
1710
John McCalldadc5752010-08-24 06:29:42 +00001711ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001712ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1713 IdentifierInfo &propertyName,
1714 SourceLocation receiverNameLoc,
1715 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001716
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001717 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001718 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1719 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001720
1721 bool IsSuper = false;
Chris Lattnera36ec422010-04-11 08:28:14 +00001722 if (IFace == 0) {
1723 // If the "receiver" is 'super' in a method, handle it as an expression-like
1724 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001725 if (receiverNamePtr->isStr("super")) {
Douglas Gregor33823722011-06-11 01:09:30 +00001726 IsSuper = true;
1727
Eli Friedman24af8502012-02-03 22:47:37 +00001728 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001729 if (CurMethod->isInstanceMethod()) {
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00001730 ObjCInterfaceDecl *Super =
1731 CurMethod->getClassInterface()->getSuperClass();
1732 if (!Super) {
1733 // The current class does not have a superclass.
1734 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1735 << CurMethod->getClassInterface()->getIdentifier();
1736 return ExprError();
1737 }
1738 QualType T = Context.getObjCInterfaceType(Super);
Chris Lattnera36ec422010-04-11 08:28:14 +00001739 T = Context.getObjCObjectPointerType(T);
Chris Lattnera36ec422010-04-11 08:28:14 +00001740
1741 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001742 /*BaseExpr*/0,
1743 SourceLocation()/*OpLoc*/,
1744 &propertyName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001745 propertyNameLoc,
1746 receiverNameLoc, T, true);
Chris Lattnera36ec422010-04-11 08:28:14 +00001747 }
Mike Stump11289f42009-09-09 15:08:12 +00001748
Chris Lattnera36ec422010-04-11 08:28:14 +00001749 // Otherwise, if this is a class method, try dispatching to our
1750 // superclass.
1751 IFace = CurMethod->getClassInterface()->getSuperClass();
1752 }
John McCall5f2d5562011-02-03 09:00:02 +00001753 }
Chris Lattnera36ec422010-04-11 08:28:14 +00001754
1755 if (IFace == 0) {
Alp Tokerec543272013-12-24 09:48:30 +00001756 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1757 << tok::l_paren;
Chris Lattnera36ec422010-04-11 08:28:14 +00001758 return ExprError();
1759 }
1760 }
1761
1762 // Search for a declared property first.
Steve Naroff9527bbf2009-03-09 21:12:44 +00001763 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001764 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001765
1766 // If this reference is in an @implementation, check for 'private' methods.
1767 if (!Getter)
1768 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1769 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00001770 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001771 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001772
1773 if (Getter) {
1774 // FIXME: refactor/share with ActOnMemberReference().
1775 // Check if we can reference this property.
1776 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1777 return ExprError();
1778 }
Mike Stump11289f42009-09-09 15:08:12 +00001779
Steve Naroff9527bbf2009-03-09 21:12:44 +00001780 // Look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00001781 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001782 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1783 PP.getSelectorTable(),
1784 &propertyName);
Mike Stump11289f42009-09-09 15:08:12 +00001785
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001786 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001787 if (!Setter) {
1788 // If this reference is in an @implementation, also check for 'private'
1789 // methods.
1790 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1791 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00001792 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001793 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001794 }
1795 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00001796 if (!Setter)
1797 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001798
1799 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1800 return ExprError();
1801
1802 if (Getter || Setter) {
Douglas Gregor33823722011-06-11 01:09:30 +00001803 if (IsSuper)
1804 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001805 Context.PseudoObjectTy,
1806 VK_LValue, OK_ObjCProperty,
Douglas Gregor33823722011-06-11 01:09:30 +00001807 propertyNameLoc,
1808 receiverNameLoc,
1809 Context.getObjCInterfaceType(IFace)));
1810
John McCallb7bd14f2010-12-02 01:19:52 +00001811 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001812 Context.PseudoObjectTy,
1813 VK_LValue, OK_ObjCProperty,
John McCallb7bd14f2010-12-02 01:19:52 +00001814 propertyNameLoc,
1815 receiverNameLoc, IFace));
Steve Naroff9527bbf2009-03-09 21:12:44 +00001816 }
1817 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1818 << &propertyName << Context.getObjCInterfaceType(IFace));
1819}
1820
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001821namespace {
1822
1823class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1824 public:
1825 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1826 // Determine whether "super" is acceptable in the current context.
1827 if (Method && Method->getClassInterface())
1828 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1829 }
1830
Craig Toppere14c0f82014-03-12 04:55:44 +00001831 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001832 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1833 candidate.isKeyword("super");
1834 }
1835};
1836
1837}
1838
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001839Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001840 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001841 SourceLocation NameLoc,
1842 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001843 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00001844 ParsedType &ReceiverType) {
1845 ReceiverType = ParsedType();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001846
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001847 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00001848 // messaging super. If the identifier is "super" and there is a
1849 // trailing dot, it's an instance message.
1850 if (IsSuper && S->isInObjcMethodScope())
1851 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001852
1853 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1854 LookupName(Result, S);
1855
1856 switch (Result.getResultKind()) {
1857 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00001858 // Normal name lookup didn't find anything. If we're in an
1859 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00001860 // FIXME: This is a hack. Ivar lookup should be part of normal
1861 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00001862 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00001863 if (!Method->getClassInterface()) {
1864 // Fall back: let the parser try to parse it as an instance message.
1865 return ObjCInstanceMessage;
1866 }
1867
Douglas Gregorca7136b2010-04-19 20:09:36 +00001868 ObjCInterfaceDecl *ClassDeclared;
1869 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1870 ClassDeclared))
1871 return ObjCInstanceMessage;
1872 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00001873
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001874 // Break out; we'll perform typo correction below.
1875 break;
1876
1877 case LookupResult::NotFoundInCurrentInstantiation:
1878 case LookupResult::FoundOverloaded:
1879 case LookupResult::FoundUnresolvedValue:
1880 case LookupResult::Ambiguous:
1881 Result.suppressDiagnostics();
1882 return ObjCInstanceMessage;
1883
1884 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00001885 // If the identifier is a class or not, and there is a trailing dot,
1886 // it's an instance message.
1887 if (HasTrailingDot)
1888 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001889 // We found something. If it's a type, then we have a class
1890 // message. Otherwise, it's an instance message.
1891 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001892 QualType T;
1893 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1894 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001895 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00001896 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001897 DiagnoseUseOfDecl(Type, NameLoc);
1898 }
1899 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00001900 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001901
Douglas Gregore5798dc2010-04-21 20:38:13 +00001902 // We have a class message, and T is the type we're
1903 // messaging. Build source-location information for it.
1904 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00001905 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00001906 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001907 }
1908 }
1909
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001910 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00001911 if (TypoCorrection Corrected =
1912 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1913 NULL, Validator, NULL, false, NULL, false)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001914 if (Corrected.isKeyword()) {
1915 // If we've found the keyword "super" (the only keyword that would be
1916 // returned by CorrectTypo), this is a send to super.
Richard Smithf9b15102013-08-17 00:46:16 +00001917 diagnoseTypo(Corrected,
1918 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001919 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001920 } else if (ObjCInterfaceDecl *Class =
Richard Smithf9b15102013-08-17 00:46:16 +00001921 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001922 // If we found a declaration, correct when it refers to an Objective-C
1923 // class.
Richard Smithf9b15102013-08-17 00:46:16 +00001924 diagnoseTypo(Corrected,
1925 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001926 QualType T = Context.getObjCInterfaceType(Class);
1927 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1928 ReceiverType = CreateParsedType(T, TSInfo);
1929 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001930 }
1931 }
Richard Smithf9b15102013-08-17 00:46:16 +00001932
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001933 // Fall back: let the parser try to parse it as an instance message.
1934 return ObjCInstanceMessage;
1935}
Steve Naroff9527bbf2009-03-09 21:12:44 +00001936
John McCalldadc5752010-08-24 06:29:42 +00001937ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001938 SourceLocation SuperLoc,
1939 Selector Sel,
1940 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00001941 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001942 SourceLocation RBracLoc,
1943 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001944 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00001945 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00001946 if (!Method) {
1947 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1948 return ExprError();
1949 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001950
Douglas Gregor4fdba132010-04-21 20:01:04 +00001951 ObjCInterfaceDecl *Class = Method->getClassInterface();
1952 if (!Class) {
1953 Diag(SuperLoc, diag::error_no_super_class_message)
1954 << Method->getDeclName();
1955 return ExprError();
1956 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001957
Douglas Gregor4fdba132010-04-21 20:01:04 +00001958 ObjCInterfaceDecl *Super = Class->getSuperClass();
1959 if (!Super) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001960 // The current class does not have a superclass.
Ted Kremenek499897b2011-01-23 17:21:34 +00001961 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1962 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001963 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00001964 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001965
Douglas Gregor4fdba132010-04-21 20:01:04 +00001966 // We are in a method whose class has a superclass, so 'super'
1967 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00001968 if (Method->getSelector() == Sel)
1969 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00001970
Jordan Rose2afd6612012-10-19 16:05:26 +00001971 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00001972 // Since we are in an instance method, this is an instance
1973 // message to the superclass instance.
1974 QualType SuperTy = Context.getObjCInterfaceType(Super);
1975 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCallb268a282010-08-23 23:25:46 +00001976 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001977 Sel, /*Method=*/0,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001978 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001979 }
Douglas Gregor4fdba132010-04-21 20:01:04 +00001980
1981 // Since we are in a class method, this is a class message to
1982 // the superclass.
1983 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1984 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001985 SuperLoc, Sel, /*Method=*/0,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001986 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001987}
1988
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001989
1990ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1991 bool isSuperReceiver,
1992 SourceLocation Loc,
1993 Selector Sel,
1994 ObjCMethodDecl *Method,
1995 MultiExprArg Args) {
1996 TypeSourceInfo *receiverTypeInfo = 0;
1997 if (!ReceiverType.isNull())
1998 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1999
2000 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2001 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2002 Sel, Method, Loc, Loc, Loc, Args,
2003 /*isImplicit=*/true);
2004
2005}
2006
Ted Kremeneke65b0862012-03-06 20:05:56 +00002007static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2008 unsigned DiagID,
2009 bool (*refactor)(const ObjCMessageExpr *,
2010 const NSAPI &, edit::Commit &)) {
2011 SourceLocation MsgLoc = Msg->getExprLoc();
2012 if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
2013 return;
2014
2015 SourceManager &SM = S.SourceMgr;
2016 edit::Commit ECommit(SM, S.LangOpts);
2017 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2018 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2019 << Msg->getSelector() << Msg->getSourceRange();
2020 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2021 if (!ECommit.isCommitable())
2022 return;
2023 for (edit::Commit::edit_iterator
2024 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2025 const edit::Commit::Edit &Edit = *I;
2026 switch (Edit.Kind) {
2027 case edit::Commit::Act_Insert:
2028 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2029 Edit.Text,
2030 Edit.BeforePrev));
2031 break;
2032 case edit::Commit::Act_InsertFromRange:
2033 Builder.AddFixItHint(
2034 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2035 Edit.getInsertFromRange(SM),
2036 Edit.BeforePrev));
2037 break;
2038 case edit::Commit::Act_Remove:
2039 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2040 break;
2041 }
2042 }
2043 }
2044}
2045
2046static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2047 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2048 edit::rewriteObjCRedundantCallWithLiteral);
2049}
2050
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002051/// \brief Build an Objective-C class message expression.
2052///
2053/// This routine takes care of both normal class messages and
2054/// class messages to the superclass.
2055///
2056/// \param ReceiverTypeInfo Type source information that describes the
2057/// receiver of this message. This may be NULL, in which case we are
2058/// sending to the superclass and \p SuperLoc must be a valid source
2059/// location.
2060
2061/// \param ReceiverType The type of the object receiving the
2062/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2063/// type as that refers to. For a superclass send, this is the type of
2064/// the superclass.
2065///
2066/// \param SuperLoc The location of the "super" keyword in a
2067/// superclass message.
2068///
2069/// \param Sel The selector to which the message is being sent.
2070///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002071/// \param Method The method that this class message is invoking, if
2072/// already known.
2073///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002074/// \param LBracLoc The location of the opening square bracket ']'.
2075///
James Dennettffad8b72012-06-22 08:10:18 +00002076/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002077///
James Dennettffad8b72012-06-22 08:10:18 +00002078/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002079ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002080 QualType ReceiverType,
2081 SourceLocation SuperLoc,
2082 Selector Sel,
2083 ObjCMethodDecl *Method,
2084 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002085 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002086 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002087 MultiExprArg ArgsIn,
2088 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002089 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002090 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002091 if (LBracLoc.isInvalid()) {
2092 Diag(Loc, diag::err_missing_open_square_message_send)
2093 << FixItHint::CreateInsertion(Loc, "[");
2094 LBracLoc = Loc;
2095 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002096 SourceLocation SelLoc;
2097 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2098 SelLoc = SelectorLocs.front();
2099 else
2100 SelLoc = Loc;
2101
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002102 if (ReceiverType->isDependentType()) {
2103 // If the receiver type is dependent, we can't type-check anything
2104 // at this point. Build a dependent expression.
2105 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002106 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002107 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCall7decc9e2010-11-18 06:31:45 +00002108 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
2109 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002110 Sel, SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002111 makeArrayRef(Args, NumArgs),RBracLoc,
2112 isImplicit));
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002113 }
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002114
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002115 // Find the class to which we are sending this message.
2116 ObjCInterfaceDecl *Class = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002117 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2118 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002119 Diag(Loc, diag::err_invalid_receiver_class_message)
2120 << ReceiverType;
2121 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002122 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002123 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002124 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002125 if (!getLangOpts().CPlusPlus)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002126 (void)DiagnoseUseOfDecl(Class, SelLoc);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002127 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002128 if (!Method) {
Douglas Gregor4123a862011-11-14 22:10:01 +00002129 SourceRange TypeRange
2130 = SuperLoc.isValid()? SourceRange(SuperLoc)
2131 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002132 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002133 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002134 ? diag::err_arc_receiver_forward_class
2135 : diag::warn_receiver_forward_class),
2136 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002137 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorb5186b12010-04-22 17:01:48 +00002138 Method = LookupFactoryMethodInGlobalPool(Sel,
2139 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002140 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002141 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2142 << Method->getDeclName();
2143 }
2144 if (!Method)
2145 Method = Class->lookupClassMethod(Sel);
2146
2147 // If we have an implementation in scope, check "private" methods.
2148 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002149 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002150
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002151 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002152 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002153 }
Mike Stump11289f42009-09-09 15:08:12 +00002154
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002155 // Check the argument types and determine the result type.
2156 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002157 ExprValueKind VK = VK_RValue;
2158
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002159 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002160 Expr **Args = ArgsIn.data();
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002161 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2162 Sel, SelectorLocs,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00002163 Method, true,
Douglas Gregor33823722011-06-11 01:09:30 +00002164 SuperLoc.isValid(), LBracLoc, RBracLoc,
2165 ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002166 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002167
Alp Toker314cc812014-01-25 16:55:45 +00002168 if (Method && !Method->getReturnType()->isVoidType() &&
2169 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002170 diag::err_illegal_message_expr_incomplete_type))
2171 return ExprError();
2172
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002173 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002174 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002175 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002176 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002177 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002178 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002179 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002180 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002181 else {
John McCall7decc9e2010-11-18 06:31:45 +00002182 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002183 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002184 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002185 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002186 if (!isImplicit)
2187 checkCocoaAPI(*this, Result);
2188 }
Douglas Gregoraae38d62010-05-22 05:17:18 +00002189 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002190}
2191
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002192// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002193// ArgExprs is optional - if it is present, the number of expressions
2194// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002195ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002196 ParsedType Receiver,
2197 Selector Sel,
2198 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002199 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002200 SourceLocation RBracLoc,
2201 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002202 TypeSourceInfo *ReceiverTypeInfo;
2203 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2204 if (ReceiverType.isNull())
2205 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002206
Mike Stump11289f42009-09-09 15:08:12 +00002207
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002208 if (!ReceiverTypeInfo)
2209 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2210
2211 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorb5186b12010-04-22 17:01:48 +00002212 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002213 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002214}
2215
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002216ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2217 QualType ReceiverType,
2218 SourceLocation Loc,
2219 Selector Sel,
2220 ObjCMethodDecl *Method,
2221 MultiExprArg Args) {
2222 return BuildInstanceMessage(Receiver, ReceiverType,
2223 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2224 Sel, Method, Loc, Loc, Loc, Args,
2225 /*isImplicit=*/true);
2226}
2227
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002228/// \brief Build an Objective-C instance message expression.
2229///
2230/// This routine takes care of both normal instance messages and
2231/// instance messages to the superclass instance.
2232///
2233/// \param Receiver The expression that computes the object that will
2234/// receive this message. This may be empty, in which case we are
2235/// sending to the superclass instance and \p SuperLoc must be a valid
2236/// source location.
2237///
2238/// \param ReceiverType The (static) type of the object receiving the
2239/// message. When a \p Receiver expression is provided, this is the
2240/// same type as that expression. For a superclass instance send, this
2241/// is a pointer to the type of the superclass.
2242///
2243/// \param SuperLoc The location of the "super" keyword in a
2244/// superclass instance message.
2245///
2246/// \param Sel The selector to which the message is being sent.
2247///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002248/// \param Method The method that this instance message is invoking, if
2249/// already known.
2250///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002251/// \param LBracLoc The location of the opening square bracket ']'.
2252///
James Dennettffad8b72012-06-22 08:10:18 +00002253/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002254///
James Dennettffad8b72012-06-22 08:10:18 +00002255/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002256ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002257 QualType ReceiverType,
2258 SourceLocation SuperLoc,
2259 Selector Sel,
2260 ObjCMethodDecl *Method,
2261 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002262 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002263 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002264 MultiExprArg ArgsIn,
2265 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002266 // The location of the receiver.
2267 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002268 SourceRange RecRange =
2269 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2270 SourceLocation SelLoc;
2271 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2272 SelLoc = SelectorLocs.front();
2273 else
2274 SelLoc = Loc;
2275
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002276 if (LBracLoc.isInvalid()) {
2277 Diag(Loc, diag::err_missing_open_square_message_send)
2278 << FixItHint::CreateInsertion(Loc, "[");
2279 LBracLoc = Loc;
2280 }
2281
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002282 // If we have a receiver expression, perform appropriate promotions
2283 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002284 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002285 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002286 ExprResult Result;
2287 if (Receiver->getType() == Context.UnknownAnyTy)
2288 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2289 else
2290 Result = CheckPlaceholderExpr(Receiver);
2291 if (Result.isInvalid()) return ExprError();
2292 Receiver = Result.take();
John McCall4124c492011-10-17 18:40:02 +00002293 }
2294
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002295 if (Receiver->isTypeDependent()) {
2296 // If the receiver is type-dependent, we can't type-check anything
2297 // at this point. Build a dependent expression.
2298 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002299 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002300 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2301 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00002302 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002303 SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002304 makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002305 RBracLoc, isImplicit));
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002306 }
2307
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002308 // If necessary, apply function/array conversion to the receiver.
2309 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002310 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2311 if (Result.isInvalid())
2312 return ExprError();
2313 Receiver = Result.take();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002314 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002315
2316 // If the receiver is an ObjC pointer, a block pointer, or an
2317 // __attribute__((NSObject)) pointer, we don't need to do any
2318 // special conversion in order to look up a receiver.
2319 if (ReceiverType->isObjCRetainableType()) {
2320 // do nothing
2321 } else if (!getLangOpts().ObjCAutoRefCount &&
2322 !Context.getObjCIdType().isNull() &&
2323 (ReceiverType->isPointerType() ||
2324 ReceiverType->isIntegerType())) {
2325 // Implicitly convert integers and pointers to 'id' but emit a warning.
2326 // But not in ARC.
2327 Diag(Loc, diag::warn_bad_receiver_type)
2328 << ReceiverType
2329 << Receiver->getSourceRange();
2330 if (ReceiverType->isPointerType()) {
2331 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2332 CK_CPointerToObjCPointerCast).take();
2333 } else {
2334 // TODO: specialized warning on null receivers?
2335 bool IsNull = Receiver->isNullPointerConstant(Context,
2336 Expr::NPC_ValueDependentIsNull);
2337 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2338 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2339 Kind).take();
2340 }
2341 ReceiverType = Receiver->getType();
2342 } else if (getLangOpts().CPlusPlus) {
Douglas Gregor4b60a152013-11-07 22:34:54 +00002343 // The receiver must be a complete type.
2344 if (RequireCompleteType(Loc, Receiver->getType(),
2345 diag::err_incomplete_receiver_type))
2346 return ExprError();
2347
John McCall80c93a02013-03-01 09:20:14 +00002348 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2349 if (result.isUsable()) {
2350 Receiver = result.take();
2351 ReceiverType = Receiver->getType();
2352 }
2353 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002354 }
2355
John McCall80c93a02013-03-01 09:20:14 +00002356 // There's a somewhat weird interaction here where we assume that we
2357 // won't actually have a method unless we also don't need to do some
2358 // of the more detailed type-checking on the receiver.
2359
Douglas Gregorb5186b12010-04-22 17:01:48 +00002360 if (!Method) {
2361 // Handle messages to id.
Fariborz Jahanian32e59ba2010-08-10 18:10:50 +00002362 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002363 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002364 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2365 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002366 SourceRange(LBracLoc, RBracLoc),
2367 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002368 if (!Method)
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002369 Method = LookupFactoryMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002370 SourceRange(LBracLoc,RBracLoc),
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002371 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002372 } else if (ReceiverType->isObjCClassType() ||
2373 ReceiverType->isObjCQualifiedClassType()) {
2374 // Handle messages to Class.
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002375 // We allow sending a message to a qualified Class ("Class<foo>"), which
2376 // is ok as long as one of the protocols implements the selector (if not, warn).
2377 if (const ObjCObjectPointerType *QClassTy
2378 = ReceiverType->getAsObjCQualifiedClassType()) {
2379 // Search protocols for class methods.
2380 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2381 if (!Method) {
2382 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2383 // warn if instance method found for a Class message.
2384 if (Method) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002385 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002386 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002387 Diag(Method->getLocation(), diag::note_method_declared_at)
2388 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002389 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002390 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002391 } else {
2392 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2393 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2394 // First check the public methods in the class interface.
2395 Method = ClassDecl->lookupClassMethod(Sel);
2396
2397 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002398 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002399 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002400 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002401 return ExprError();
2402 }
2403 if (!Method) {
2404 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002405 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002406 Method = LookupFactoryMethodInGlobalPool(Sel,
2407 SourceRange(LBracLoc, RBracLoc),
2408 true);
2409 if (!Method) {
2410 // If no class (factory) method was found, check if an _instance_
2411 // method of the same name exists in the root class only.
2412 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002413 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002414 true);
2415 if (Method)
2416 if (const ObjCInterfaceDecl *ID =
2417 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2418 if (ID->getSuperClass())
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002419 Diag(SelLoc, diag::warn_root_inst_method_not_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002420 << Sel << SourceRange(LBracLoc, RBracLoc);
2421 }
2422 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002423 }
2424 }
2425 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002426 } else {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002427 ObjCInterfaceDecl* ClassDecl = 0;
2428
2429 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2430 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002431 // And as long as message is not deprecated/unavailable (warn if it is).
Douglas Gregorb5186b12010-04-22 17:01:48 +00002432 if (const ObjCObjectPointerType *QIdTy
2433 = ReceiverType->getAsObjCQualifiedIdType()) {
2434 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002435 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2436 if (!Method)
2437 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002438 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002439 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002440 } else if (const ObjCObjectPointerType *OCIType
2441 = ReceiverType->getAsObjCInterfacePointerType()) {
2442 // We allow sending a message to a pointer to an interface (an object).
2443 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002444
Douglas Gregor4123a862011-11-14 22:10:01 +00002445 // Try to complete the type. Under ARC, this is a hard error from which
2446 // we don't try to recover.
2447 const ObjCInterfaceDecl *forwardClass = 0;
2448 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002449 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002450 ? diag::err_arc_receiver_forward_instance
2451 : diag::warn_receiver_forward_instance,
2452 Receiver? Receiver->getSourceRange()
2453 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002454 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002455 return ExprError();
2456
2457 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanianc934de62012-02-03 01:02:44 +00002458 Diag(Receiver ? Receiver->getLocStart()
2459 : SuperLoc, diag::note_receiver_is_id);
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002460 Method = 0;
2461 } else {
2462 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002463 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002464
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002465 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002466 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002467 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2468
Douglas Gregorb5186b12010-04-22 17:01:48 +00002469 if (!Method) {
2470 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002471 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002472
David Blaikiebbafb8a2012-03-11 07:00:24 +00002473 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002474 Diag(SelLoc, diag::err_arc_may_not_respond)
2475 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002476 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002477 return ExprError();
2478 }
2479
Douglas Gregor486b74e2011-09-27 16:10:05 +00002480 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002481 // If we still haven't found a method, look in the global pool. This
2482 // behavior isn't very desirable, however we need it for GCC
2483 // compatibility. FIXME: should we deviate??
2484 if (OCIType->qual_empty()) {
2485 Method = LookupInstanceMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002486 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002487 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002488 Diag(SelLoc, diag::warn_maynot_respond)
2489 << OCIType->getInterfaceDecl()->getIdentifier()
2490 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002491 }
2492 }
2493 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002494 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002495 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002496 } else {
John McCall80c93a02013-03-01 09:20:14 +00002497 // Reject other random receiver types (e.g. structs).
2498 Diag(Loc, diag::err_bad_receiver_type)
2499 << ReceiverType << Receiver->getSourceRange();
2500 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002501 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002502 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002503 }
Mike Stump11289f42009-09-09 15:08:12 +00002504
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002505 if (Method && Method->getMethodFamily() == OMF_init &&
2506 getCurFunction()->ObjCIsDesignatedInit &&
2507 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2508 bool isDesignatedInitChain = false;
2509 if (SuperLoc.isValid()) {
2510 if (const ObjCObjectPointerType *
2511 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2512 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
Argyrios Kyrtzidisd664a342013-12-13 03:48:17 +00002513 // Either we know this is a designated initializer or we
2514 // conservatively assume it because we don't know for sure.
2515 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2516 ID->isDesignatedInitializer(Sel)) {
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002517 isDesignatedInitChain = true;
2518 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
2519 }
2520 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002521 }
2522 }
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002523 if (!isDesignatedInitChain) {
2524 const ObjCMethodDecl *InitMethod = 0;
2525 bool isDesignated =
2526 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2527 assert(isDesignated && InitMethod);
2528 (void)isDesignated;
2529 Diag(SelLoc, SuperLoc.isValid() ?
2530 diag::warn_objc_designated_init_non_designated_init_call :
2531 diag::warn_objc_designated_init_non_super_designated_init_call);
2532 Diag(InitMethod->getLocation(),
2533 diag::note_objc_designated_init_marked_here);
2534 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002535 }
2536
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002537 if (Method && Method->getMethodFamily() == OMF_init &&
2538 getCurFunction()->ObjCIsSecondaryInit &&
2539 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2540 if (SuperLoc.isValid()) {
2541 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2542 } else {
2543 getCurFunction()->ObjCWarnForNoInitDelegation = false;
2544 }
2545 }
2546
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002547 // Check the message arguments.
2548 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002549 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002550 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002551 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00002552 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2553 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002554 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2555 Sel, SelectorLocs, Method,
Douglas Gregor33823722011-06-11 01:09:30 +00002556 ClassMessage, SuperLoc.isValid(),
John McCall7decc9e2010-11-18 06:31:45 +00002557 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002558 return ExprError();
Alp Toker314cc812014-01-25 16:55:45 +00002559
2560 if (Method && !Method->getReturnType()->isVoidType() &&
2561 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002562 diag::err_illegal_message_expr_incomplete_type))
2563 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00002564
John McCall31168b02011-06-15 23:02:42 +00002565 // In ARC, forbid the user from sending messages to
2566 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002567 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002568 ObjCMethodFamily family =
2569 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2570 switch (family) {
2571 case OMF_init:
2572 if (Method)
2573 checkInitMethod(Method, ReceiverType);
2574
2575 case OMF_None:
2576 case OMF_alloc:
2577 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00002578 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002579 case OMF_mutableCopy:
2580 case OMF_new:
2581 case OMF_self:
2582 break;
2583
2584 case OMF_dealloc:
2585 case OMF_retain:
2586 case OMF_release:
2587 case OMF_autorelease:
2588 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002589 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2590 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00002591 break;
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002592
2593 case OMF_performSelector:
2594 if (Method && NumArgs >= 1) {
2595 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2596 Selector ArgSel = SelExp->getSelector();
2597 ObjCMethodDecl *SelMethod =
2598 LookupInstanceMethodInGlobalPool(ArgSel,
2599 SelExp->getSourceRange());
2600 if (!SelMethod)
2601 SelMethod =
2602 LookupFactoryMethodInGlobalPool(ArgSel,
2603 SelExp->getSourceRange());
2604 if (SelMethod) {
2605 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2606 switch (SelFamily) {
2607 case OMF_alloc:
2608 case OMF_copy:
2609 case OMF_mutableCopy:
2610 case OMF_new:
2611 case OMF_self:
2612 case OMF_init:
2613 // Issue error, unless ns_returns_not_retained.
2614 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2615 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002616 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002617 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002618 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2619 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002620 }
2621 break;
2622 default:
2623 // +0 call. OK. unless ns_returns_retained.
2624 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2625 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002626 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002627 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002628 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2629 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002630 }
2631 break;
2632 }
2633 }
2634 } else {
2635 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002636 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002637 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2638 }
2639 }
2640 break;
John McCall31168b02011-06-15 23:02:42 +00002641 }
2642 }
2643
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002644 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00002645 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002646 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002647 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002648 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002649 ReceiverType, 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 else {
John McCall7decc9e2010-11-18 06:31:45 +00002653 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002654 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002655 makeArrayRef(Args, NumArgs), RBracLoc,
2656 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002657 if (!isImplicit)
2658 checkCocoaAPI(*this, Result);
2659 }
John McCall31168b02011-06-15 23:02:42 +00002660
David Blaikiebbafb8a2012-03-11 07:00:24 +00002661 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahaniand155c782012-04-19 23:49:39 +00002662 DiagnoseARCUseOfWeakReceiver(*this, Receiver);
Fariborz Jahanian6bd22262012-04-04 20:05:25 +00002663
John McCall31168b02011-06-15 23:02:42 +00002664 // In ARC, annotate delegate init calls.
2665 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00002666 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00002667 // Only consider init calls *directly* in init implementations,
2668 // not within blocks.
2669 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2670 if (method && method->getMethodFamily() == OMF_init) {
2671 // The implicit assignment to self means we also don't want to
2672 // consume the result.
2673 Result->setDelegateInitCall(true);
2674 return Owned(Result);
2675 }
2676 }
2677
2678 // In ARC, check for message sends which are likely to introduce
2679 // retain cycles.
2680 checkRetainCycles(Result);
Jordan Rose22487652012-10-11 16:06:21 +00002681
2682 if (!isImplicit && Method) {
2683 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2684 bool IsWeak =
2685 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2686 if (!IsWeak && Sel.isUnarySelector())
2687 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
2688
2689 if (IsWeak) {
2690 DiagnosticsEngine::Level Level =
2691 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
2692 LBracLoc);
2693 if (Level != DiagnosticsEngine::Ignored)
2694 getCurFunction()->recordUseOfWeak(Result, Prop);
2695
2696 }
2697 }
2698 }
John McCall31168b02011-06-15 23:02:42 +00002699 }
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00002700
Douglas Gregoraae38d62010-05-22 05:17:18 +00002701 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002702}
2703
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002704static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2705 if (ObjCSelectorExpr *OSE =
2706 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2707 Selector Sel = OSE->getSelector();
2708 SourceLocation Loc = OSE->getAtLoc();
2709 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
2710 = S.ReferencedSelectors.find(Sel);
2711 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
2712 S.ReferencedSelectors.erase(Pos);
2713 }
2714}
2715
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002716// ActOnInstanceMessage - used for both unary and keyword messages.
2717// ArgExprs is optional - if it is present, the number of expressions
2718// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002719ExprResult Sema::ActOnInstanceMessage(Scope *S,
2720 Expr *Receiver,
2721 Selector Sel,
2722 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002723 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00002724 SourceLocation RBracLoc,
2725 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002726 if (!Receiver)
2727 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002728
2729 // A ParenListExpr can show up while doing error recovery with invalid code.
2730 if (isa<ParenListExpr>(Receiver)) {
2731 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
2732 if (Result.isInvalid()) return ExprError();
2733 Receiver = Result.take();
2734 }
Fariborz Jahanian17748062013-01-22 19:05:17 +00002735
2736 if (RespondsToSelectorSel.isNull()) {
2737 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
2738 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
2739 }
2740 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002741 RemoveSelectorFromWarningCache(*this, Args[0]);
2742
John McCallb268a282010-08-23 23:25:46 +00002743 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorb5186b12010-04-22 17:01:48 +00002744 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002745 LBracLoc, SelectorLocs, RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002746}
Chris Lattner2a3569b2008-04-07 05:30:13 +00002747
John McCall31168b02011-06-15 23:02:42 +00002748enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00002749 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00002750 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00002751
2752 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00002753 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00002754
2755 /// id*, id***, void (^*)(),
2756 ACTC_indirectRetainable,
2757
2758 /// void* might be a normal C type, or it might a CF type.
2759 ACTC_voidPtr,
2760
2761 /// struct A*
2762 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00002763};
John McCalle4fe2452011-10-01 01:01:08 +00002764static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2765 return (ACTC == ACTC_retainable ||
2766 ACTC == ACTC_coreFoundation ||
2767 ACTC == ACTC_voidPtr);
2768}
2769static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2770 return ACTC == ACTC_none ||
2771 ACTC == ACTC_voidPtr ||
2772 ACTC == ACTC_coreFoundation;
2773}
2774
John McCall31168b02011-06-15 23:02:42 +00002775static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00002776 bool isIndirect = false;
John McCall31168b02011-06-15 23:02:42 +00002777
2778 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00002779 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00002780 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002781 isIndirect = true;
2782 }
John McCall31168b02011-06-15 23:02:42 +00002783
2784 // Drill through pointers and arrays recursively.
2785 while (true) {
2786 if (const PointerType *ptr = type->getAs<PointerType>()) {
2787 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002788
2789 // The first level of pointer may be the innermost pointer on a CF type.
2790 if (!isIndirect) {
2791 if (type->isVoidType()) return ACTC_voidPtr;
2792 if (type->isRecordType()) return ACTC_coreFoundation;
2793 }
John McCall31168b02011-06-15 23:02:42 +00002794 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2795 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2796 } else {
2797 break;
2798 }
John McCalle4fe2452011-10-01 01:01:08 +00002799 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00002800 }
2801
John McCalle4fe2452011-10-01 01:01:08 +00002802 if (isIndirect) {
2803 if (type->isObjCARCBridgableType())
2804 return ACTC_indirectRetainable;
2805 return ACTC_none;
2806 }
2807
2808 if (type->isObjCARCBridgableType())
2809 return ACTC_retainable;
2810
2811 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00002812}
2813
2814namespace {
John McCalle4fe2452011-10-01 01:01:08 +00002815 /// A result from the cast checker.
2816 enum ACCResult {
2817 /// Cannot be casted.
2818 ACC_invalid,
2819
2820 /// Can be safely retained or not retained.
2821 ACC_bottom,
2822
2823 /// Can be casted at +0.
2824 ACC_plusZero,
2825
2826 /// Can be casted at +1.
2827 ACC_plusOne
2828 };
2829 ACCResult merge(ACCResult left, ACCResult right) {
2830 if (left == right) return left;
2831 if (left == ACC_bottom) return right;
2832 if (right == ACC_bottom) return left;
2833 return ACC_invalid;
2834 }
2835
2836 /// A checker which white-lists certain expressions whose conversion
2837 /// to or from retainable type would otherwise be forbidden in ARC.
2838 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2839 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2840
John McCall31168b02011-06-15 23:02:42 +00002841 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00002842 ARCConversionTypeClass SourceClass;
2843 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002844 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00002845
2846 static bool isCFType(QualType type) {
2847 // Someday this can use ns_bridged. For now, it has to do this.
2848 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00002849 }
John McCalle4fe2452011-10-01 01:01:08 +00002850
2851 public:
2852 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002853 ARCConversionTypeClass target, bool diagnose)
2854 : Context(Context), SourceClass(source), TargetClass(target),
2855 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00002856
2857 using super::Visit;
2858 ACCResult Visit(Expr *e) {
2859 return super::Visit(e->IgnoreParens());
2860 }
2861
2862 ACCResult VisitStmt(Stmt *s) {
2863 return ACC_invalid;
2864 }
2865
2866 /// Null pointer constants can be casted however you please.
2867 ACCResult VisitExpr(Expr *e) {
2868 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2869 return ACC_bottom;
2870 return ACC_invalid;
2871 }
2872
2873 /// Objective-C string literals can be safely casted.
2874 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2875 // If we're casting to any retainable type, go ahead. Global
2876 // strings are immune to retains, so this is bottom.
2877 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2878
2879 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002880 }
2881
John McCalle4fe2452011-10-01 01:01:08 +00002882 /// Look through certain implicit and explicit casts.
2883 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002884 switch (e->getCastKind()) {
2885 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00002886 return ACC_bottom;
2887
John McCall31168b02011-06-15 23:02:42 +00002888 case CK_NoOp:
2889 case CK_LValueToRValue:
2890 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002891 case CK_CPointerToObjCPointerCast:
2892 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002893 case CK_AnyPointerToBlockPointerCast:
2894 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00002895
John McCall31168b02011-06-15 23:02:42 +00002896 default:
John McCalle4fe2452011-10-01 01:01:08 +00002897 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002898 }
2899 }
John McCalle4fe2452011-10-01 01:01:08 +00002900
2901 /// Look through unary extension.
2902 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002903 return Visit(e->getSubExpr());
2904 }
John McCalle4fe2452011-10-01 01:01:08 +00002905
2906 /// Ignore the LHS of a comma operator.
2907 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002908 return Visit(e->getRHS());
2909 }
John McCalle4fe2452011-10-01 01:01:08 +00002910
2911 /// Conditional operators are okay if both sides are okay.
2912 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2913 ACCResult left = Visit(e->getTrueExpr());
2914 if (left == ACC_invalid) return ACC_invalid;
2915 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00002916 }
John McCalle4fe2452011-10-01 01:01:08 +00002917
John McCallfe96e0b2011-11-06 09:01:30 +00002918 /// Look through pseudo-objects.
2919 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2920 // If we're getting here, we should always have a result.
2921 return Visit(e->getResultExpr());
2922 }
2923
John McCalle4fe2452011-10-01 01:01:08 +00002924 /// Statement expressions are okay if their result expression is okay.
2925 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002926 return Visit(e->getSubStmt()->body_back());
2927 }
John McCall31168b02011-06-15 23:02:42 +00002928
John McCalle4fe2452011-10-01 01:01:08 +00002929 /// Some declaration references are okay.
2930 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2931 // References to global constants from system headers are okay.
2932 // These are things like 'kCFStringTransformToLatin'. They are
2933 // can also be assumed to be immune to retains.
2934 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2935 if (isAnyRetainable(TargetClass) &&
2936 isAnyRetainable(SourceClass) &&
2937 var &&
2938 var->getStorageClass() == SC_Extern &&
2939 var->getType().isConstQualified() &&
2940 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2941 return ACC_bottom;
2942 }
2943
2944 // Nothing else.
2945 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00002946 }
John McCalle4fe2452011-10-01 01:01:08 +00002947
2948 /// Some calls are okay.
2949 ACCResult VisitCallExpr(CallExpr *e) {
2950 if (FunctionDecl *fn = e->getDirectCallee())
2951 if (ACCResult result = checkCallToFunction(fn))
2952 return result;
2953
2954 return super::VisitCallExpr(e);
2955 }
2956
2957 ACCResult checkCallToFunction(FunctionDecl *fn) {
2958 // Require a CF*Ref return type.
Alp Toker314cc812014-01-25 16:55:45 +00002959 if (!isCFType(fn->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00002960 return ACC_invalid;
2961
2962 if (!isAnyRetainable(TargetClass))
2963 return ACC_invalid;
2964
2965 // Honor an explicit 'not retained' attribute.
2966 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2967 return ACC_plusZero;
2968
2969 // Honor an explicit 'retained' attribute, except that for
2970 // now we're not going to permit implicit handling of +1 results,
2971 // because it's a bit frightening.
2972 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00002973 return Diagnose ? ACC_plusOne
2974 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00002975
2976 // Recognize this specific builtin function, which is used by CFSTR.
2977 unsigned builtinID = fn->getBuiltinID();
2978 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2979 return ACC_bottom;
2980
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00002981 // Otherwise, don't do anything implicit with an unaudited function.
2982 if (!fn->hasAttr<CFAuditedTransferAttr>())
2983 return ACC_invalid;
2984
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002985 // Otherwise, it's +0 unless it follows the create convention.
2986 if (ento::coreFoundation::followsCreateRule(fn))
2987 return Diagnose ? ACC_plusOne
2988 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00002989
John McCalle4fe2452011-10-01 01:01:08 +00002990 return ACC_plusZero;
2991 }
2992
2993 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
2994 return checkCallToMethod(e->getMethodDecl());
2995 }
2996
2997 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
2998 ObjCMethodDecl *method;
2999 if (e->isExplicitProperty())
3000 method = e->getExplicitProperty()->getGetterMethodDecl();
3001 else
3002 method = e->getImplicitPropertyGetter();
3003 return checkCallToMethod(method);
3004 }
3005
3006 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3007 if (!method) return ACC_invalid;
3008
3009 // Check for message sends to functions returning CF types. We
3010 // just obey the Cocoa conventions with these, even though the
3011 // return type is CF.
Alp Toker314cc812014-01-25 16:55:45 +00003012 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003013 return ACC_invalid;
3014
3015 // If the method is explicitly marked not-retained, it's +0.
3016 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3017 return ACC_plusZero;
3018
3019 // If the method is explicitly marked as returning retained, or its
3020 // selector follows a +1 Cocoa convention, treat it as +1.
3021 if (method->hasAttr<CFReturnsRetainedAttr>())
3022 return ACC_plusOne;
3023
3024 switch (method->getSelector().getMethodFamily()) {
3025 case OMF_alloc:
3026 case OMF_copy:
3027 case OMF_mutableCopy:
3028 case OMF_new:
3029 return ACC_plusOne;
3030
3031 default:
3032 // Otherwise, treat it as +0.
3033 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00003034 }
3035 }
John McCalle4fe2452011-10-01 01:01:08 +00003036 };
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00003037}
3038
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003039bool Sema::isKnownName(StringRef name) {
3040 if (name.empty())
3041 return false;
3042 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003043 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003044 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003045}
3046
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003047static void addFixitForObjCARCConversion(Sema &S,
3048 DiagnosticBuilder &DiagB,
3049 Sema::CheckedConversionKind CCK,
3050 SourceLocation afterLParen,
3051 QualType castType,
3052 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003053 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003054 const char *bridgeKeyword,
3055 const char *CFBridgeName) {
3056 // We handle C-style and implicit casts here.
3057 switch (CCK) {
3058 case Sema::CCK_ImplicitConversion:
3059 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003060 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003061 break;
3062 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003063 return;
3064 }
3065
3066 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003067 if (CCK == Sema::CCK_OtherCast) {
3068 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3069 SourceRange range(NCE->getOperatorLoc(),
3070 NCE->getAngleBrackets().getEnd());
3071 SmallString<32> BridgeCall;
3072
3073 SourceManager &SM = S.getSourceManager();
3074 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3075 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3076 BridgeCall += ' ';
3077
3078 BridgeCall += CFBridgeName;
3079 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3080 }
3081 return;
3082 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003083 Expr *castedE = castExpr;
3084 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3085 castedE = CCE->getSubExpr();
3086 castedE = castedE->IgnoreImpCasts();
3087 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00003088
3089 SmallString<32> BridgeCall;
3090
3091 SourceManager &SM = S.getSourceManager();
3092 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3093 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3094 BridgeCall += ' ';
3095
3096 BridgeCall += CFBridgeName;
3097
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003098 if (isa<ParenExpr>(castedE)) {
3099 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003100 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003101 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00003102 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003103 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003104 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003105 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3106 S.PP.getLocForEndOfToken(range.getEnd()),
3107 ")"));
3108 }
3109 return;
3110 }
3111
3112 if (CCK == Sema::CCK_CStyleCast) {
3113 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003114 } else if (CCK == Sema::CCK_OtherCast) {
3115 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3116 std::string castCode = "(";
3117 castCode += bridgeKeyword;
3118 castCode += castType.getAsString();
3119 castCode += ")";
3120 SourceRange Range(NCE->getOperatorLoc(),
3121 NCE->getAngleBrackets().getEnd());
3122 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3123 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003124 } else {
3125 std::string castCode = "(";
3126 castCode += bridgeKeyword;
3127 castCode += castType.getAsString();
3128 castCode += ")";
3129 Expr *castedE = castExpr->IgnoreImpCasts();
3130 SourceRange range = castedE->getSourceRange();
3131 if (isa<ParenExpr>(castedE)) {
3132 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3133 castCode));
3134 } else {
3135 castCode += "(";
3136 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3137 castCode));
3138 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3139 S.PP.getLocForEndOfToken(range.getEnd()),
3140 ")"));
3141 }
3142 }
3143}
3144
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003145template <typename T>
3146static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3147 TypedefNameDecl *TDNDecl = TD->getDecl();
3148 QualType QT = TDNDecl->getUnderlyingType();
3149 if (QT->isPointerType()) {
3150 QT = QT->getPointeeType();
3151 if (const RecordType *RT = QT->getAs<RecordType>())
3152 if (RecordDecl *RD = RT->getDecl())
Aaron Ballman2084f8f2013-12-19 13:20:36 +00003153 return RD->getAttr<T>();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003154 }
3155 return 0;
3156}
3157
3158static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3159 TypedefNameDecl *&TDNDecl) {
3160 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3161 TDNDecl = TD->getDecl();
3162 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3163 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3164 return ObjCBAttr;
3165 T = TDNDecl->getUnderlyingType();
3166 }
3167 return 0;
3168}
3169
John McCall4124c492011-10-17 18:40:02 +00003170static void
3171diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3172 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003173 Expr *castExpr, Expr *realCast,
3174 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003175 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003176 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003177 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00003178
John McCall4124c492011-10-17 18:40:02 +00003179 if (S.makeUnavailableInSystemHeader(loc,
John McCalle4fe2452011-10-01 01:01:08 +00003180 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCall31168b02011-06-15 23:02:42 +00003181 return;
John McCall4124c492011-10-17 18:40:02 +00003182
3183 QualType castExprType = castExpr->getType();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003184 TypedefNameDecl *TDNDecl = 0;
3185 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3186 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3187 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
3188 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
3189 return;
John McCall31168b02011-06-15 23:02:42 +00003190
John McCall640767f2011-06-17 06:50:50 +00003191 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003192 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003193 case ACTC_none:
3194 case ACTC_coreFoundation:
3195 case ACTC_voidPtr:
3196 srcKind = (castExprType->isPointerType() ? 1 : 0);
3197 break;
3198 case ACTC_retainable:
3199 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3200 break;
3201 case ACTC_indirectRetainable:
3202 srcKind = 4;
3203 break;
John McCall31168b02011-06-15 23:02:42 +00003204 }
3205
John McCall4124c492011-10-17 18:40:02 +00003206 // Check whether this could be fixed with a bridge cast.
3207 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3208 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003209
John McCall4124c492011-10-17 18:40:02 +00003210 // Bridge from an ARC type to a CF type.
3211 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003212
John McCall4124c492011-10-17 18:40:02 +00003213 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3214 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3215 << 2 // of C pointer type
3216 << castExprType
3217 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3218 << castType
3219 << castRange
3220 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003221 bool br = S.isKnownName("CFBridgingRelease");
Jordan Rose4502b532012-07-31 01:07:43 +00003222 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003223 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003224 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003225 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003226 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003227 DiagnosticBuilder DiagB =
3228 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3229 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3230
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003231 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003232 castType, castExpr, realCast, "__bridge ", 0);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003233 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003234 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003235 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003236 DiagnosticBuilder DiagB =
3237 (CCK == Sema::CCK_OtherCast && !br) ?
3238 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3239 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3240 diag::note_arc_bridge_transfer)
3241 << castExprType << br;
3242
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003243 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003244 castType, castExpr, realCast, "__bridge_transfer ",
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003245 br ? "CFBridgingRelease" : 0);
3246 }
John McCall4124c492011-10-17 18:40:02 +00003247
3248 return;
3249 }
3250
3251 // Bridge from a CF type to an ARC type.
3252 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003253 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003254 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3255 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3256 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3257 << castExprType
3258 << 2 // to C pointer type
3259 << castType
3260 << castRange
3261 << castExpr->getSourceRange();
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003262 ACCResult CreateRule =
3263 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003264 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003265 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003266 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003267 DiagnosticBuilder DiagB =
3268 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3269 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003270 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003271 castType, castExpr, realCast, "__bridge ", 0);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003272 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003273 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003274 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003275 DiagnosticBuilder DiagB =
3276 (CCK == Sema::CCK_OtherCast && !br) ?
3277 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3278 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3279 diag::note_arc_bridge_retained)
3280 << castType << br;
3281
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003282 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003283 castType, castExpr, realCast, "__bridge_retained ",
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003284 br ? "CFBridgingRetain" : 0);
3285 }
John McCall4124c492011-10-17 18:40:02 +00003286
3287 return;
John McCall31168b02011-06-15 23:02:42 +00003288 }
3289
John McCall4124c492011-10-17 18:40:02 +00003290 S.Diag(loc, diag::err_arc_mismatched_cast)
3291 << (CCK != Sema::CCK_ImplicitConversion)
3292 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003293 << castRange << castExpr->getSourceRange();
3294}
3295
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003296template <typename TB>
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003297static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr) {
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003298 QualType T = castExpr->getType();
3299 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3300 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003301 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003302 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3303 NamedDecl *Target = 0;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003304 // Check for an existing type with this name.
3305 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3306 Sema::LookupOrdinaryName);
3307 if (S.LookupName(R, S.TUScope)) {
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003308 Target = R.getFoundDecl();
3309 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3310 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3311 if (const ObjCObjectPointerType *InterfacePointerType =
3312 castType->getAsObjCInterfacePointerType()) {
3313 ObjCInterfaceDecl *CastClass
3314 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003315 if ((CastClass == ExprClass) ||
3316 (CastClass && ExprClass->isSuperClassOf(CastClass)))
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003317 return true;
3318 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
Fariborz Jahanian509f31e2013-11-19 01:23:07 +00003319 << T << Target->getName() << castType->getPointeeType();
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003320 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003321 } else if (castType->isObjCIdType() ||
3322 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3323 castType, ExprClass)))
3324 // ok to cast to 'id'.
3325 // casting to id<p-list> is ok if bridge type adopts all of
3326 // p-list protocols.
3327 return true;
3328 else {
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003329 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
Fariborz Jahanian509f31e2013-11-19 01:23:07 +00003330 << T << Target->getName() << castType;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003331 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3332 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003333 return true;
3334 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003335 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003336 }
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003337 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
Aaron Ballmanc0550742014-01-03 02:07:43 +00003338 << castExpr->getType() << Parm;
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003339 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3340 if (Target)
3341 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003342 }
3343 return true;
3344 }
3345 T = TDNDecl->getUnderlyingType();
3346 }
3347 return false;
3348}
3349
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003350template <typename TB>
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003351static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr) {
3352 QualType T = castType;
3353 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3354 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003355 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003356 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3357 NamedDecl *Target = 0;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003358 // Check for an existing type with this name.
3359 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3360 Sema::LookupOrdinaryName);
3361 if (S.LookupName(R, S.TUScope)) {
3362 Target = R.getFoundDecl();
3363 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3364 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3365 if (const ObjCObjectPointerType *InterfacePointerType =
3366 castExpr->getType()->getAsObjCInterfacePointerType()) {
3367 ObjCInterfaceDecl *ExprClass
3368 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003369 if ((CastClass == ExprClass) ||
3370 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003371 return true;
3372 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
Fariborz Jahanian509f31e2013-11-19 01:23:07 +00003373 << castExpr->getType()->getPointeeType() << T;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003374 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3375 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003376 } else if (castExpr->getType()->isObjCIdType() ||
3377 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3378 castExpr->getType(), CastClass)))
3379 // ok to cast an 'id' expression to a CFtype.
3380 // ok to cast an 'id<plist>' expression to CFtype provided plist
3381 // adopts all of CFtype's ObjetiveC's class plist.
3382 return true;
3383 else {
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003384 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3385 << castExpr->getType() << castType;
3386 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003387 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003388 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003389 }
3390 }
3391 }
3392 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3393 << castExpr->getType() << castType;
3394 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3395 if (Target)
3396 S.Diag(Target->getLocStart(), diag::note_declared_at);
3397 }
3398 return true;
3399 }
3400 T = TDNDecl->getUnderlyingType();
3401 }
3402 return false;
3403}
3404
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003405void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003406 // warn in presence of __bridge casting to or from a toll free bridge cast.
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003407 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3408 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003409 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
3410 (void)CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr);
3411 (void)CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr);
3412 }
3413 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
3414 (void)CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr);
3415 (void)CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr);
3416 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003417}
3418
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003419
3420bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3421 QualType DestType, QualType SrcType,
3422 ObjCInterfaceDecl *&RelatedClass,
3423 ObjCMethodDecl *&ClassMethod,
3424 ObjCMethodDecl *&InstanceMethod,
3425 TypedefNameDecl *&TDNDecl,
3426 bool CfToNs) {
3427 QualType T = CfToNs ? SrcType : DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003428 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3429 if (!ObjCBAttr)
3430 return false;
3431
3432 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3433 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3434 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3435 if (!RCId)
3436 return false;
3437 NamedDecl *Target = 0;
3438 // Check for an existing type with this name.
3439 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3440 Sema::LookupOrdinaryName);
3441 if (!LookupName(R, TUScope)) {
3442 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003443 << SrcType << DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003444 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3445 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003446 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003447 Target = R.getFoundDecl();
3448 if (Target && isa<ObjCInterfaceDecl>(Target))
3449 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3450 else {
3451 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3452 << SrcType << DestType;
3453 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3454 if (Target)
3455 Diag(Target->getLocStart(), diag::note_declared_at);
3456 return false;
3457 }
3458
3459 // Check for an existing class method with the given selector name.
3460 if (CfToNs && CMId) {
3461 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3462 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3463 if (!ClassMethod) {
3464 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003465 << SrcType << DestType << Sel << false;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003466 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3467 return false;
3468 }
3469 }
3470
3471 // Check for an existing instance method with the given selector name.
3472 if (!CfToNs && IMId) {
3473 Selector Sel = Context.Selectors.getNullarySelector(IMId);
3474 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3475 if (!InstanceMethod) {
3476 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003477 << SrcType << DestType << Sel << true;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003478 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3479 return false;
3480 }
3481 }
3482 return true;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003483}
3484
3485bool
3486Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003487 QualType DestType, QualType SrcType,
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003488 Expr *&SrcExpr) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003489 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3490 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3491 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3492 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3493 if (!CfToNs && !NsToCf)
3494 return false;
3495
3496 ObjCInterfaceDecl *RelatedClass;
3497 ObjCMethodDecl *ClassMethod = 0;
3498 ObjCMethodDecl *InstanceMethod = 0;
3499 TypedefNameDecl *TDNDecl = 0;
3500 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
3501 ClassMethod, InstanceMethod, TDNDecl, CfToNs))
3502 return false;
3503
3504 if (CfToNs) {
3505 // Implicit conversion from CF to ObjC object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003506 if (ClassMethod) {
3507 std::string ExpressionString = "[";
3508 ExpressionString += RelatedClass->getNameAsString();
3509 ExpressionString += " ";
3510 ExpressionString += ClassMethod->getSelector().getAsString();
3511 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3512 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003513 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003514 << SrcType << DestType << ClassMethod->getSelector() << false
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003515 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3516 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003517 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3518 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3519
3520 QualType receiverType =
3521 Context.getObjCInterfaceType(RelatedClass);
3522 // Argument.
3523 Expr *args[] = { SrcExpr };
3524 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
3525 ClassMethod->getLocation(),
3526 ClassMethod->getSelector(), ClassMethod,
3527 MultiExprArg(args, 1));
3528 SrcExpr = msg.take();
3529 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003530 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003531 }
3532 else {
3533 // Implicit conversion from ObjC type to CF object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003534 if (InstanceMethod) {
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003535 std::string ExpressionString;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003536 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003537 if (InstanceMethod->isPropertyAccessor())
3538 if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
3539 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
3540 ExpressionString = ".";
3541 ExpressionString += PDecl->getNameAsString();
3542 Diag(Loc, diag::err_objc_bridged_related_known_method)
3543 << SrcType << DestType << InstanceMethod->getSelector() << true
3544 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3545 }
3546 if (ExpressionString.empty()) {
3547 // Provide a fixit: [ObjectExpr InstanceMethod]
3548 ExpressionString = " ";
3549 ExpressionString += InstanceMethod->getSelector().getAsString();
3550 ExpressionString += "]";
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003551
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003552 Diag(Loc, diag::err_objc_bridged_related_known_method)
3553 << SrcType << DestType << InstanceMethod->getSelector() << true
3554 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3555 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3556 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003557 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3558 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3559
3560 ExprResult msg =
3561 BuildInstanceMessageImplicit(SrcExpr, SrcType,
3562 InstanceMethod->getLocation(),
3563 InstanceMethod->getSelector(),
3564 InstanceMethod, None);
3565 SrcExpr = msg.take();
3566 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003567 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003568 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003569 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003570}
3571
John McCall4124c492011-10-17 18:40:02 +00003572Sema::ARCConversionResult
3573Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003574 Expr *&castExpr, CheckedConversionKind CCK,
3575 bool DiagnoseCFAudited) {
John McCall4124c492011-10-17 18:40:02 +00003576 QualType castExprType = castExpr->getType();
3577
3578 // For the purposes of the classification, we assume reference types
3579 // will bind to temporaries.
3580 QualType effCastType = castType;
3581 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3582 effCastType = ref->getPointeeType();
3583
3584 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3585 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003586 if (exprACTC == castACTC) {
3587 // check for viablity and report error if casting an rvalue to a
3588 // life-time qualifier.
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003589 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003590 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003591 (castType != castExprType)) {
3592 const Type *DT = castType.getTypePtr();
3593 QualType QDT = castType;
3594 // We desugar some types but not others. We ignore those
3595 // that cannot happen in a cast; i.e. auto, and those which
3596 // should not be de-sugared; i.e typedef.
3597 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3598 QDT = PT->desugar();
3599 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3600 QDT = TP->desugar();
3601 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3602 QDT = AT->desugar();
3603 if (QDT != castType &&
3604 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3605 SourceLocation loc =
3606 (castRange.isValid() ? castRange.getBegin()
3607 : castExpr->getExprLoc());
3608 Diag(loc, diag::err_arc_nolifetime_behavior);
3609 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003610 }
3611 return ACR_okay;
3612 }
3613
John McCall4124c492011-10-17 18:40:02 +00003614 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
3615
3616 // Allow all of these types to be cast to integer types (but not
3617 // vice-versa).
3618 if (castACTC == ACTC_none && castType->isIntegralType(Context))
3619 return ACR_okay;
3620
3621 // Allow casts between pointers to lifetime types (e.g., __strong id*)
3622 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
3623 // must be explicit.
3624 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
3625 return ACR_okay;
3626 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
3627 CCK != CCK_ImplicitConversion)
3628 return ACR_okay;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003629
3630 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation &&
3631 (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast))
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003632 if (CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr) ||
3633 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr))
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003634 return ACR_okay;
3635
3636 if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3637 (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast))
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003638 if (CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr) ||
3639 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr))
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003640 return ACR_okay;
3641
John McCall4124c492011-10-17 18:40:02 +00003642
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003643 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00003644 // For invalid casts, fall through.
3645 case ACC_invalid:
3646 break;
3647
3648 // Do nothing for both bottom and +0.
3649 case ACC_bottom:
3650 case ACC_plusZero:
3651 return ACR_okay;
3652
3653 // If the result is +1, consume it here.
3654 case ACC_plusOne:
3655 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3656 CK_ARCConsumeObject, castExpr,
3657 0, VK_RValue);
3658 ExprNeedsCleanups = true;
3659 return ACR_okay;
3660 }
3661
3662 // If this is a non-implicit cast from id or block type to a
3663 // CoreFoundation type, delay complaining in case the cast is used
3664 // in an acceptable context.
3665 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3666 CCK != CCK_ImplicitConversion)
3667 return ACR_unbridged;
3668
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003669 // Do not issue bridge cast" diagnostic when implicit casting a cstring
3670 // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
3671 // suitable fix-it.
Fariborz Jahanian283bf892013-12-18 21:04:43 +00003672 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
3673 ConversionToObjCStringLiteralCheck(castType, castExpr))
3674 return ACR_okay;
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003675
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003676 // Do not issue "bridge cast" diagnostic when implicit casting
3677 // a retainable object to a CF type parameter belonging to an audited
3678 // CF API function. Let caller issue a normal type mismatched diagnostic
3679 // instead.
3680 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
3681 castACTC != ACTC_coreFoundation)
3682 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3683 castExpr, castExpr, exprACTC, CCK);
John McCall4124c492011-10-17 18:40:02 +00003684 return ACR_okay;
3685}
3686
3687/// Given that we saw an expression with the ARCUnbridgedCastTy
3688/// placeholder type, complain bitterly.
3689void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3690 // We expect the spurious ImplicitCastExpr to already have been stripped.
3691 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3692 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3693
3694 SourceRange castRange;
3695 QualType castType;
3696 CheckedConversionKind CCK;
3697
3698 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3699 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3700 castType = cast->getTypeAsWritten();
3701 CCK = CCK_CStyleCast;
3702 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3703 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3704 castType = cast->getTypeAsWritten();
3705 CCK = CCK_OtherCast;
3706 } else {
3707 castType = cast->getType();
3708 CCK = CCK_ImplicitConversion;
3709 }
3710
3711 ARCConversionTypeClass castACTC =
3712 classifyTypeForARCConversion(castType.getNonReferenceType());
3713
3714 Expr *castExpr = realCast->getSubExpr();
3715 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3716
3717 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003718 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00003719}
3720
3721/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3722/// type, remove the placeholder cast.
3723Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3724 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3725
3726 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3727 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3728 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3729 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3730 assert(uo->getOpcode() == UO_Extension);
3731 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3732 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3733 sub->getValueKind(), sub->getObjectKind(),
3734 uo->getOperatorLoc());
3735 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3736 assert(!gse->isResultDependent());
3737
3738 unsigned n = gse->getNumAssocs();
3739 SmallVector<Expr*, 4> subExprs(n);
3740 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3741 for (unsigned i = 0; i != n; ++i) {
3742 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3743 Expr *sub = gse->getAssocExpr(i);
3744 if (i == gse->getResultIndex())
3745 sub = stripARCUnbridgedCast(sub);
3746 subExprs[i] = sub;
3747 }
3748
3749 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3750 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003751 subTypes, subExprs,
3752 gse->getDefaultLoc(),
John McCall4124c492011-10-17 18:40:02 +00003753 gse->getRParenLoc(),
3754 gse->containsUnexpandedParameterPack(),
3755 gse->getResultIndex());
3756 } else {
3757 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3758 return cast<ImplicitCastExpr>(e)->getSubExpr();
3759 }
3760}
3761
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003762bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3763 QualType exprType) {
3764 QualType canCastType =
3765 Context.getCanonicalType(castType).getUnqualifiedType();
3766 QualType canExprType =
3767 Context.getCanonicalType(exprType).getUnqualifiedType();
3768 if (isa<ObjCObjectPointerType>(canCastType) &&
3769 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3770 canExprType->isObjCObjectPointerType()) {
3771 if (const ObjCObjectPointerType *ObjT =
3772 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00003773 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
3774 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003775 }
3776 return true;
3777}
3778
John McCall4db5c3c2011-07-07 06:58:02 +00003779/// Look for an ObjCReclaimReturnedObject cast and destroy it.
3780static Expr *maybeUndoReclaimObject(Expr *e) {
3781 // For now, we just undo operands that are *immediately* reclaim
3782 // expressions, which prevents the vast majority of potential
3783 // problems here. To catch them all, we'd need to rebuild arbitrary
3784 // value-propagating subexpressions --- we can't reliably rebuild
3785 // in-place because of expression sharing.
3786 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall2d637d22011-09-10 06:18:15 +00003787 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall4db5c3c2011-07-07 06:58:02 +00003788 return ice->getSubExpr();
3789
3790 return e;
3791}
3792
John McCall31168b02011-06-15 23:02:42 +00003793ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3794 ObjCBridgeCastKind Kind,
3795 SourceLocation BridgeKeywordLoc,
3796 TypeSourceInfo *TSInfo,
3797 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00003798 ExprResult SubResult = UsualUnaryConversions(SubExpr);
3799 if (SubResult.isInvalid()) return ExprError();
3800 SubExpr = SubResult.take();
3801
John McCall31168b02011-06-15 23:02:42 +00003802 QualType T = TSInfo->getType();
3803 QualType FromType = SubExpr->getType();
3804
John McCall9320b872011-09-09 05:25:32 +00003805 CastKind CK;
3806
John McCall31168b02011-06-15 23:02:42 +00003807 bool MustConsume = false;
3808 if (T->isDependentType() || SubExpr->isTypeDependent()) {
3809 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00003810 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00003811 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3812 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00003813 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3814 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00003815 switch (Kind) {
3816 case OBC_Bridge:
3817 break;
3818
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003819 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003820 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00003821 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3822 << 2
3823 << FromType
3824 << (T->isBlockPointerType()? 1 : 0)
3825 << T
3826 << SubExpr->getSourceRange()
3827 << Kind;
3828 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3829 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3830 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003831 << FromType << br
John McCall31168b02011-06-15 23:02:42 +00003832 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003833 br ? "CFBridgingRelease "
3834 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00003835
3836 Kind = OBC_Bridge;
3837 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003838 }
John McCall31168b02011-06-15 23:02:42 +00003839
3840 case OBC_BridgeTransfer:
3841 // We must consume the Objective-C object produced by the cast.
3842 MustConsume = true;
3843 break;
3844 }
3845 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3846 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00003847 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00003848 switch (Kind) {
3849 case OBC_Bridge:
John McCall4db5c3c2011-07-07 06:58:02 +00003850 // Reclaiming a value that's going to be __bridge-casted to CF
3851 // is very dangerous, so we don't do it.
3852 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCall31168b02011-06-15 23:02:42 +00003853 break;
3854
3855 case OBC_BridgeRetained:
3856 // Produce the object before casting it.
3857 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00003858 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00003859 SubExpr, 0, VK_RValue);
3860 break;
3861
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003862 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003863 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00003864 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3865 << (FromType->isBlockPointerType()? 1 : 0)
3866 << FromType
3867 << 2
3868 << T
3869 << SubExpr->getSourceRange()
3870 << Kind;
3871
3872 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3873 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3874 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003875 << T << br
3876 << FixItHint::CreateReplacement(BridgeKeywordLoc,
3877 br ? "CFBridgingRetain " : "__bridge_retained");
John McCall31168b02011-06-15 23:02:42 +00003878
3879 Kind = OBC_Bridge;
3880 break;
3881 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003882 }
John McCall31168b02011-06-15 23:02:42 +00003883 } else {
3884 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3885 << FromType << T << Kind
3886 << SubExpr->getSourceRange()
3887 << TSInfo->getTypeLoc().getSourceRange();
3888 return ExprError();
3889 }
3890
John McCall9320b872011-09-09 05:25:32 +00003891 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00003892 BridgeKeywordLoc,
3893 TSInfo, SubExpr);
3894
3895 if (MustConsume) {
3896 ExprNeedsCleanups = true;
John McCall2d637d22011-09-10 06:18:15 +00003897 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
John McCall31168b02011-06-15 23:02:42 +00003898 0, VK_RValue);
3899 }
3900
3901 return Result;
3902}
3903
3904ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
3905 SourceLocation LParenLoc,
3906 ObjCBridgeCastKind Kind,
3907 SourceLocation BridgeKeywordLoc,
3908 ParsedType Type,
3909 SourceLocation RParenLoc,
3910 Expr *SubExpr) {
3911 TypeSourceInfo *TSInfo = 0;
3912 QualType T = GetTypeFromParser(Type, &TSInfo);
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003913 if (Kind == OBC_Bridge)
3914 CheckTollFreeBridgeCast(T, SubExpr);
John McCall31168b02011-06-15 23:02:42 +00003915 if (!TSInfo)
3916 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3917 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
3918 SubExpr);
3919}