blob: 7d7d3ecc3dec127877fc32f4c67c86402c75c8d8 [file] [log] [blame]
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for Objective-C expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnera3fc41d2008-01-04 22:32:30 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
Steve Naroff021ca182008-05-29 21:12:08 +000017#include "clang/AST/ExprObjC.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor0c78ad92010-04-21 19:57:20 +000019#include "clang/AST/TypeLoc.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
21#include "clang/Edit/Commit.h"
22#include "clang/Edit/Rewriters.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000023#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/Initialization.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/Scope.h"
27#include "clang/Sema/ScopeInfo.h"
28#include "llvm/ADT/SmallString.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000029
Chris Lattnera3fc41d2008-01-04 22:32:30 +000030using namespace clang;
John McCall5f2d5562011-02-03 09:00:02 +000031using namespace sema;
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +000032using llvm::makeArrayRef;
Chris Lattnera3fc41d2008-01-04 22:32:30 +000033
John McCallfaf5fb42010-08-26 23:41:50 +000034ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
35 Expr **strings,
36 unsigned NumStrings) {
Chris Lattner163ffd22009-02-18 06:48:40 +000037 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
38
Chris Lattnerd7670d92009-02-18 06:13:04 +000039 // Most ObjC strings are formed out of a single piece. However, we *can*
40 // have strings formed out of multiple @ strings with multiple pptokens in
41 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
42 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner163ffd22009-02-18 06:48:40 +000043 StringLiteral *S = Strings[0];
Mike Stump11289f42009-09-09 15:08:12 +000044
Chris Lattnerd7670d92009-02-18 06:13:04 +000045 // If we have a multi-part string, merge it all together.
46 if (NumStrings != 1) {
Chris Lattnera3fc41d2008-01-04 22:32:30 +000047 // Concatenate objc strings.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000048 SmallString<128> StrBuf;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000049 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump11289f42009-09-09 15:08:12 +000050
Chris Lattner630970d2009-02-18 05:49:11 +000051 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner163ffd22009-02-18 06:48:40 +000052 S = Strings[i];
Mike Stump11289f42009-09-09 15:08:12 +000053
Douglas Gregorfb65e592011-07-27 05:40:30 +000054 // ObjC strings can't be wide or UTF.
55 if (!S->isAscii()) {
Chris Lattnerd7670d92009-02-18 06:13:04 +000056 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
57 << S->getSourceRange();
58 return true;
59 }
Mike Stump11289f42009-09-09 15:08:12 +000060
Benjamin Kramer35b077e2010-08-17 12:54:38 +000061 // Append the string.
62 StrBuf += S->getString();
Mike Stump11289f42009-09-09 15:08:12 +000063
Chris Lattner163ffd22009-02-18 06:48:40 +000064 // Get the locations of the string tokens.
65 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000066 }
Mike Stump11289f42009-09-09 15:08:12 +000067
Chris Lattner163ffd22009-02-18 06:48:40 +000068 // Create the aggregate string with the appropriate content and location
69 // information.
Benjamin Kramercdac7612014-02-25 12:26:20 +000070 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
71 assert(CAT && "String literal not of constant array type!");
72 QualType StrTy = Context.getConstantArrayType(
73 CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1),
74 CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
75 S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
76 /*Pascal=*/false, StrTy, &StrLocs[0],
77 StrLocs.size());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000078 }
Ted Kremeneke65b0862012-03-06 20:05:56 +000079
80 return BuildObjCStringLiteral(AtLocs[0], S);
81}
Mike Stump11289f42009-09-09 15:08:12 +000082
Ted Kremeneke65b0862012-03-06 20:05:56 +000083ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
Chris Lattner6436fb62009-02-18 06:01:06 +000084 // Verify that this composite string is acceptable for ObjC strings.
85 if (CheckObjCString(S))
Chris Lattnera3fc41d2008-01-04 22:32:30 +000086 return true;
Chris Lattnerfffd6a72009-02-18 06:06:56 +000087
88 // Initialize the constant string interface lazily. This assumes
Steve Naroff54e59452009-04-07 14:18:33 +000089 // the NSString interface is seen in this translation unit. Note: We
90 // don't use NSConstantString, since the runtime team considers this
91 // interface private (even though it appears in the header files).
Chris Lattnerfffd6a72009-02-18 06:06:56 +000092 QualType Ty = Context.getObjCConstantStringInterface();
93 if (!Ty.isNull()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +000094 Ty = Context.getObjCObjectPointerType(Ty);
David Blaikiebbafb8a2012-03-11 07:00:24 +000095 } else if (getLangOpts().NoConstantCFStrings) {
Craig Topperc3ec1492014-05-26 06:22:03 +000096 IdentifierInfo *NSIdent=nullptr;
David Blaikiebbafb8a2012-03-11 07:00:24 +000097 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +000098
99 if (StringClass.empty())
100 NSIdent = &Context.Idents.get("NSConstantString");
101 else
102 NSIdent = &Context.Idents.get(StringClass);
103
Ted Kremeneke65b0862012-03-06 20:05:56 +0000104 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Fariborz Jahanian07317632010-04-23 23:19:04 +0000105 LookupOrdinaryName);
106 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
107 Context.setObjCConstantStringInterface(StrIF);
108 Ty = Context.getObjCConstantStringInterface();
109 Ty = Context.getObjCObjectPointerType(Ty);
110 } else {
111 // If there is no NSConstantString interface defined then treat this
112 // as error and recover from it.
113 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
114 << S->getSourceRange();
115 Ty = Context.getObjCIdType();
116 }
Chris Lattner091f6982008-06-21 21:44:18 +0000117 } else {
Patrick Beard0caa3942012-04-19 00:25:12 +0000118 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000119 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000120 LookupOrdinaryName);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000121 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
122 Context.setObjCConstantStringInterface(StrIF);
123 Ty = Context.getObjCConstantStringInterface();
Steve Naroff7cae42b2009-07-10 23:34:53 +0000124 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000125 } else {
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000126 // If there is no NSString interface defined, implicitly declare
127 // a @class NSString; and use that instead. This is to make sure
128 // type of an NSString literal is represented correctly, instead of
129 // being an 'id' type.
130 Ty = Context.getObjCNSStringType();
131 if (Ty.isNull()) {
132 ObjCInterfaceDecl *NSStringIDecl =
133 ObjCInterfaceDecl::Create (Context,
134 Context.getTranslationUnitDecl(),
135 SourceLocation(), NSIdent,
Craig Topperc3ec1492014-05-26 06:22:03 +0000136 nullptr, SourceLocation());
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000137 Ty = Context.getObjCInterfaceType(NSStringIDecl);
138 Context.setObjCNSStringType(Ty);
139 }
140 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000141 }
Chris Lattner091f6982008-06-21 21:44:18 +0000142 }
Mike Stump11289f42009-09-09 15:08:12 +0000143
Ted Kremeneke65b0862012-03-06 20:05:56 +0000144 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
145}
146
Jordy Rose08e500c2012-05-12 17:32:44 +0000147/// \brief Emits an error if the given method does not exist, or if the return
148/// type is not an Objective-C object.
149static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
150 const ObjCInterfaceDecl *Class,
151 Selector Sel, const ObjCMethodDecl *Method) {
152 if (!Method) {
153 // FIXME: Is there a better way to avoid quotes than using getName()?
154 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
155 return false;
156 }
157
158 // Make sure the return type is reasonable.
Alp Toker314cc812014-01-25 16:55:45 +0000159 QualType ReturnType = Method->getReturnType();
Jordy Rose08e500c2012-05-12 17:32:44 +0000160 if (!ReturnType->isObjCObjectPointerType()) {
161 S.Diag(Loc, diag::err_objc_literal_method_sig)
162 << Sel;
163 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
164 << ReturnType;
165 return false;
166 }
167
168 return true;
169}
170
Ted Kremeneke65b0862012-03-06 20:05:56 +0000171/// \brief Retrieve the NSNumber factory method that should be used to create
172/// an Objective-C literal for the given type.
173static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
Patrick Beard0caa3942012-04-19 00:25:12 +0000174 QualType NumberType,
175 bool isLiteral = false,
176 SourceRange R = SourceRange()) {
David Blaikie05785d12013-02-20 22:23:23 +0000177 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
178 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
179
Ted Kremeneke65b0862012-03-06 20:05:56 +0000180 if (!Kind) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000181 if (isLiteral) {
182 S.Diag(Loc, diag::err_invalid_nsnumber_type)
183 << NumberType << R;
184 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000185 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000186 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000187
Ted Kremeneke65b0862012-03-06 20:05:56 +0000188 // If we already looked up this method, we're done.
189 if (S.NSNumberLiteralMethods[*Kind])
190 return S.NSNumberLiteralMethods[*Kind];
191
192 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
193 /*Instance=*/false);
194
Patrick Beard0caa3942012-04-19 00:25:12 +0000195 ASTContext &CX = S.Context;
196
197 // Look up the NSNumber class, if we haven't done so already. It's cached
198 // in the Sema instance.
199 if (!S.NSNumberDecl) {
Jordy Roseaca01f92012-05-12 17:32:52 +0000200 IdentifierInfo *NSNumberId =
201 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber);
Patrick Beard0caa3942012-04-19 00:25:12 +0000202 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId,
203 Loc, Sema::LookupOrdinaryName);
204 S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
205 if (!S.NSNumberDecl) {
206 if (S.getLangOpts().DebuggerObjCLiteral) {
207 // Create a stub definition of NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000208 S.NSNumberDecl = ObjCInterfaceDecl::Create(CX,
209 CX.getTranslationUnitDecl(),
210 SourceLocation(), NSNumberId,
Craig Topperc3ec1492014-05-26 06:22:03 +0000211 nullptr, SourceLocation());
Patrick Beard0caa3942012-04-19 00:25:12 +0000212 } else {
213 // Otherwise, require a declaration of NSNumber.
214 S.Diag(Loc, diag::err_undeclared_nsnumber);
Craig Topperc3ec1492014-05-26 06:22:03 +0000215 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000216 }
217 } else if (!S.NSNumberDecl->hasDefinition()) {
218 S.Diag(Loc, diag::err_undeclared_nsnumber);
Craig Topperc3ec1492014-05-26 06:22:03 +0000219 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000220 }
Alex Denisove36748a2015-02-16 16:17:05 +0000221 }
222
223 if (S.NSNumberPointer.isNull()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000224 // generate the pointer to NSNumber type.
Jordy Roseaca01f92012-05-12 17:32:52 +0000225 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
226 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000227 }
228
Ted Kremeneke65b0862012-03-06 20:05:56 +0000229 // Look for the appropriate method within NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000230 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000231 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000232 // create a stub definition this NSNumber factory method.
Craig Topperc3ec1492014-05-26 06:22:03 +0000233 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000234 Method =
235 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
236 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
237 /*isInstance=*/false, /*isVariadic=*/false,
238 /*isPropertyAccessor=*/false,
239 /*isImplicitlyDeclared=*/true,
240 /*isDefined=*/false, ObjCMethodDecl::Required,
241 /*HasRelatedResultType=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000242 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
243 SourceLocation(), SourceLocation(),
Patrick Beard0caa3942012-04-19 00:25:12 +0000244 &CX.Idents.get("value"),
Craig Topperc3ec1492014-05-26 06:22:03 +0000245 NumberType, /*TInfo=*/nullptr,
246 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000247 Method->setMethodParams(S.Context, value, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000248 }
249
Jordy Rose08e500c2012-05-12 17:32:44 +0000250 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
Craig Topperc3ec1492014-05-26 06:22:03 +0000251 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000252
253 // Note: if the parameter type is out-of-line, we'll catch it later in the
254 // implicit conversion.
255
256 S.NSNumberLiteralMethods[*Kind] = Method;
257 return Method;
258}
259
Patrick Beard0caa3942012-04-19 00:25:12 +0000260/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
261/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremeneke65b0862012-03-06 20:05:56 +0000262ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000263 // Determine the type of the literal.
264 QualType NumberType = Number->getType();
265 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
266 // In C, character literals have type 'int'. That's not the type we want
267 // to use to determine the Objective-c literal kind.
268 switch (Char->getKind()) {
269 case CharacterLiteral::Ascii:
270 NumberType = Context.CharTy;
271 break;
272
273 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000274 NumberType = Context.getWideCharType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000275 break;
276
277 case CharacterLiteral::UTF16:
278 NumberType = Context.Char16Ty;
279 break;
280
281 case CharacterLiteral::UTF32:
282 NumberType = Context.Char32Ty;
283 break;
284 }
285 }
286
Ted Kremeneke65b0862012-03-06 20:05:56 +0000287 // Look for the appropriate method within NSNumber.
288 // Construct the literal.
Patrick Beard2565c592012-05-01 21:47:19 +0000289 SourceRange NR(Number->getSourceRange());
Patrick Beard0caa3942012-04-19 00:25:12 +0000290 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
Patrick Beard2565c592012-05-01 21:47:19 +0000291 true, NR);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000292 if (!Method)
293 return ExprError();
294
295 // Convert the number to the type that the parameter expects.
Alp Toker03376dc2014-07-07 09:02:20 +0000296 ParmVarDecl *ParamDecl = Method->parameters()[0];
Patrick Beard2565c592012-05-01 21:47:19 +0000297 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
298 ParamDecl);
299 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
300 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000301 Number);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000302 if (ConvertedNumber.isInvalid())
303 return ExprError();
304 Number = ConvertedNumber.get();
305
Patrick Beard2565c592012-05-01 21:47:19 +0000306 // Use the effective source range of the literal, including the leading '@'.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000307 return MaybeBindToTemporary(
Patrick Beard2565c592012-05-01 21:47:19 +0000308 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
309 SourceRange(AtLoc, NR.getEnd())));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000310}
311
312ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
313 SourceLocation ValueLoc,
314 bool Value) {
315 ExprResult Inner;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000316 if (getLangOpts().CPlusPlus) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000317 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
318 } else {
319 // C doesn't actually have a way to represent literal values of type
320 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
321 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
322 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
323 CK_IntegralToBoolean);
324 }
325
326 return BuildObjCNumericLiteral(AtLoc, Inner.get());
327}
328
329/// \brief Check that the given expression is a valid element of an Objective-C
330/// collection literal.
331static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000332 QualType T,
333 bool ArrayLiteral = false) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000334 // If the expression is type-dependent, there's nothing for us to do.
335 if (Element->isTypeDependent())
336 return Element;
337
338 ExprResult Result = S.CheckPlaceholderExpr(Element);
339 if (Result.isInvalid())
340 return ExprError();
341 Element = Result.get();
342
343 // In C++, check for an implicit conversion to an Objective-C object pointer
344 // type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000345 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000346 InitializedEntity Entity
Jordy Roseaca01f92012-05-12 17:32:52 +0000347 = InitializedEntity::InitializeParameter(S.Context, T,
348 /*Consumed=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000349 InitializationKind Kind
Jordy Roseaca01f92012-05-12 17:32:52 +0000350 = InitializationKind::CreateCopy(Element->getLocStart(),
351 SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000352 InitializationSequence Seq(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000353 if (!Seq.Failed())
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000354 return Seq.Perform(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000355 }
356
357 Expr *OrigElement = Element;
358
359 // Perform lvalue-to-rvalue conversion.
360 Result = S.DefaultLvalueConversion(Element);
361 if (Result.isInvalid())
362 return ExprError();
363 Element = Result.get();
364
365 // Make sure that we have an Objective-C pointer type or block.
366 if (!Element->getType()->isObjCObjectPointerType() &&
367 !Element->getType()->isBlockPointerType()) {
368 bool Recovered = false;
369
370 // If this is potentially an Objective-C numeric literal, add the '@'.
371 if (isa<IntegerLiteral>(OrigElement) ||
372 isa<CharacterLiteral>(OrigElement) ||
373 isa<FloatingLiteral>(OrigElement) ||
374 isa<ObjCBoolLiteralExpr>(OrigElement) ||
375 isa<CXXBoolLiteralExpr>(OrigElement)) {
376 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
377 int Which = isa<CharacterLiteral>(OrigElement) ? 1
378 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
379 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
380 : 3;
381
382 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
383 << Which << OrigElement->getSourceRange()
384 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
385
386 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
387 OrigElement);
388 if (Result.isInvalid())
389 return ExprError();
390
391 Element = Result.get();
392 Recovered = true;
393 }
394 }
395 // If this is potentially an Objective-C string literal, add the '@'.
396 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
397 if (String->isAscii()) {
398 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
399 << 0 << OrigElement->getSourceRange()
400 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
401
402 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
403 if (Result.isInvalid())
404 return ExprError();
405
406 Element = Result.get();
407 Recovered = true;
408 }
409 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000410
Ted Kremeneke65b0862012-03-06 20:05:56 +0000411 if (!Recovered) {
412 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
413 << Element->getType();
414 return ExprError();
415 }
416 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000417 if (ArrayLiteral)
Ted Kremenek197fee42013-10-09 22:34:33 +0000418 if (ObjCStringLiteral *getString =
419 dyn_cast<ObjCStringLiteral>(OrigElement)) {
420 if (StringLiteral *SL = getString->getString()) {
421 unsigned numConcat = SL->getNumConcatenated();
422 if (numConcat > 1) {
423 // Only warn if the concatenated string doesn't come from a macro.
424 bool hasMacro = false;
425 for (unsigned i = 0; i < numConcat ; ++i)
426 if (SL->getStrTokenLoc(i).isMacroID()) {
427 hasMacro = true;
428 break;
429 }
430 if (!hasMacro)
431 S.Diag(Element->getLocStart(),
432 diag::warn_concatenated_nsarray_literal)
433 << Element->getType();
434 }
435 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000436 }
437
Ted Kremeneke65b0862012-03-06 20:05:56 +0000438 // Make sure that the element has the type that the container factory
439 // function expects.
440 return S.PerformCopyInitialization(
441 InitializedEntity::InitializeParameter(S.Context, T,
442 /*Consumed=*/false),
443 Element->getLocStart(), Element);
444}
445
Patrick Beard0caa3942012-04-19 00:25:12 +0000446ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
447 if (ValueExpr->isTypeDependent()) {
448 ObjCBoxedExpr *BoxedExpr =
Craig Topperc3ec1492014-05-26 06:22:03 +0000449 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000450 return BoxedExpr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000451 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000452 ObjCMethodDecl *BoxingMethod = nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000453 QualType BoxedType;
454 // Convert the expression to an RValue, so we can check for pointer types...
455 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
456 if (RValue.isInvalid()) {
457 return ExprError();
458 }
459 ValueExpr = RValue.get();
Patrick Beard2565c592012-05-01 21:47:19 +0000460 QualType ValueType(ValueExpr->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +0000461 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
462 QualType PointeeType = PT->getPointeeType();
463 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
464
465 if (!NSStringDecl) {
466 IdentifierInfo *NSStringId =
467 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
468 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
469 SR.getBegin(), LookupOrdinaryName);
470 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
471 if (!NSStringDecl) {
472 if (getLangOpts().DebuggerObjCLiteral) {
473 // Support boxed expressions in the debugger w/o NSString declaration.
Jordy Roseaca01f92012-05-12 17:32:52 +0000474 DeclContext *TU = Context.getTranslationUnitDecl();
475 NSStringDecl = ObjCInterfaceDecl::Create(Context, TU,
476 SourceLocation(),
477 NSStringId,
Craig Topperc3ec1492014-05-26 06:22:03 +0000478 nullptr, SourceLocation());
Patrick Beard0caa3942012-04-19 00:25:12 +0000479 } else {
480 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
481 return ExprError();
482 }
483 } else if (!NSStringDecl->hasDefinition()) {
484 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
485 return ExprError();
486 }
487 assert(NSStringDecl && "NSStringDecl should not be NULL");
Jordy Roseaca01f92012-05-12 17:32:52 +0000488 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
489 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000490 }
491
492 if (!StringWithUTF8StringMethod) {
493 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
494 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
495
496 // Look for the appropriate method within NSString.
Jordy Rose08e500c2012-05-12 17:32:44 +0000497 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
498 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000499 // Debugger needs to work even if NSString hasn't been defined.
Craig Topperc3ec1492014-05-26 06:22:03 +0000500 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000501 ObjCMethodDecl *M = ObjCMethodDecl::Create(
502 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
503 NSStringPointer, ReturnTInfo, NSStringDecl,
504 /*isInstance=*/false, /*isVariadic=*/false,
505 /*isPropertyAccessor=*/false,
506 /*isImplicitlyDeclared=*/true,
507 /*isDefined=*/false, ObjCMethodDecl::Required,
508 /*HasRelatedResultType=*/false);
Jordy Roseaca01f92012-05-12 17:32:52 +0000509 QualType ConstCharType = Context.CharTy.withConst();
Patrick Beard0caa3942012-04-19 00:25:12 +0000510 ParmVarDecl *value =
511 ParmVarDecl::Create(Context, M,
512 SourceLocation(), SourceLocation(),
513 &Context.Idents.get("value"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000514 Context.getPointerType(ConstCharType),
Craig Topperc3ec1492014-05-26 06:22:03 +0000515 /*TInfo=*/nullptr,
516 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000517 M->setMethodParams(Context, value, None);
Jordy Rose08e500c2012-05-12 17:32:44 +0000518 BoxingMethod = M;
Patrick Beard0caa3942012-04-19 00:25:12 +0000519 }
Jordy Rose890f4572012-05-12 15:53:41 +0000520
Jordy Rose08e500c2012-05-12 17:32:44 +0000521 if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
522 stringWithUTF8String, BoxingMethod))
523 return ExprError();
524
525 StringWithUTF8StringMethod = BoxingMethod;
Patrick Beard0caa3942012-04-19 00:25:12 +0000526 }
527
528 BoxingMethod = StringWithUTF8StringMethod;
529 BoxedType = NSStringPointer;
530 }
Patrick Beard2565c592012-05-01 21:47:19 +0000531 } else if (ValueType->isBuiltinType()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000532 // The other types we support are numeric, char and BOOL/bool. We could also
533 // provide limited support for structure types, such as NSRange, NSRect, and
534 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
535 // for more details.
536
537 // Check for a top-level character literal.
538 if (const CharacterLiteral *Char =
539 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
540 // In C, character literals have type 'int'. That's not the type we want
541 // to use to determine the Objective-c literal kind.
542 switch (Char->getKind()) {
543 case CharacterLiteral::Ascii:
544 ValueType = Context.CharTy;
545 break;
546
547 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000548 ValueType = Context.getWideCharType();
Patrick Beard0caa3942012-04-19 00:25:12 +0000549 break;
550
551 case CharacterLiteral::UTF16:
552 ValueType = Context.Char16Ty;
553 break;
554
555 case CharacterLiteral::UTF32:
556 ValueType = Context.Char32Ty;
557 break;
558 }
559 }
Fariborz Jahanian5d64abb2014-06-18 20:49:02 +0000560 CheckForIntOverflow(ValueExpr);
Patrick Beard0caa3942012-04-19 00:25:12 +0000561 // FIXME: Do I need to do anything special with BoolTy expressions?
562
563 // Look for the appropriate method within NSNumber.
564 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
565 BoxedType = NSNumberPointer;
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000566
567 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
568 if (!ET->getDecl()->isComplete()) {
569 Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type)
570 << ValueType << ValueExpr->getSourceRange();
571 return ExprError();
572 }
573
574 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(),
575 ET->getDecl()->getIntegerType());
576 BoxedType = NSNumberPointer;
Patrick Beard0caa3942012-04-19 00:25:12 +0000577 }
578
579 if (!BoxingMethod) {
580 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
581 << ValueType << ValueExpr->getSourceRange();
582 return ExprError();
583 }
584
585 // Convert the expression to the type that the parameter requires.
Alp Toker03376dc2014-07-07 09:02:20 +0000586 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
Patrick Beard2565c592012-05-01 21:47:19 +0000587 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
588 ParamDecl);
589 ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
590 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000591 ValueExpr);
Patrick Beard0caa3942012-04-19 00:25:12 +0000592 if (ConvertedValueExpr.isInvalid())
593 return ExprError();
594 ValueExpr = ConvertedValueExpr.get();
595
596 ObjCBoxedExpr *BoxedExpr =
597 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
598 BoxingMethod, SR);
599 return MaybeBindToTemporary(BoxedExpr);
600}
601
John McCallf2538342012-07-31 05:14:30 +0000602/// Build an ObjC subscript pseudo-object expression, given that
603/// that's supported by the runtime.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000604ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
605 Expr *IndexExpr,
606 ObjCMethodDecl *getterMethod,
607 ObjCMethodDecl *setterMethod) {
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +0000608 assert(!LangOpts.isSubscriptPointerArithmetic());
John McCall5fb5df92012-06-20 06:18:46 +0000609
John McCallf2538342012-07-31 05:14:30 +0000610 // We can't get dependent types here; our callers should have
611 // filtered them out.
612 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
613 "base or index cannot have dependent type here");
614
615 // Filter out placeholders in the index. In theory, overloads could
616 // be preserved here, although that might not actually work correctly.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000617 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
618 if (Result.isInvalid())
619 return ExprError();
620 IndexExpr = Result.get();
621
John McCallf2538342012-07-31 05:14:30 +0000622 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000623 Result = DefaultLvalueConversion(BaseExpr);
624 if (Result.isInvalid())
625 return ExprError();
626 BaseExpr = Result.get();
John McCallf2538342012-07-31 05:14:30 +0000627
628 // Build the pseudo-object expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000629 return ObjCSubscriptRefExpr::Create(Context, BaseExpr, IndexExpr,
630 Context.PseudoObjectTy, getterMethod,
631 setterMethod, RB);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000632}
633
634ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
635 // Look up the NSArray class, if we haven't done so already.
636 if (!NSArrayDecl) {
637 NamedDecl *IF = LookupSingleName(TUScope,
638 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
639 SR.getBegin(),
640 LookupOrdinaryName);
641 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000642 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000643 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
644 Context.getTranslationUnitDecl(),
645 SourceLocation(),
646 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
Craig Topperc3ec1492014-05-26 06:22:03 +0000647 nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000648
649 if (!NSArrayDecl) {
650 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
651 return ExprError();
652 }
653 }
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000654
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000655 // Find the arrayWithObjects:count: method, if we haven't done so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000656 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000657 if (!ArrayWithObjectsMethod) {
658 Selector
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000659 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
660 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000661 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000662 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000663 Method = ObjCMethodDecl::Create(
664 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000665 Context.getTranslationUnitDecl(), false /*Instance*/,
Alp Toker314cc812014-01-25 16:55:45 +0000666 false /*isVariadic*/,
667 /*isPropertyAccessor=*/false,
668 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
669 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000670 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000671 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000672 SourceLocation(),
673 SourceLocation(),
674 &Context.Idents.get("objects"),
675 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000676 /*TInfo=*/nullptr,
677 SC_None, nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000678 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000679 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000680 SourceLocation(),
681 SourceLocation(),
682 &Context.Idents.get("cnt"),
683 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000684 /*TInfo=*/nullptr, SC_None,
685 nullptr);
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.
Alp Toker03376dc2014-07-07 09:02:20 +0000694 QualType T = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000695 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;
Alp Toker03376dc2014-07-07 09:02:20 +0000700 Diag(Method->parameters()[0]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000701 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.
Alp Toker03376dc2014-07-07 09:02:20 +0000708 if (!Method->parameters()[1]->getType()->isIntegerType()) {
Jordy Rose4af44872012-05-12 17:32:56 +0000709 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
710 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000711 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000712 diag::note_objc_literal_method_param)
713 << 1
Alp Toker03376dc2014-07-07 09:02:20 +0000714 << Method->parameters()[1]->getType()
Jordy Rose4af44872012-05-12 17:32:56 +0000715 << "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
Alp Toker03376dc2014-07-07 09:02:20 +0000723 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000724 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,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000745 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),
Craig Topperc3ec1492014-05-26 06:22:03 +0000762 nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000763
764 if (!NSDictionaryDecl) {
765 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
766 return ExprError();
767 }
768 }
769
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000770 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
771 // so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000772 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000773 if (!DictionaryWithObjectsMethod) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000774 Selector Sel = NSAPIObj->getNSDictionarySelector(
775 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
776 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000777 if (!Method && getLangOpts().DebuggerObjCLiteral) {
778 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000779 SourceLocation(), SourceLocation(), Sel,
780 IdT,
Craig Topperc3ec1492014-05-26 06:22:03 +0000781 nullptr /*TypeSourceInfo */,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000782 Context.getTranslationUnitDecl(),
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000783 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),
Craig Topperc3ec1492014-05-26 06:22:03 +0000794 /*TInfo=*/nullptr, SC_None,
795 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000796 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000797 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000798 SourceLocation(),
799 SourceLocation(),
800 &Context.Idents.get("keys"),
801 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000802 /*TInfo=*/nullptr, SC_None,
803 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000804 Params.push_back(keys);
Jordy Rose08e500c2012-05-12 17:32:44 +0000805 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000806 SourceLocation(),
807 SourceLocation(),
808 &Context.Idents.get("cnt"),
809 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000810 /*TInfo=*/nullptr, SC_None,
811 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000812 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000813 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000814 }
815
Jordy Rose08e500c2012-05-12 17:32:44 +0000816 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
817 Method))
818 return ExprError();
819
Jordy Rose4af44872012-05-12 17:32:56 +0000820 // Dig out the type that all values should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000821 QualType ValueT = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000822 const PointerType *PtrValue = ValueT->getAs<PointerType>();
823 if (!PtrValue ||
824 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000825 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000826 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000827 Diag(Method->parameters()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000828 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000829 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000830 << Context.getPointerType(IdT.withConst());
831 return ExprError();
832 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000833
Jordy Rose4af44872012-05-12 17:32:56 +0000834 // Dig out the type that all keys should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000835 QualType KeyT = Method->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000836 const PointerType *PtrKey = KeyT->getAs<PointerType>();
837 if (!PtrKey ||
838 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
839 IdT)) {
840 bool err = true;
841 if (PtrKey) {
842 if (QIDNSCopying.isNull()) {
843 // key argument of selector is id<NSCopying>?
844 if (ObjCProtocolDecl *NSCopyingPDecl =
845 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
846 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
847 QIDNSCopying =
848 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
849 (ObjCProtocolDecl**) PQ,1);
850 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
851 }
852 }
853 if (!QIDNSCopying.isNull())
854 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
855 QIDNSCopying);
856 }
857
858 if (err) {
859 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
860 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000861 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000862 diag::note_objc_literal_method_param)
863 << 1 << KeyT
864 << Context.getPointerType(IdT.withConst());
865 return ExprError();
866 }
867 }
868
869 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000870 QualType CountType = Method->parameters()[2]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000871 if (!CountType->isIntegerType()) {
872 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
873 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000874 Diag(Method->parameters()[2]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000875 diag::note_objc_literal_method_param)
876 << 2 << CountType
877 << "integral";
878 return ExprError();
879 }
880
881 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
882 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000883 }
884
Alp Toker03376dc2014-07-07 09:02:20 +0000885 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000886 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
Alp Toker03376dc2014-07-07 09:02:20 +0000887 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000888 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
889
Ted Kremeneke65b0862012-03-06 20:05:56 +0000890 // Check that each of the keys and values provided is valid in a collection
891 // literal, performing conversions as necessary.
892 bool HasPackExpansions = false;
893 for (unsigned I = 0, N = NumElements; I != N; ++I) {
894 // Check the key.
895 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
896 KeyT);
897 if (Key.isInvalid())
898 return ExprError();
899
900 // Check the value.
901 ExprResult Value
902 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
903 if (Value.isInvalid())
904 return ExprError();
905
906 Elements[I].Key = Key.get();
907 Elements[I].Value = Value.get();
908
909 if (Elements[I].EllipsisLoc.isInvalid())
910 continue;
911
912 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
913 !Elements[I].Value->containsUnexpandedParameterPack()) {
914 Diag(Elements[I].EllipsisLoc,
915 diag::err_pack_expansion_without_parameter_packs)
916 << SourceRange(Elements[I].Key->getLocStart(),
917 Elements[I].Value->getLocEnd());
918 return ExprError();
919 }
920
921 HasPackExpansions = true;
922 }
923
924
925 QualType Ty
926 = Context.getObjCObjectPointerType(
Robert Wilhelm88e02492013-08-19 07:57:02 +0000927 Context.getObjCInterfaceType(NSDictionaryDecl));
928 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
929 Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000930 DictionaryWithObjectsMethod, SR));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000931}
932
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000933ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregorabd9e962010-04-20 15:39:42 +0000934 TypeSourceInfo *EncodedTypeInfo,
Anders Carlsson315d2292009-06-07 18:45:35 +0000935 SourceLocation RParenLoc) {
Douglas Gregorabd9e962010-04-20 15:39:42 +0000936 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlsson315d2292009-06-07 18:45:35 +0000937 QualType StrTy;
Mike Stump11289f42009-09-09 15:08:12 +0000938 if (EncodedType->isDependentType())
Anders Carlsson315d2292009-06-07 18:45:35 +0000939 StrTy = Context.DependentTy;
940 else {
Fariborz Jahaniand9bc6c32011-06-16 22:34:44 +0000941 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
942 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000943 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000944 diag::err_incomplete_type_objc_at_encode,
945 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000946 return ExprError();
947
Anders Carlsson315d2292009-06-07 18:45:35 +0000948 std::string Str;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +0000949 QualType NotEncodedT;
950 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
951 if (!NotEncodedT.isNull())
952 Diag(AtLoc, diag::warn_incomplete_encoded_type)
953 << EncodedType << NotEncodedT;
Anders Carlsson315d2292009-06-07 18:45:35 +0000954
955 // The type of @encode is the same as the type of the corresponding string,
956 // which is an array type.
957 StrTy = Context.CharTy;
958 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +0000959 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlsson315d2292009-06-07 18:45:35 +0000960 StrTy.addConst();
961 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
962 ArrayType::Normal, 0);
963 }
Mike Stump11289f42009-09-09 15:08:12 +0000964
Douglas Gregorabd9e962010-04-20 15:39:42 +0000965 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlsson315d2292009-06-07 18:45:35 +0000966}
967
John McCallfaf5fb42010-08-26 23:41:50 +0000968ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
969 SourceLocation EncodeLoc,
970 SourceLocation LParenLoc,
971 ParsedType ty,
972 SourceLocation RParenLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000973 // FIXME: Preserve type source info ?
Douglas Gregorabd9e962010-04-20 15:39:42 +0000974 TypeSourceInfo *TInfo;
975 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
976 if (!TInfo)
977 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
978 PP.getLocForEndOfToken(LParenLoc));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000979
Douglas Gregorabd9e962010-04-20 15:39:42 +0000980 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000981}
982
Fariborz Jahanian44be1542014-03-12 18:34:01 +0000983static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
984 SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +0000985 SourceLocation LParenLoc,
986 SourceLocation RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +0000987 ObjCMethodDecl *Method,
988 ObjCMethodList &MethList) {
989 ObjCMethodList *M = &MethList;
990 bool Warned = false;
991 for (M = M->getNext(); M; M=M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +0000992 ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
Fariborz Jahanian44be1542014-03-12 18:34:01 +0000993 if (MatchingMethodDecl == Method ||
994 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
995 MatchingMethodDecl->getSelector() != Method->getSelector())
996 continue;
997 if (!S.MatchTwoMethodDeclarations(Method,
998 MatchingMethodDecl, Sema::MMS_loose)) {
999 if (!Warned) {
1000 Warned = true;
1001 S.Diag(AtLoc, diag::warning_multiple_selectors)
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001002 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1003 << FixItHint::CreateInsertion(RParenLoc, ")");
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001004 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1005 << Method->getDeclName();
1006 }
1007 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1008 << MatchingMethodDecl->getDeclName();
1009 }
1010 }
1011 return Warned;
1012}
1013
1014static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001015 ObjCMethodDecl *Method,
1016 SourceLocation LParenLoc,
1017 SourceLocation RParenLoc,
1018 bool WarnMultipleSelectors) {
1019 if (!WarnMultipleSelectors ||
1020 S.Diags.isIgnored(diag::warning_multiple_selectors, SourceLocation()))
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001021 return;
1022 bool Warned = false;
1023 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1024 e = S.MethodPool.end(); b != e; b++) {
1025 // first, instance methods
1026 ObjCMethodList &InstMethList = b->second.first;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001027 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001028 Method, InstMethList))
1029 Warned = true;
1030
1031 // second, class methods
1032 ObjCMethodList &ClsMethList = b->second.second;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001033 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1034 Method, ClsMethList) || Warned)
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001035 return;
1036 }
1037}
1038
John McCallfaf5fb42010-08-26 23:41:50 +00001039ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1040 SourceLocation AtLoc,
1041 SourceLocation SelLoc,
1042 SourceLocation LParenLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001043 SourceLocation RParenLoc,
1044 bool WarnMultipleSelectors) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001045 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1046 SourceRange(LParenLoc, RParenLoc), false, false);
1047 if (!Method)
1048 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian0571d9b2009-06-16 16:25:00 +00001049 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00001050 if (!Method) {
1051 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1052 Selector MatchedSel = OM->getSelector();
1053 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1054 RParenLoc.getLocWithOffset(-1));
1055 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1056 << Sel << MatchedSel
1057 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1058
1059 } else
1060 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001061 } else
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001062 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1063 WarnMultipleSelectors);
Fariborz Jahanian9a881012011-07-13 19:05:43 +00001064
Fariborz Jahanian65a78b52014-05-09 19:51:39 +00001065 if (Method &&
1066 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
1067 !getSourceManager().isInSystemHeader(Method->getLocation())) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001068 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
1069 = ReferencedSelectors.find(Sel);
1070 if (Pos == ReferencedSelectors.end())
1071 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian9a881012011-07-13 19:05:43 +00001072 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001073
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001074 // In ARC, forbid the user from using @selector for
John McCall31168b02011-06-15 23:02:42 +00001075 // retain/release/autorelease/dealloc/retainCount.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001076 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001077 switch (Sel.getMethodFamily()) {
1078 case OMF_retain:
1079 case OMF_release:
1080 case OMF_autorelease:
1081 case OMF_retainCount:
1082 case OMF_dealloc:
1083 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1084 Sel << SourceRange(LParenLoc, RParenLoc);
1085 break;
1086
1087 case OMF_None:
1088 case OMF_alloc:
1089 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00001090 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00001091 case OMF_init:
1092 case OMF_mutableCopy:
1093 case OMF_new:
1094 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00001095 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001096 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001097 break;
1098 }
1099 }
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001100 QualType Ty = Context.getObjCSelType();
Daniel Dunbar45858d22010-02-03 20:11:42 +00001101 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001102}
1103
John McCallfaf5fb42010-08-26 23:41:50 +00001104ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1105 SourceLocation AtLoc,
1106 SourceLocation ProtoLoc,
1107 SourceLocation LParenLoc,
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001108 SourceLocation ProtoIdLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00001109 SourceLocation RParenLoc) {
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001110 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001111 if (!PDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001112 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001113 return true;
1114 }
Fariborz Jahaniana57d91c22014-07-25 19:45:01 +00001115 if (PDecl->hasDefinition())
1116 PDecl = PDecl->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00001117
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001118 QualType Ty = Context.getObjCProtoType();
1119 if (Ty.isNull())
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001120 return true;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001121 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001122 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001123}
1124
John McCall5f2d5562011-02-03 09:00:02 +00001125/// Try to capture an implicit reference to 'self'.
Eli Friedman24af8502012-02-03 22:47:37 +00001126ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1127 DeclContext *DC = getFunctionLevelDeclContext();
John McCall5f2d5562011-02-03 09:00:02 +00001128
1129 // If we're not in an ObjC method, error out. Note that, unlike the
1130 // C++ case, we don't require an instance method --- class methods
1131 // still have a 'self', and we really do still need to capture it!
1132 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1133 if (!method)
Craig Topperc3ec1492014-05-26 06:22:03 +00001134 return nullptr;
John McCall5f2d5562011-02-03 09:00:02 +00001135
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001136 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall5f2d5562011-02-03 09:00:02 +00001137
1138 return method;
1139}
1140
Douglas Gregor64910ca2011-09-09 20:05:21 +00001141static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1142 if (T == Context.getObjCInstanceType())
1143 return Context.getObjCIdType();
1144
1145 return T;
1146}
1147
Douglas Gregor33823722011-06-11 01:09:30 +00001148QualType Sema::getMessageSendResultType(QualType ReceiverType,
1149 ObjCMethodDecl *Method,
1150 bool isClassMessage, bool isSuperMessage) {
1151 assert(Method && "Must have a method");
1152 if (!Method->hasRelatedResultType())
1153 return Method->getSendResultType();
1154
1155 // If a method has a related return type:
1156 // - if the method found is an instance method, but the message send
1157 // was a class message send, T is the declared return type of the method
1158 // found
1159 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor64910ca2011-09-09 20:05:21 +00001160 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001161
1162 // - if the receiver is super, T is a pointer to the class of the
1163 // enclosing method definition
1164 if (isSuperMessage) {
1165 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1166 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1167 return Context.getObjCObjectPointerType(
1168 Context.getObjCInterfaceType(Class));
1169 }
1170
1171 // - if the receiver is the name of a class U, T is a pointer to U
1172 if (ReceiverType->getAs<ObjCInterfaceType>() ||
1173 ReceiverType->isObjCQualifiedInterfaceType())
1174 return Context.getObjCObjectPointerType(ReceiverType);
1175 // - if the receiver is of type Class or qualified Class type,
1176 // T is the declared return type of the method.
1177 if (ReceiverType->isObjCClassType() ||
1178 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor64910ca2011-09-09 20:05:21 +00001179 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001180
1181 // - if the receiver is id, qualified id, Class, or qualified Class, T
1182 // is the receiver type, otherwise
1183 // - T is the type of the receiver expression.
1184 return ReceiverType;
1185}
John McCall5f2d5562011-02-03 09:00:02 +00001186
John McCall5ec7e7d2013-03-19 07:04:25 +00001187/// Look for an ObjC method whose result type exactly matches the given type.
1188static const ObjCMethodDecl *
1189findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1190 QualType instancetype) {
Alp Toker314cc812014-01-25 16:55:45 +00001191 if (MD->getReturnType() == instancetype)
1192 return MD;
John McCall5ec7e7d2013-03-19 07:04:25 +00001193
1194 // For these purposes, a method in an @implementation overrides a
1195 // declaration in the @interface.
1196 if (const ObjCImplDecl *impl =
1197 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1198 const ObjCContainerDecl *iface;
1199 if (const ObjCCategoryImplDecl *catImpl =
1200 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1201 iface = catImpl->getCategoryDecl();
1202 } else {
1203 iface = impl->getClassInterface();
1204 }
1205
1206 const ObjCMethodDecl *ifaceMD =
1207 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1208 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1209 }
1210
1211 SmallVector<const ObjCMethodDecl *, 4> overrides;
1212 MD->getOverriddenMethods(overrides);
1213 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1214 if (const ObjCMethodDecl *result =
1215 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1216 return result;
1217 }
1218
Craig Topperc3ec1492014-05-26 06:22:03 +00001219 return nullptr;
John McCall5ec7e7d2013-03-19 07:04:25 +00001220}
1221
1222void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1223 // Only complain if we're in an ObjC method and the required return
1224 // type doesn't match the method's declared return type.
1225 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1226 if (!MD || !MD->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +00001227 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
John McCall5ec7e7d2013-03-19 07:04:25 +00001228 return;
1229
1230 // Look for a method overridden by this method which explicitly uses
1231 // 'instancetype'.
1232 if (const ObjCMethodDecl *overridden =
1233 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +00001234 SourceRange range = overridden->getReturnTypeSourceRange();
1235 SourceLocation loc = range.getBegin();
John McCall5ec7e7d2013-03-19 07:04:25 +00001236 if (loc.isInvalid())
1237 loc = overridden->getLocation();
1238 Diag(loc, diag::note_related_result_type_explicit)
1239 << /*current method*/ 1 << range;
1240 return;
1241 }
1242
1243 // Otherwise, if we have an interesting method family, note that.
1244 // This should always trigger if the above didn't.
1245 if (ObjCMethodFamily family = MD->getMethodFamily())
1246 Diag(MD->getLocation(), diag::note_related_result_type_family)
1247 << /*current method*/ 1
1248 << family;
1249}
1250
Douglas Gregor33823722011-06-11 01:09:30 +00001251void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1252 E = E->IgnoreParenImpCasts();
1253 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1254 if (!MsgSend)
1255 return;
1256
1257 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1258 if (!Method)
1259 return;
1260
1261 if (!Method->hasRelatedResultType())
1262 return;
Alp Toker314cc812014-01-25 16:55:45 +00001263
1264 if (Context.hasSameUnqualifiedType(
1265 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
Douglas Gregor33823722011-06-11 01:09:30 +00001266 return;
Alp Toker314cc812014-01-25 16:55:45 +00001267
1268 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
Douglas Gregorbab8a962011-09-08 01:46:34 +00001269 Context.getObjCInstanceType()))
1270 return;
1271
Douglas Gregor33823722011-06-11 01:09:30 +00001272 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1273 << Method->isInstanceMethod() << Method->getSelector()
1274 << MsgSend->getType();
1275}
1276
1277bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001278 MultiExprArg Args,
1279 Selector Sel,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001280 ArrayRef<SourceLocation> SelectorLocs,
1281 ObjCMethodDecl *Method,
Douglas Gregor33823722011-06-11 01:09:30 +00001282 bool isClassMessage, bool isSuperMessage,
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001283 SourceLocation lbrac, SourceLocation rbrac,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001284 SourceRange RecRange,
John McCall7decc9e2010-11-18 06:31:45 +00001285 QualType &ReturnType, ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001286 SourceLocation SelLoc;
1287 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1288 SelLoc = SelectorLocs.front();
1289 else
1290 SelLoc = lbrac;
1291
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001292 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001293 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001294 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001295 if (Args[i]->isTypeDependent())
1296 continue;
1297
John McCallcc5788c2013-03-04 07:34:02 +00001298 ExprResult result;
1299 if (getLangOpts().DebuggerSupport) {
1300 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001301 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001302 } else {
1303 result = DefaultArgumentPromotion(Args[i]);
1304 }
1305 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001306 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001307 Args[i] = result.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001308 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001309
John McCall31168b02011-06-15 23:02:42 +00001310 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001311 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001312 DiagID = diag::err_arc_method_not_found;
1313 else
1314 DiagID = isClassMessage ? diag::warn_class_method_not_found
1315 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001316 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001317 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahanian06499232013-06-18 17:10:58 +00001318 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001319 if (getLangOpts().ObjCAutoRefCount)
1320 DiagID = diag::error_method_not_found_with_typo;
1321 else
1322 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1323 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001324 Selector MatchedSel = OMD->getSelector();
1325 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian5ab87502014-08-12 22:16:41 +00001326 if (MatchedSel.isUnarySelector())
1327 Diag(SelLoc, DiagID)
1328 << Sel<< isClassMessage << MatchedSel
1329 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1330 else
1331 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001332 }
1333 else
1334 Diag(SelLoc, DiagID)
1335 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001336 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001337 // Find the class to which we are sending this message.
1338 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001339 if (ObjCInterfaceDecl *ThisClass =
1340 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
1341 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1342 if (!RecRange.isInvalid())
1343 if (ThisClass->lookupClassMethod(Sel))
1344 Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
1345 << FixItHint::CreateReplacement(RecRange,
1346 ThisClass->getNameAsString());
1347 }
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001348 }
1349 }
John McCall3f4138c2011-07-13 17:56:40 +00001350
1351 // In debuggers, we want to use __unknown_anytype for these
1352 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001353 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001354 ReturnType = Context.UnknownAnyTy;
1355 } else {
1356 ReturnType = Context.getObjCIdType();
1357 }
John McCall7decc9e2010-11-18 06:31:45 +00001358 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001359 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001360 }
Mike Stump11289f42009-09-09 15:08:12 +00001361
Douglas Gregor33823722011-06-11 01:09:30 +00001362 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1363 isSuperMessage);
Alp Toker314cc812014-01-25 16:55:45 +00001364 VK = Expr::getValueKindForType(Method->getReturnType());
Mike Stump11289f42009-09-09 15:08:12 +00001365
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001366 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001367 // Method might have more arguments than selector indicates. This is due
1368 // to addition of c-style arguments in method.
1369 if (Method->param_size() > Sel.getNumArgs())
1370 NumNamedArgs = Method->param_size();
1371 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001372 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001373 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001374 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001375 return false;
1376 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001377
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001378 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001379 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001380 // We can't do any type-checking on a type-dependent argument.
1381 if (Args[i]->isTypeDependent())
1382 continue;
1383
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001384 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001385
Alp Toker03376dc2014-07-07 09:02:20 +00001386 ParmVarDecl *param = Method->parameters()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001387 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001388
John McCall4124c492011-10-17 18:40:02 +00001389 // Strip the unbridged-cast placeholder expression off unless it's
1390 // a consumed argument.
1391 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1392 !param->hasAttr<CFConsumedAttr>())
1393 argExpr = stripARCUnbridgedCast(argExpr);
1394
John McCallea0a39e2012-11-14 00:49:39 +00001395 // If the parameter is __unknown_anytype, infer its type
1396 // from the argument.
1397 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001398 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001399 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001400 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001401 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001402 } else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001403 Args[i] = argE.get();
John McCallea0a39e2012-11-14 00:49:39 +00001404
John McCallcc5788c2013-03-04 07:34:02 +00001405 // Update the parameter type in-place.
1406 param->setType(paramType);
1407 }
1408 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001409 }
1410
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001411 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall4124c492011-10-17 18:40:02 +00001412 param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001413 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001414 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001415
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001416 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall4124c492011-10-17 18:40:02 +00001417 param);
Fariborz Jahaniana1db7df2014-07-31 17:39:50 +00001418 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001419 if (ArgE.isInvalid())
1420 IsError = true;
1421 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001422 Args[i] = ArgE.getAs<Expr>();
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001423 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001424
1425 // Promote additional arguments to variadic methods.
1426 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001427 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001428 if (Args[i]->isTypeDependent())
1429 continue;
1430
Jordy Roseaca01f92012-05-12 17:32:52 +00001431 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
Craig Topperc3ec1492014-05-26 06:22:03 +00001432 nullptr);
John Wiegley01296292011-04-08 18:41:53 +00001433 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001434 Args[i] = Arg.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001435 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001436 } else {
1437 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001438 if (Args.size() != NumNamedArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00001439 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001440 diag::err_typecheck_call_too_many_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001441 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001442 << Method->getSourceRange()
Chris Lattner3b054132008-11-19 05:08:23 +00001443 << SourceRange(Args[NumNamedArgs]->getLocStart(),
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001444 Args.back()->getLocEnd());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001445 }
1446 }
1447
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001448 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001449
1450 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001451 IsError |= CheckObjCMethodCall(
Craig Topper8c2a2a02014-08-30 16:55:39 +00001452 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001453
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001454 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001455}
1456
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001457bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001458 // 'self' is objc 'self' in an objc method only.
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001459 ObjCMethodDecl *Method =
1460 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1461 return isSelfExpr(RExpr, Method);
1462}
1463
1464bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
John McCallfe96e0b2011-11-06 09:01:30 +00001465 if (!method) return false;
1466
John McCall31168b02011-06-15 23:02:42 +00001467 receiver = receiver->IgnoreParenLValueCasts();
1468 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001469 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001470 return true;
1471 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001472}
1473
John McCall526ab472011-10-25 17:37:35 +00001474/// LookupMethodInType - Look up a method in an ObjCObjectType.
1475ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1476 bool isInstance) {
1477 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1478 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1479 // Look it up in the main interface (and categories, etc.)
1480 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1481 return method;
1482
1483 // Okay, look for "private" methods declared in any
1484 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001485 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1486 return method;
John McCall526ab472011-10-25 17:37:35 +00001487 }
1488
1489 // Check qualifiers.
Aaron Ballman1683f7b2014-03-17 15:55:30 +00001490 for (const auto *I : objType->quals())
1491 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
John McCall526ab472011-10-25 17:37:35 +00001492 return method;
1493
Craig Topperc3ec1492014-05-26 06:22:03 +00001494 return nullptr;
John McCall526ab472011-10-25 17:37:35 +00001495}
1496
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001497/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1498/// list of a qualified objective pointer type.
1499ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1500 const ObjCObjectPointerType *OPT,
1501 bool Instance)
1502{
Craig Topperc3ec1492014-05-26 06:22:03 +00001503 ObjCMethodDecl *MD = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +00001504 for (const auto *PROTO : OPT->quals()) {
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001505 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1506 return MD;
1507 }
1508 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001509 return nullptr;
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001510}
1511
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001512static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1513 if (!Receiver)
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001514 return;
1515
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001516 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver))
1517 Receiver = OVE->getSourceExpr();
1518
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001519 Expr *RExpr = Receiver->IgnoreParenImpCasts();
1520 SourceLocation Loc = RExpr->getLocStart();
1521 QualType T = RExpr->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001522 const ObjCPropertyDecl *PDecl = nullptr;
1523 const ObjCMethodDecl *GDecl = nullptr;
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001524 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1525 RExpr = POE->getSyntacticForm();
1526 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1527 if (PRE->isImplicitProperty()) {
1528 GDecl = PRE->getImplicitPropertyGetter();
1529 if (GDecl) {
Alp Toker314cc812014-01-25 16:55:45 +00001530 T = GDecl->getReturnType();
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001531 }
1532 }
1533 else {
1534 PDecl = PRE->getExplicitProperty();
1535 if (PDecl) {
1536 T = PDecl->getType();
1537 }
1538 }
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001539 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001540 }
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001541 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) {
1542 // See if receiver is a method which envokes a synthesized getter
1543 // backing a 'weak' property.
1544 ObjCMethodDecl *Method = ME->getMethodDecl();
Jordan Rose2bd991a2012-10-10 16:42:54 +00001545 if (Method && Method->getSelector().getNumArgs() == 0) {
1546 PDecl = Method->findPropertyDecl();
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001547 if (PDecl)
1548 T = PDecl->getType();
1549 }
1550 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001551
Jordan Rose13d6b712012-09-28 22:21:42 +00001552 if (T.getObjCLifetime() != Qualifiers::OCL_Weak) {
1553 if (!PDecl)
1554 return;
1555 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak))
1556 return;
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001557 }
Jordan Rose13d6b712012-09-28 22:21:42 +00001558
1559 S.Diag(Loc, diag::warn_receiver_is_weak)
1560 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1561
1562 if (PDecl)
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001563 S.Diag(PDecl->getLocation(), diag::note_property_declare);
Jordan Rose13d6b712012-09-28 22:21:42 +00001564 else if (GDecl)
1565 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
1566
1567 S.Diag(Loc, diag::note_arc_assign_to_strong);
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001568}
1569
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001570/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1571/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001572ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001573HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001574 Expr *BaseExpr, SourceLocation OpLoc,
1575 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001576 SourceLocation MemberLoc,
1577 SourceLocation SuperLoc, QualType SuperType,
1578 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001579 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1580 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001581
Benjamin Kramer365082d2012-05-19 16:34:46 +00001582 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001583 Diag(MemberLoc, diag::err_invalid_property_name)
1584 << MemberName << QualType(OPT, 0);
1585 return ExprError();
1586 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001587
1588 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregord6459312011-04-20 18:19:55 +00001589
Douglas Gregor4123a862011-11-14 22:10:01 +00001590 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1591 : BaseExpr->getSourceRange();
1592 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001593 diag::err_property_not_found_forward_class,
1594 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001595 return ExprError();
Douglas Gregor4123a862011-11-14 22:10:01 +00001596
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001597 // Search for a declared property first.
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001598 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001599 // Check whether we can reference this property.
1600 if (DiagnoseUseOfDecl(PD, MemberLoc))
1601 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001602 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001603 return new (Context)
1604 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1605 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001606 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001607 return new (Context)
1608 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1609 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001610 }
1611 // Check protocols on qualified interfaces.
Aaron Ballman83731462014-03-17 16:14:00 +00001612 for (const auto *I : OPT->quals())
1613 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001614 // Check whether we can reference this property.
1615 if (DiagnoseUseOfDecl(PD, MemberLoc))
1616 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001617
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001618 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001619 return new (Context) ObjCPropertyRefExpr(
1620 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1621 SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001622 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001623 return new (Context)
1624 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1625 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001626 }
1627 // If that failed, look for an "implicit" property by seeing if the nullary
1628 // selector is implemented.
1629
1630 // FIXME: The logic for looking up nullary and unary selectors should be
1631 // shared with the code in ActOnInstanceMessage.
1632
1633 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1634 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001635
1636 // May be founf in property's qualified list.
1637 if (!Getter)
1638 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001639
1640 // If this reference is in an @implementation, check for 'private' methods.
1641 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001642 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001643
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001644 if (Getter) {
1645 // Check if we can reference this property.
1646 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1647 return ExprError();
1648 }
1649 // If we found a getter then this may be a valid dot-reference, we
1650 // will look for the matching setter, in case it is needed.
1651 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001652 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1653 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001654 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001655
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001656 // May be founf in property's qualified list.
1657 if (!Setter)
1658 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1659
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001660 if (!Setter) {
1661 // If this reference is in an @implementation, also check for 'private'
1662 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001663 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001664 }
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001665
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001666 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1667 return ExprError();
1668
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001669 // Special warning if member name used in a property-dot for a setter accessor
1670 // does not use a property with same name; e.g. obj.X = ... for a property with
1671 // name 'x'.
1672 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor()
1673 && !IFace->FindPropertyDeclaration(Member)) {
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001674 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
1675 // Do not warn if user is using property-dot syntax to make call to
1676 // user named setter.
1677 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001678 Diag(MemberLoc,
1679 diag::warn_property_access_suggest)
1680 << MemberName << QualType(OPT, 0) << PDecl->getName()
1681 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001682 }
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001683 }
1684
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001685 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001686 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001687 return new (Context)
1688 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1689 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001690 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001691 return new (Context)
1692 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1693 OK_ObjCProperty, MemberLoc, BaseExpr);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001694
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001695 }
1696
1697 // Attempt to correct for typos in property names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001698 if (TypoCorrection Corrected =
1699 CorrectTypo(DeclarationNameInfo(MemberName, MemberLoc),
1700 LookupOrdinaryName, nullptr, nullptr,
1701 llvm::make_unique<DeclFilterCCC<ObjCPropertyDecl>>(),
1702 CTK_ErrorRecovery, IFace, false, OPT)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001703 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1704 << MemberName << QualType(OPT, 0));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001705 DeclarationName TypoResult = Corrected.getCorrection();
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001706 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1707 TypoResult, MemberLoc,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001708 SuperLoc, SuperType, Super);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001709 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001710 ObjCInterfaceDecl *ClassDeclared;
1711 if (ObjCIvarDecl *Ivar =
1712 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1713 QualType T = Ivar->getType();
1714 if (const ObjCObjectPointerType * OBJPT =
1715 T->getAsObjCInterfacePointerType()) {
Douglas Gregor4123a862011-11-14 22:10:01 +00001716 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001717 diag::err_property_not_as_forward_class,
1718 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001719 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001720 }
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001721 Diag(MemberLoc,
1722 diag::err_ivar_access_using_property_syntax_suggest)
1723 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1724 << FixItHint::CreateReplacement(OpLoc, "->");
1725 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001726 }
Chris Lattner90c58fa2010-04-11 07:51:10 +00001727
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001728 Diag(MemberLoc, diag::err_property_not_found)
1729 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001730 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001731 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001732 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001733 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001734}
1735
1736
1737
John McCalldadc5752010-08-24 06:29:42 +00001738ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001739ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1740 IdentifierInfo &propertyName,
1741 SourceLocation receiverNameLoc,
1742 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001743
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001744 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001745 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1746 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001747
1748 bool IsSuper = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00001749 if (!IFace) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001750 // If the "receiver" is 'super' in a method, handle it as an expression-like
1751 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001752 if (receiverNamePtr->isStr("super")) {
Douglas Gregor33823722011-06-11 01:09:30 +00001753 IsSuper = true;
1754
Eli Friedman24af8502012-02-03 22:47:37 +00001755 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001756 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1757 if (CurMethod->isInstanceMethod()) {
1758 ObjCInterfaceDecl *Super = Class->getSuperClass();
1759 if (!Super) {
1760 // The current class does not have a superclass.
1761 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1762 << Class->getIdentifier();
1763 return ExprError();
1764 }
1765 QualType T = Context.getObjCInterfaceType(Super);
1766 T = Context.getObjCObjectPointerType(T);
1767
1768 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
1769 /*BaseExpr*/nullptr,
1770 SourceLocation()/*OpLoc*/,
1771 &propertyName,
1772 propertyNameLoc,
1773 receiverNameLoc, T, true);
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00001774 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001775
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001776 // Otherwise, if this is a class method, try dispatching to our
1777 // superclass.
1778 IFace = Class->getSuperClass();
Chris Lattnera36ec422010-04-11 08:28:14 +00001779 }
Chris Lattnera36ec422010-04-11 08:28:14 +00001780 }
John McCall5f2d5562011-02-03 09:00:02 +00001781 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001782
1783 if (!IFace) {
Alp Tokerec543272013-12-24 09:48:30 +00001784 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1785 << tok::l_paren;
Chris Lattnera36ec422010-04-11 08:28:14 +00001786 return ExprError();
1787 }
1788 }
1789
1790 // Search for a declared property first.
Steve Naroff9527bbf2009-03-09 21:12:44 +00001791 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001792 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001793
1794 // If this reference is in an @implementation, check for 'private' methods.
1795 if (!Getter)
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001796 Getter = IFace->lookupPrivateClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001797
1798 if (Getter) {
1799 // FIXME: refactor/share with ActOnMemberReference().
1800 // Check if we can reference this property.
1801 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1802 return ExprError();
1803 }
Mike Stump11289f42009-09-09 15:08:12 +00001804
Steve Naroff9527bbf2009-03-09 21:12:44 +00001805 // Look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00001806 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001807 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1808 PP.getSelectorTable(),
1809 &propertyName);
Mike Stump11289f42009-09-09 15:08:12 +00001810
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001811 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001812 if (!Setter) {
1813 // If this reference is in an @implementation, also check for 'private'
1814 // methods.
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001815 Setter = IFace->lookupPrivateClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001816 }
1817 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00001818 if (!Setter)
1819 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001820
1821 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1822 return ExprError();
1823
1824 if (Getter || Setter) {
Douglas Gregor33823722011-06-11 01:09:30 +00001825 if (IsSuper)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001826 return new (Context)
1827 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1828 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
1829 Context.getObjCInterfaceType(IFace));
Douglas Gregor33823722011-06-11 01:09:30 +00001830
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001831 return new (Context) ObjCPropertyRefExpr(
1832 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
1833 propertyNameLoc, receiverNameLoc, IFace);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001834 }
1835 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1836 << &propertyName << Context.getObjCInterfaceType(IFace));
1837}
1838
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001839namespace {
1840
1841class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1842 public:
1843 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1844 // Determine whether "super" is acceptable in the current context.
1845 if (Method && Method->getClassInterface())
1846 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1847 }
1848
Craig Toppere14c0f82014-03-12 04:55:44 +00001849 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001850 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1851 candidate.isKeyword("super");
1852 }
1853};
1854
1855}
1856
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001857Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001858 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001859 SourceLocation NameLoc,
1860 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001861 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00001862 ParsedType &ReceiverType) {
1863 ReceiverType = ParsedType();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001864
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001865 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00001866 // messaging super. If the identifier is "super" and there is a
1867 // trailing dot, it's an instance message.
1868 if (IsSuper && S->isInObjcMethodScope())
1869 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001870
1871 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1872 LookupName(Result, S);
1873
1874 switch (Result.getResultKind()) {
1875 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00001876 // Normal name lookup didn't find anything. If we're in an
1877 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00001878 // FIXME: This is a hack. Ivar lookup should be part of normal
1879 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00001880 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00001881 if (!Method->getClassInterface()) {
1882 // Fall back: let the parser try to parse it as an instance message.
1883 return ObjCInstanceMessage;
1884 }
1885
Douglas Gregorca7136b2010-04-19 20:09:36 +00001886 ObjCInterfaceDecl *ClassDeclared;
1887 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1888 ClassDeclared))
1889 return ObjCInstanceMessage;
1890 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00001891
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001892 // Break out; we'll perform typo correction below.
1893 break;
1894
1895 case LookupResult::NotFoundInCurrentInstantiation:
1896 case LookupResult::FoundOverloaded:
1897 case LookupResult::FoundUnresolvedValue:
1898 case LookupResult::Ambiguous:
1899 Result.suppressDiagnostics();
1900 return ObjCInstanceMessage;
1901
1902 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00001903 // If the identifier is a class or not, and there is a trailing dot,
1904 // it's an instance message.
1905 if (HasTrailingDot)
1906 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001907 // We found something. If it's a type, then we have a class
1908 // message. Otherwise, it's an instance message.
1909 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001910 QualType T;
1911 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1912 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001913 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00001914 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001915 DiagnoseUseOfDecl(Type, NameLoc);
1916 }
1917 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00001918 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001919
Douglas Gregore5798dc2010-04-21 20:38:13 +00001920 // We have a class message, and T is the type we're
1921 // messaging. Build source-location information for it.
1922 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00001923 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00001924 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001925 }
1926 }
1927
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001928 if (TypoCorrection Corrected = CorrectTypo(
1929 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr,
1930 llvm::make_unique<ObjCInterfaceOrSuperCCC>(getCurMethodDecl()),
1931 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001932 if (Corrected.isKeyword()) {
1933 // If we've found the keyword "super" (the only keyword that would be
1934 // returned by CorrectTypo), this is a send to super.
Richard Smithf9b15102013-08-17 00:46:16 +00001935 diagnoseTypo(Corrected,
1936 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001937 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001938 } else if (ObjCInterfaceDecl *Class =
Richard Smithf9b15102013-08-17 00:46:16 +00001939 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001940 // If we found a declaration, correct when it refers to an Objective-C
1941 // class.
Richard Smithf9b15102013-08-17 00:46:16 +00001942 diagnoseTypo(Corrected,
1943 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001944 QualType T = Context.getObjCInterfaceType(Class);
1945 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1946 ReceiverType = CreateParsedType(T, TSInfo);
1947 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001948 }
1949 }
Richard Smithf9b15102013-08-17 00:46:16 +00001950
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001951 // Fall back: let the parser try to parse it as an instance message.
1952 return ObjCInstanceMessage;
1953}
Steve Naroff9527bbf2009-03-09 21:12:44 +00001954
John McCalldadc5752010-08-24 06:29:42 +00001955ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001956 SourceLocation SuperLoc,
1957 Selector Sel,
1958 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00001959 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001960 SourceLocation RBracLoc,
1961 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001962 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00001963 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00001964 if (!Method) {
1965 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1966 return ExprError();
1967 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001968
Douglas Gregor4fdba132010-04-21 20:01:04 +00001969 ObjCInterfaceDecl *Class = Method->getClassInterface();
1970 if (!Class) {
1971 Diag(SuperLoc, diag::error_no_super_class_message)
1972 << Method->getDeclName();
1973 return ExprError();
1974 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001975
Douglas Gregor4fdba132010-04-21 20:01:04 +00001976 ObjCInterfaceDecl *Super = Class->getSuperClass();
1977 if (!Super) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001978 // The current class does not have a superclass.
Ted Kremenek499897b2011-01-23 17:21:34 +00001979 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1980 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001981 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00001982 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001983
Douglas Gregor4fdba132010-04-21 20:01:04 +00001984 // We are in a method whose class has a superclass, so 'super'
1985 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00001986 if (Method->getSelector() == Sel)
1987 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00001988
Jordan Rose2afd6612012-10-19 16:05:26 +00001989 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00001990 // Since we are in an instance method, this is an instance
1991 // message to the superclass instance.
1992 QualType SuperTy = Context.getObjCInterfaceType(Super);
1993 SuperTy = Context.getObjCObjectPointerType(SuperTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00001994 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
1995 Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001996 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001997 }
Douglas Gregor4fdba132010-04-21 20:01:04 +00001998
1999 // Since we are in a class method, this is a class message to
2000 // the superclass.
Craig Topperc3ec1492014-05-26 06:22:03 +00002001 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
Douglas Gregor4fdba132010-04-21 20:01:04 +00002002 Context.getObjCInterfaceType(Super),
Craig Topperc3ec1492014-05-26 06:22:03 +00002003 SuperLoc, Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002004 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002005}
2006
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002007
2008ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2009 bool isSuperReceiver,
2010 SourceLocation Loc,
2011 Selector Sel,
2012 ObjCMethodDecl *Method,
2013 MultiExprArg Args) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002014 TypeSourceInfo *receiverTypeInfo = nullptr;
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002015 if (!ReceiverType.isNull())
2016 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2017
2018 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2019 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2020 Sel, Method, Loc, Loc, Loc, Args,
2021 /*isImplicit=*/true);
2022
2023}
2024
Ted Kremeneke65b0862012-03-06 20:05:56 +00002025static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2026 unsigned DiagID,
2027 bool (*refactor)(const ObjCMessageExpr *,
2028 const NSAPI &, edit::Commit &)) {
2029 SourceLocation MsgLoc = Msg->getExprLoc();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002030 if (S.Diags.isIgnored(DiagID, MsgLoc))
Ted Kremeneke65b0862012-03-06 20:05:56 +00002031 return;
2032
2033 SourceManager &SM = S.SourceMgr;
2034 edit::Commit ECommit(SM, S.LangOpts);
2035 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2036 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2037 << Msg->getSelector() << Msg->getSourceRange();
2038 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2039 if (!ECommit.isCommitable())
2040 return;
2041 for (edit::Commit::edit_iterator
2042 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2043 const edit::Commit::Edit &Edit = *I;
2044 switch (Edit.Kind) {
2045 case edit::Commit::Act_Insert:
2046 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2047 Edit.Text,
2048 Edit.BeforePrev));
2049 break;
2050 case edit::Commit::Act_InsertFromRange:
2051 Builder.AddFixItHint(
2052 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2053 Edit.getInsertFromRange(SM),
2054 Edit.BeforePrev));
2055 break;
2056 case edit::Commit::Act_Remove:
2057 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2058 break;
2059 }
2060 }
2061 }
2062}
2063
2064static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2065 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2066 edit::rewriteObjCRedundantCallWithLiteral);
2067}
2068
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002069/// \brief Diagnose use of %s directive in an NSString which is being passed
2070/// as formatting string to formatting method.
2071static void
2072DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2073 ObjCMethodDecl *Method,
2074 Selector Sel,
2075 Expr **Args, unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002076 unsigned Idx = 0;
2077 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002078 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2079 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002080 Idx = 0;
2081 Format = true;
2082 }
2083 else if (Method) {
2084 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2085 if (S.GetFormatNSStringIdx(I, Idx)) {
2086 Format = true;
2087 break;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002088 }
2089 }
2090 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002091 if (!Format || NumArgs <= Idx)
2092 return;
2093
2094 Expr *FormatExpr = Args[Idx];
2095 if (ObjCStringLiteral *OSL =
2096 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2097 StringLiteral *FormatString = OSL->getString();
2098 if (S.FormatStringHasSArg(FormatString)) {
2099 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2100 << "%s" << 0 << 0;
2101 if (Method)
2102 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2103 << Method->getDeclName();
2104 }
2105 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002106}
2107
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002108/// \brief Build an Objective-C class message expression.
2109///
2110/// This routine takes care of both normal class messages and
2111/// class messages to the superclass.
2112///
2113/// \param ReceiverTypeInfo Type source information that describes the
2114/// receiver of this message. This may be NULL, in which case we are
2115/// sending to the superclass and \p SuperLoc must be a valid source
2116/// location.
2117
2118/// \param ReceiverType The type of the object receiving the
2119/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2120/// type as that refers to. For a superclass send, this is the type of
2121/// the superclass.
2122///
2123/// \param SuperLoc The location of the "super" keyword in a
2124/// superclass message.
2125///
2126/// \param Sel The selector to which the message is being sent.
2127///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002128/// \param Method The method that this class message is invoking, if
2129/// already known.
2130///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002131/// \param LBracLoc The location of the opening square bracket ']'.
2132///
James Dennettffad8b72012-06-22 08:10:18 +00002133/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002134///
James Dennettffad8b72012-06-22 08:10:18 +00002135/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002136ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002137 QualType ReceiverType,
2138 SourceLocation SuperLoc,
2139 Selector Sel,
2140 ObjCMethodDecl *Method,
2141 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002142 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002143 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002144 MultiExprArg ArgsIn,
2145 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002146 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002147 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002148 if (LBracLoc.isInvalid()) {
2149 Diag(Loc, diag::err_missing_open_square_message_send)
2150 << FixItHint::CreateInsertion(Loc, "[");
2151 LBracLoc = Loc;
2152 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002153 SourceLocation SelLoc;
2154 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2155 SelLoc = SelectorLocs.front();
2156 else
2157 SelLoc = Loc;
2158
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002159 if (ReceiverType->isDependentType()) {
2160 // If the receiver type is dependent, we can't type-check anything
2161 // at this point. Build a dependent expression.
2162 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002163 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002164 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002165 return ObjCMessageExpr::Create(
2166 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2167 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2168 isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002169 }
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002170
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002171 // Find the class to which we are sending this message.
Craig Topperc3ec1492014-05-26 06:22:03 +00002172 ObjCInterfaceDecl *Class = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00002173 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2174 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002175 Diag(Loc, diag::err_invalid_receiver_class_message)
2176 << ReceiverType;
2177 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002178 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002179 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002180 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002181 if (!getLangOpts().CPlusPlus)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002182 (void)DiagnoseUseOfDecl(Class, SelLoc);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002183 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002184 if (!Method) {
Douglas Gregor4123a862011-11-14 22:10:01 +00002185 SourceRange TypeRange
2186 = SuperLoc.isValid()? SourceRange(SuperLoc)
2187 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002188 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002189 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002190 ? diag::err_arc_receiver_forward_class
2191 : diag::warn_receiver_forward_class),
2192 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002193 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorb5186b12010-04-22 17:01:48 +00002194 Method = LookupFactoryMethodInGlobalPool(Sel,
2195 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002196 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002197 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2198 << Method->getDeclName();
2199 }
2200 if (!Method)
2201 Method = Class->lookupClassMethod(Sel);
2202
2203 // If we have an implementation in scope, check "private" methods.
2204 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002205 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002206
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002207 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002208 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002209 }
Mike Stump11289f42009-09-09 15:08:12 +00002210
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002211 // Check the argument types and determine the result type.
2212 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002213 ExprValueKind VK = VK_RValue;
2214
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002215 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002216 Expr **Args = ArgsIn.data();
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002217 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2218 Sel, SelectorLocs,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00002219 Method, true,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002220 SuperLoc.isValid(), LBracLoc, RBracLoc,
2221 SourceRange(),
Douglas Gregor33823722011-06-11 01:09:30 +00002222 ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002223 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002224
Alp Toker314cc812014-01-25 16:55:45 +00002225 if (Method && !Method->getReturnType()->isVoidType() &&
2226 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002227 diag::err_illegal_message_expr_incomplete_type))
2228 return ExprError();
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002229
Fariborz Jahaniane8b45502014-08-22 19:52:49 +00002230 // Warn about explicit call of +initialize on its own class. But not on 'super'.
Fariborz Jahanian42292282014-08-25 21:27:38 +00002231 if (Method && Method->getMethodFamily() == OMF_initialize) {
2232 if (!SuperLoc.isValid()) {
2233 const ObjCInterfaceDecl *ID =
2234 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2235 if (ID == Class) {
2236 Diag(Loc, diag::warn_direct_initialize_call);
2237 Diag(Method->getLocation(), diag::note_method_declared_at)
2238 << Method->getDeclName();
2239 }
2240 }
2241 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2242 // [super initialize] is allowed only within an +initialize implementation
2243 if (CurMeth->getMethodFamily() != OMF_initialize) {
2244 Diag(Loc, diag::warn_direct_super_initialize_call);
2245 Diag(Method->getLocation(), diag::note_method_declared_at)
2246 << Method->getDeclName();
2247 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2248 << CurMeth->getDeclName();
2249 }
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002250 }
2251 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002252
2253 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2254
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002255 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002256 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002257 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002258 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002259 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002260 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002261 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002262 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002263 else {
John McCall7decc9e2010-11-18 06:31:45 +00002264 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002265 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002266 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002267 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002268 if (!isImplicit)
2269 checkCocoaAPI(*this, Result);
2270 }
Douglas Gregoraae38d62010-05-22 05:17:18 +00002271 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002272}
2273
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002274// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002275// ArgExprs is optional - if it is present, the number of expressions
2276// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002277ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002278 ParsedType Receiver,
2279 Selector Sel,
2280 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002281 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002282 SourceLocation RBracLoc,
2283 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002284 TypeSourceInfo *ReceiverTypeInfo;
2285 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2286 if (ReceiverType.isNull())
2287 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002288
Mike Stump11289f42009-09-09 15:08:12 +00002289
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002290 if (!ReceiverTypeInfo)
2291 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2292
2293 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002294 /*SuperLoc=*/SourceLocation(), Sel,
2295 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2296 Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002297}
2298
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002299ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2300 QualType ReceiverType,
2301 SourceLocation Loc,
2302 Selector Sel,
2303 ObjCMethodDecl *Method,
2304 MultiExprArg Args) {
2305 return BuildInstanceMessage(Receiver, ReceiverType,
2306 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2307 Sel, Method, Loc, Loc, Loc, Args,
2308 /*isImplicit=*/true);
2309}
2310
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002311/// \brief Build an Objective-C instance message expression.
2312///
2313/// This routine takes care of both normal instance messages and
2314/// instance messages to the superclass instance.
2315///
2316/// \param Receiver The expression that computes the object that will
2317/// receive this message. This may be empty, in which case we are
2318/// sending to the superclass instance and \p SuperLoc must be a valid
2319/// source location.
2320///
2321/// \param ReceiverType The (static) type of the object receiving the
2322/// message. When a \p Receiver expression is provided, this is the
2323/// same type as that expression. For a superclass instance send, this
2324/// is a pointer to the type of the superclass.
2325///
2326/// \param SuperLoc The location of the "super" keyword in a
2327/// superclass instance message.
2328///
2329/// \param Sel The selector to which the message is being sent.
2330///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002331/// \param Method The method that this instance message is invoking, if
2332/// already known.
2333///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002334/// \param LBracLoc The location of the opening square bracket ']'.
2335///
James Dennettffad8b72012-06-22 08:10:18 +00002336/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002337///
James Dennettffad8b72012-06-22 08:10:18 +00002338/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002339ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002340 QualType ReceiverType,
2341 SourceLocation SuperLoc,
2342 Selector Sel,
2343 ObjCMethodDecl *Method,
2344 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002345 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002346 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002347 MultiExprArg ArgsIn,
2348 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002349 // The location of the receiver.
2350 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002351 SourceRange RecRange =
2352 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2353 SourceLocation SelLoc;
2354 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2355 SelLoc = SelectorLocs.front();
2356 else
2357 SelLoc = Loc;
2358
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002359 if (LBracLoc.isInvalid()) {
2360 Diag(Loc, diag::err_missing_open_square_message_send)
2361 << FixItHint::CreateInsertion(Loc, "[");
2362 LBracLoc = Loc;
2363 }
2364
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002365 // If we have a receiver expression, perform appropriate promotions
2366 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002367 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002368 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002369 ExprResult Result;
2370 if (Receiver->getType() == Context.UnknownAnyTy)
2371 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2372 else
2373 Result = CheckPlaceholderExpr(Receiver);
2374 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002375 Receiver = Result.get();
John McCall4124c492011-10-17 18:40:02 +00002376 }
2377
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002378 if (Receiver->isTypeDependent()) {
2379 // If the receiver is type-dependent, we can't type-check anything
2380 // at this point. Build a dependent expression.
2381 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002382 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002383 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002384 return ObjCMessageExpr::Create(
2385 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2386 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2387 RBracLoc, isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002388 }
2389
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002390 // If necessary, apply function/array conversion to the receiver.
2391 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002392 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2393 if (Result.isInvalid())
2394 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002395 Receiver = Result.get();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002396 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002397
2398 // If the receiver is an ObjC pointer, a block pointer, or an
2399 // __attribute__((NSObject)) pointer, we don't need to do any
2400 // special conversion in order to look up a receiver.
2401 if (ReceiverType->isObjCRetainableType()) {
2402 // do nothing
2403 } else if (!getLangOpts().ObjCAutoRefCount &&
2404 !Context.getObjCIdType().isNull() &&
2405 (ReceiverType->isPointerType() ||
2406 ReceiverType->isIntegerType())) {
2407 // Implicitly convert integers and pointers to 'id' but emit a warning.
2408 // But not in ARC.
2409 Diag(Loc, diag::warn_bad_receiver_type)
2410 << ReceiverType
2411 << Receiver->getSourceRange();
2412 if (ReceiverType->isPointerType()) {
2413 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002414 CK_CPointerToObjCPointerCast).get();
John McCall80c93a02013-03-01 09:20:14 +00002415 } else {
2416 // TODO: specialized warning on null receivers?
2417 bool IsNull = Receiver->isNullPointerConstant(Context,
2418 Expr::NPC_ValueDependentIsNull);
2419 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2420 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002421 Kind).get();
John McCall80c93a02013-03-01 09:20:14 +00002422 }
2423 ReceiverType = Receiver->getType();
2424 } else if (getLangOpts().CPlusPlus) {
Douglas Gregor4b60a152013-11-07 22:34:54 +00002425 // The receiver must be a complete type.
2426 if (RequireCompleteType(Loc, Receiver->getType(),
2427 diag::err_incomplete_receiver_type))
2428 return ExprError();
2429
John McCall80c93a02013-03-01 09:20:14 +00002430 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2431 if (result.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002432 Receiver = result.get();
John McCall80c93a02013-03-01 09:20:14 +00002433 ReceiverType = Receiver->getType();
2434 }
2435 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002436 }
2437
John McCall80c93a02013-03-01 09:20:14 +00002438 // There's a somewhat weird interaction here where we assume that we
2439 // won't actually have a method unless we also don't need to do some
2440 // of the more detailed type-checking on the receiver.
2441
Douglas Gregorb5186b12010-04-22 17:01:48 +00002442 if (!Method) {
2443 // Handle messages to id.
Fariborz Jahanian32e59ba2010-08-10 18:10:50 +00002444 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002445 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002446 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2447 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002448 SourceRange(LBracLoc, RBracLoc),
2449 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002450 if (!Method)
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002451 Method = LookupFactoryMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002452 SourceRange(LBracLoc,RBracLoc),
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002453 receiverIsId);
Fariborz Jahanian05e77f82014-11-07 23:51:15 +00002454 if (Method) {
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002455 if (ObjCMethodDecl *BestMethod =
Fariborz Jahaniand288fad2014-08-13 23:38:04 +00002456 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002457 Method = BestMethod;
Sylvestre Ledru30f17082014-11-17 18:26:39 +00002458 if (!AreMultipleMethodsInGlobalPool(Sel, Method->isInstanceMethod()))
2459 DiagnoseUseOfDecl(Method, SelLoc);
Fariborz Jahanian05e77f82014-11-07 23:51:15 +00002460 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002461 } else if (ReceiverType->isObjCClassType() ||
2462 ReceiverType->isObjCQualifiedClassType()) {
2463 // Handle messages to Class.
Nico Weber2e0c8f72014-12-27 03:58:08 +00002464 // We allow sending a message to a qualified Class ("Class<foo>"), which
2465 // is ok as long as one of the protocols implements the selector (if not,
2466 // warn).
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002467 if (const ObjCObjectPointerType *QClassTy
2468 = ReceiverType->getAsObjCQualifiedClassType()) {
2469 // Search protocols for class methods.
2470 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2471 if (!Method) {
2472 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2473 // warn if instance method found for a Class message.
2474 if (Method) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002475 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002476 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002477 Diag(Method->getLocation(), diag::note_method_declared_at)
2478 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002479 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002480 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002481 } else {
2482 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2483 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2484 // First check the public methods in the class interface.
2485 Method = ClassDecl->lookupClassMethod(Sel);
2486
2487 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002488 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002489 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002490 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002491 return ExprError();
2492 }
2493 if (!Method) {
2494 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002495 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002496 Method = LookupFactoryMethodInGlobalPool(Sel,
2497 SourceRange(LBracLoc, RBracLoc),
2498 true);
2499 if (!Method) {
2500 // If no class (factory) method was found, check if an _instance_
2501 // method of the same name exists in the root class only.
2502 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002503 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002504 true);
2505 if (Method)
2506 if (const ObjCInterfaceDecl *ID =
2507 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2508 if (ID->getSuperClass())
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002509 Diag(SelLoc, diag::warn_root_inst_method_not_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002510 << Sel << SourceRange(LBracLoc, RBracLoc);
2511 }
2512 }
Fariborz Jahaniand288fad2014-08-13 23:38:04 +00002513 if (Method)
2514 if (ObjCMethodDecl *BestMethod =
2515 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
2516 Method = BestMethod;
Douglas Gregor9a129192010-04-21 00:45:42 +00002517 }
2518 }
2519 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002520 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002521 ObjCInterfaceDecl *ClassDecl = nullptr;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002522
2523 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2524 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002525 // And as long as message is not deprecated/unavailable (warn if it is).
Douglas Gregorb5186b12010-04-22 17:01:48 +00002526 if (const ObjCObjectPointerType *QIdTy
2527 = ReceiverType->getAsObjCQualifiedIdType()) {
2528 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002529 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2530 if (!Method)
2531 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002532 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002533 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002534 } else if (const ObjCObjectPointerType *OCIType
2535 = ReceiverType->getAsObjCInterfacePointerType()) {
2536 // We allow sending a message to a pointer to an interface (an object).
2537 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002538
Douglas Gregor4123a862011-11-14 22:10:01 +00002539 // Try to complete the type. Under ARC, this is a hard error from which
2540 // we don't try to recover.
Craig Topperc3ec1492014-05-26 06:22:03 +00002541 const ObjCInterfaceDecl *forwardClass = nullptr;
Douglas Gregor4123a862011-11-14 22:10:01 +00002542 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002543 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002544 ? diag::err_arc_receiver_forward_instance
2545 : diag::warn_receiver_forward_instance,
2546 Receiver? Receiver->getSourceRange()
2547 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002548 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002549 return ExprError();
2550
2551 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanianc934de62012-02-03 01:02:44 +00002552 Diag(Receiver ? Receiver->getLocStart()
2553 : SuperLoc, diag::note_receiver_is_id);
Craig Topperc3ec1492014-05-26 06:22:03 +00002554 Method = nullptr;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002555 } else {
2556 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002557 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002558
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002559 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002560 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002561 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2562
Douglas Gregorb5186b12010-04-22 17:01:48 +00002563 if (!Method) {
2564 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002565 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002566
David Blaikiebbafb8a2012-03-11 07:00:24 +00002567 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002568 Diag(SelLoc, diag::err_arc_may_not_respond)
2569 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002570 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002571 return ExprError();
2572 }
2573
Douglas Gregor486b74e2011-09-27 16:10:05 +00002574 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002575 // If we still haven't found a method, look in the global pool. This
2576 // behavior isn't very desirable, however we need it for GCC
2577 // compatibility. FIXME: should we deviate??
2578 if (OCIType->qual_empty()) {
2579 Method = LookupInstanceMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002580 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002581 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002582 Diag(SelLoc, diag::warn_maynot_respond)
2583 << OCIType->getInterfaceDecl()->getIdentifier()
2584 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002585 }
2586 }
2587 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002588 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002589 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002590 } else {
John McCall80c93a02013-03-01 09:20:14 +00002591 // Reject other random receiver types (e.g. structs).
2592 Diag(Loc, diag::err_bad_receiver_type)
2593 << ReceiverType << Receiver->getSourceRange();
2594 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002595 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002596 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002597 }
Mike Stump11289f42009-09-09 15:08:12 +00002598
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002599 FunctionScopeInfo *DIFunctionScopeInfo =
2600 (Method && Method->getMethodFamily() == OMF_init)
Craig Topperc3ec1492014-05-26 06:22:03 +00002601 ? getEnclosingFunction() : nullptr;
2602
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002603 if (DIFunctionScopeInfo &&
2604 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002605 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2606 bool isDesignatedInitChain = false;
2607 if (SuperLoc.isValid()) {
2608 if (const ObjCObjectPointerType *
2609 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2610 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
Argyrios Kyrtzidisd664a342013-12-13 03:48:17 +00002611 // Either we know this is a designated initializer or we
2612 // conservatively assume it because we don't know for sure.
2613 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2614 ID->isDesignatedInitializer(Sel)) {
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002615 isDesignatedInitChain = true;
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002616 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002617 }
2618 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002619 }
2620 }
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002621 if (!isDesignatedInitChain) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002622 const ObjCMethodDecl *InitMethod = nullptr;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002623 bool isDesignated =
2624 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2625 assert(isDesignated && InitMethod);
2626 (void)isDesignated;
2627 Diag(SelLoc, SuperLoc.isValid() ?
2628 diag::warn_objc_designated_init_non_designated_init_call :
2629 diag::warn_objc_designated_init_non_super_designated_init_call);
2630 Diag(InitMethod->getLocation(),
2631 diag::note_objc_designated_init_marked_here);
2632 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002633 }
2634
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002635 if (DIFunctionScopeInfo &&
2636 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002637 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2638 if (SuperLoc.isValid()) {
2639 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2640 } else {
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002641 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002642 }
2643 }
2644
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002645 // Check the message arguments.
2646 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002647 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002648 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002649 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00002650 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2651 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002652 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2653 Sel, SelectorLocs, Method,
Douglas Gregor33823722011-06-11 01:09:30 +00002654 ClassMessage, SuperLoc.isValid(),
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002655 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002656 return ExprError();
Alp Toker314cc812014-01-25 16:55:45 +00002657
2658 if (Method && !Method->getReturnType()->isVoidType() &&
2659 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002660 diag::err_illegal_message_expr_incomplete_type))
2661 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00002662
John McCall31168b02011-06-15 23:02:42 +00002663 // In ARC, forbid the user from sending messages to
2664 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002665 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002666 ObjCMethodFamily family =
2667 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2668 switch (family) {
2669 case OMF_init:
2670 if (Method)
2671 checkInitMethod(Method, ReceiverType);
2672
2673 case OMF_None:
2674 case OMF_alloc:
2675 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00002676 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002677 case OMF_mutableCopy:
2678 case OMF_new:
2679 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002680 case OMF_initialize:
John McCall31168b02011-06-15 23:02:42 +00002681 break;
2682
2683 case OMF_dealloc:
2684 case OMF_retain:
2685 case OMF_release:
2686 case OMF_autorelease:
2687 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002688 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2689 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00002690 break;
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002691
2692 case OMF_performSelector:
2693 if (Method && NumArgs >= 1) {
2694 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2695 Selector ArgSel = SelExp->getSelector();
2696 ObjCMethodDecl *SelMethod =
2697 LookupInstanceMethodInGlobalPool(ArgSel,
2698 SelExp->getSourceRange());
2699 if (!SelMethod)
2700 SelMethod =
2701 LookupFactoryMethodInGlobalPool(ArgSel,
2702 SelExp->getSourceRange());
2703 if (SelMethod) {
2704 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2705 switch (SelFamily) {
2706 case OMF_alloc:
2707 case OMF_copy:
2708 case OMF_mutableCopy:
2709 case OMF_new:
2710 case OMF_self:
2711 case OMF_init:
2712 // Issue error, unless ns_returns_not_retained.
2713 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2714 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002715 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002716 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002717 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2718 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002719 }
2720 break;
2721 default:
2722 // +0 call. OK. unless ns_returns_retained.
2723 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2724 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002725 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002726 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002727 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2728 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002729 }
2730 break;
2731 }
2732 }
2733 } else {
2734 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002735 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002736 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2737 }
2738 }
2739 break;
John McCall31168b02011-06-15 23:02:42 +00002740 }
2741 }
2742
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002743 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2744
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002745 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00002746 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002747 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002748 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002749 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002750 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002751 makeArrayRef(Args, NumArgs), RBracLoc,
2752 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002753 else {
John McCall7decc9e2010-11-18 06:31:45 +00002754 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002755 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002756 makeArrayRef(Args, NumArgs), RBracLoc,
2757 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002758 if (!isImplicit)
2759 checkCocoaAPI(*this, Result);
2760 }
John McCall31168b02011-06-15 23:02:42 +00002761
David Blaikiebbafb8a2012-03-11 07:00:24 +00002762 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahanian9277ff42014-06-17 23:35:13 +00002763 // Do not warn about IBOutlet weak property receivers being set to null
2764 // as this cannot asynchronously happen.
2765 bool WarnWeakReceiver = true;
2766 if (isImplicit && Method)
2767 if (const ObjCPropertyDecl *PropertyDecl = Method->findPropertyDecl())
2768 WarnWeakReceiver = !PropertyDecl->hasAttr<IBOutletAttr>();
2769 if (WarnWeakReceiver)
2770 DiagnoseARCUseOfWeakReceiver(*this, Receiver);
Fariborz Jahanian6bd22262012-04-04 20:05:25 +00002771
John McCall31168b02011-06-15 23:02:42 +00002772 // In ARC, annotate delegate init calls.
2773 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00002774 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00002775 // Only consider init calls *directly* in init implementations,
2776 // not within blocks.
2777 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2778 if (method && method->getMethodFamily() == OMF_init) {
2779 // The implicit assignment to self means we also don't want to
2780 // consume the result.
2781 Result->setDelegateInitCall(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002782 return Result;
John McCall31168b02011-06-15 23:02:42 +00002783 }
2784 }
2785
2786 // In ARC, check for message sends which are likely to introduce
2787 // retain cycles.
2788 checkRetainCycles(Result);
Jordan Rose22487652012-10-11 16:06:21 +00002789
2790 if (!isImplicit && Method) {
2791 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2792 bool IsWeak =
2793 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2794 if (!IsWeak && Sel.isUnarySelector())
2795 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002796 if (IsWeak &&
2797 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
2798 getCurFunction()->recordUseOfWeak(Result, Prop);
Jordan Rose22487652012-10-11 16:06:21 +00002799 }
2800 }
John McCall31168b02011-06-15 23:02:42 +00002801 }
Alex Denisove1d882c2015-03-04 17:55:52 +00002802
2803 CheckObjCCircularContainer(Result);
2804
Douglas Gregoraae38d62010-05-22 05:17:18 +00002805 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002806}
2807
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002808static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2809 if (ObjCSelectorExpr *OSE =
2810 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2811 Selector Sel = OSE->getSelector();
2812 SourceLocation Loc = OSE->getAtLoc();
2813 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
2814 = S.ReferencedSelectors.find(Sel);
2815 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
2816 S.ReferencedSelectors.erase(Pos);
2817 }
2818}
2819
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002820// ActOnInstanceMessage - used for both unary and keyword messages.
2821// ArgExprs is optional - if it is present, the number of expressions
2822// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002823ExprResult Sema::ActOnInstanceMessage(Scope *S,
2824 Expr *Receiver,
2825 Selector Sel,
2826 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002827 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00002828 SourceLocation RBracLoc,
2829 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002830 if (!Receiver)
2831 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002832
2833 // A ParenListExpr can show up while doing error recovery with invalid code.
2834 if (isa<ParenListExpr>(Receiver)) {
2835 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
2836 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002837 Receiver = Result.get();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002838 }
Fariborz Jahanian17748062013-01-22 19:05:17 +00002839
2840 if (RespondsToSelectorSel.isNull()) {
2841 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
2842 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
2843 }
2844 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002845 RemoveSelectorFromWarningCache(*this, Args[0]);
Craig Topperc3ec1492014-05-26 06:22:03 +00002846
John McCallb268a282010-08-23 23:25:46 +00002847 return BuildInstanceMessage(Receiver, Receiver->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002848 /*SuperLoc=*/SourceLocation(), Sel,
2849 /*Method=*/nullptr, LBracLoc, SelectorLocs,
2850 RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002851}
Chris Lattner2a3569b2008-04-07 05:30:13 +00002852
John McCall31168b02011-06-15 23:02:42 +00002853enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00002854 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00002855 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00002856
2857 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00002858 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00002859
2860 /// id*, id***, void (^*)(),
2861 ACTC_indirectRetainable,
2862
2863 /// void* might be a normal C type, or it might a CF type.
2864 ACTC_voidPtr,
2865
2866 /// struct A*
2867 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00002868};
John McCalle4fe2452011-10-01 01:01:08 +00002869static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2870 return (ACTC == ACTC_retainable ||
2871 ACTC == ACTC_coreFoundation ||
2872 ACTC == ACTC_voidPtr);
2873}
2874static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2875 return ACTC == ACTC_none ||
2876 ACTC == ACTC_voidPtr ||
2877 ACTC == ACTC_coreFoundation;
2878}
2879
John McCall31168b02011-06-15 23:02:42 +00002880static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00002881 bool isIndirect = false;
John McCall31168b02011-06-15 23:02:42 +00002882
2883 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00002884 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00002885 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002886 isIndirect = true;
2887 }
John McCall31168b02011-06-15 23:02:42 +00002888
2889 // Drill through pointers and arrays recursively.
2890 while (true) {
2891 if (const PointerType *ptr = type->getAs<PointerType>()) {
2892 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002893
2894 // The first level of pointer may be the innermost pointer on a CF type.
2895 if (!isIndirect) {
2896 if (type->isVoidType()) return ACTC_voidPtr;
2897 if (type->isRecordType()) return ACTC_coreFoundation;
2898 }
John McCall31168b02011-06-15 23:02:42 +00002899 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2900 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2901 } else {
2902 break;
2903 }
John McCalle4fe2452011-10-01 01:01:08 +00002904 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00002905 }
2906
John McCalle4fe2452011-10-01 01:01:08 +00002907 if (isIndirect) {
2908 if (type->isObjCARCBridgableType())
2909 return ACTC_indirectRetainable;
2910 return ACTC_none;
2911 }
2912
2913 if (type->isObjCARCBridgableType())
2914 return ACTC_retainable;
2915
2916 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00002917}
2918
2919namespace {
John McCalle4fe2452011-10-01 01:01:08 +00002920 /// A result from the cast checker.
2921 enum ACCResult {
2922 /// Cannot be casted.
2923 ACC_invalid,
2924
2925 /// Can be safely retained or not retained.
2926 ACC_bottom,
2927
2928 /// Can be casted at +0.
2929 ACC_plusZero,
2930
2931 /// Can be casted at +1.
2932 ACC_plusOne
2933 };
2934 ACCResult merge(ACCResult left, ACCResult right) {
2935 if (left == right) return left;
2936 if (left == ACC_bottom) return right;
2937 if (right == ACC_bottom) return left;
2938 return ACC_invalid;
2939 }
2940
2941 /// A checker which white-lists certain expressions whose conversion
2942 /// to or from retainable type would otherwise be forbidden in ARC.
2943 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2944 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2945
John McCall31168b02011-06-15 23:02:42 +00002946 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00002947 ARCConversionTypeClass SourceClass;
2948 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002949 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00002950
2951 static bool isCFType(QualType type) {
2952 // Someday this can use ns_bridged. For now, it has to do this.
2953 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00002954 }
John McCalle4fe2452011-10-01 01:01:08 +00002955
2956 public:
2957 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002958 ARCConversionTypeClass target, bool diagnose)
2959 : Context(Context), SourceClass(source), TargetClass(target),
2960 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00002961
2962 using super::Visit;
2963 ACCResult Visit(Expr *e) {
2964 return super::Visit(e->IgnoreParens());
2965 }
2966
2967 ACCResult VisitStmt(Stmt *s) {
2968 return ACC_invalid;
2969 }
2970
2971 /// Null pointer constants can be casted however you please.
2972 ACCResult VisitExpr(Expr *e) {
2973 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2974 return ACC_bottom;
2975 return ACC_invalid;
2976 }
2977
2978 /// Objective-C string literals can be safely casted.
2979 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2980 // If we're casting to any retainable type, go ahead. Global
2981 // strings are immune to retains, so this is bottom.
2982 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2983
2984 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002985 }
2986
John McCalle4fe2452011-10-01 01:01:08 +00002987 /// Look through certain implicit and explicit casts.
2988 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002989 switch (e->getCastKind()) {
2990 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00002991 return ACC_bottom;
2992
John McCall31168b02011-06-15 23:02:42 +00002993 case CK_NoOp:
2994 case CK_LValueToRValue:
2995 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002996 case CK_CPointerToObjCPointerCast:
2997 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002998 case CK_AnyPointerToBlockPointerCast:
2999 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00003000
John McCall31168b02011-06-15 23:02:42 +00003001 default:
John McCalle4fe2452011-10-01 01:01:08 +00003002 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00003003 }
3004 }
John McCalle4fe2452011-10-01 01:01:08 +00003005
3006 /// Look through unary extension.
3007 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003008 return Visit(e->getSubExpr());
3009 }
John McCalle4fe2452011-10-01 01:01:08 +00003010
3011 /// Ignore the LHS of a comma operator.
3012 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00003013 return Visit(e->getRHS());
3014 }
John McCalle4fe2452011-10-01 01:01:08 +00003015
3016 /// Conditional operators are okay if both sides are okay.
3017 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3018 ACCResult left = Visit(e->getTrueExpr());
3019 if (left == ACC_invalid) return ACC_invalid;
3020 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00003021 }
John McCalle4fe2452011-10-01 01:01:08 +00003022
John McCallfe96e0b2011-11-06 09:01:30 +00003023 /// Look through pseudo-objects.
3024 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3025 // If we're getting here, we should always have a result.
3026 return Visit(e->getResultExpr());
3027 }
3028
John McCalle4fe2452011-10-01 01:01:08 +00003029 /// Statement expressions are okay if their result expression is okay.
3030 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00003031 return Visit(e->getSubStmt()->body_back());
3032 }
John McCall31168b02011-06-15 23:02:42 +00003033
John McCalle4fe2452011-10-01 01:01:08 +00003034 /// Some declaration references are okay.
3035 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
John McCalle4fe2452011-10-01 01:01:08 +00003036 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
Ben Langmuir443aa4b2015-02-25 20:09:06 +00003037 // References to global constants are okay.
John McCalle4fe2452011-10-01 01:01:08 +00003038 if (isAnyRetainable(TargetClass) &&
3039 isAnyRetainable(SourceClass) &&
3040 var &&
3041 var->getStorageClass() == SC_Extern &&
Ben Langmuir443aa4b2015-02-25 20:09:06 +00003042 var->getType().isConstQualified()) {
3043
3044 // In system headers, they can also be assumed to be immune to retains.
3045 // These are things like 'kCFStringTransformToLatin'.
3046 if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
3047 return ACC_bottom;
3048
3049 return ACC_plusZero;
John McCalle4fe2452011-10-01 01:01:08 +00003050 }
3051
3052 // Nothing else.
3053 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00003054 }
John McCalle4fe2452011-10-01 01:01:08 +00003055
3056 /// Some calls are okay.
3057 ACCResult VisitCallExpr(CallExpr *e) {
3058 if (FunctionDecl *fn = e->getDirectCallee())
3059 if (ACCResult result = checkCallToFunction(fn))
3060 return result;
3061
3062 return super::VisitCallExpr(e);
3063 }
3064
3065 ACCResult checkCallToFunction(FunctionDecl *fn) {
3066 // Require a CF*Ref return type.
Alp Toker314cc812014-01-25 16:55:45 +00003067 if (!isCFType(fn->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003068 return ACC_invalid;
3069
3070 if (!isAnyRetainable(TargetClass))
3071 return ACC_invalid;
3072
3073 // Honor an explicit 'not retained' attribute.
3074 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3075 return ACC_plusZero;
3076
3077 // Honor an explicit 'retained' attribute, except that for
3078 // now we're not going to permit implicit handling of +1 results,
3079 // because it's a bit frightening.
3080 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003081 return Diagnose ? ACC_plusOne
3082 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003083
3084 // Recognize this specific builtin function, which is used by CFSTR.
3085 unsigned builtinID = fn->getBuiltinID();
3086 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3087 return ACC_bottom;
3088
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003089 // Otherwise, don't do anything implicit with an unaudited function.
3090 if (!fn->hasAttr<CFAuditedTransferAttr>())
3091 return ACC_invalid;
3092
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003093 // Otherwise, it's +0 unless it follows the create convention.
3094 if (ento::coreFoundation::followsCreateRule(fn))
3095 return Diagnose ? ACC_plusOne
3096 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003097
John McCalle4fe2452011-10-01 01:01:08 +00003098 return ACC_plusZero;
3099 }
3100
3101 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3102 return checkCallToMethod(e->getMethodDecl());
3103 }
3104
3105 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3106 ObjCMethodDecl *method;
3107 if (e->isExplicitProperty())
3108 method = e->getExplicitProperty()->getGetterMethodDecl();
3109 else
3110 method = e->getImplicitPropertyGetter();
3111 return checkCallToMethod(method);
3112 }
3113
3114 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3115 if (!method) return ACC_invalid;
3116
3117 // Check for message sends to functions returning CF types. We
3118 // just obey the Cocoa conventions with these, even though the
3119 // return type is CF.
Alp Toker314cc812014-01-25 16:55:45 +00003120 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003121 return ACC_invalid;
3122
3123 // If the method is explicitly marked not-retained, it's +0.
3124 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3125 return ACC_plusZero;
3126
3127 // If the method is explicitly marked as returning retained, or its
3128 // selector follows a +1 Cocoa convention, treat it as +1.
3129 if (method->hasAttr<CFReturnsRetainedAttr>())
3130 return ACC_plusOne;
3131
3132 switch (method->getSelector().getMethodFamily()) {
3133 case OMF_alloc:
3134 case OMF_copy:
3135 case OMF_mutableCopy:
3136 case OMF_new:
3137 return ACC_plusOne;
3138
3139 default:
3140 // Otherwise, treat it as +0.
3141 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00003142 }
3143 }
John McCalle4fe2452011-10-01 01:01:08 +00003144 };
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00003145}
3146
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003147bool Sema::isKnownName(StringRef name) {
3148 if (name.empty())
3149 return false;
3150 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003151 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003152 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003153}
3154
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003155static void addFixitForObjCARCConversion(Sema &S,
3156 DiagnosticBuilder &DiagB,
3157 Sema::CheckedConversionKind CCK,
3158 SourceLocation afterLParen,
3159 QualType castType,
3160 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003161 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003162 const char *bridgeKeyword,
3163 const char *CFBridgeName) {
3164 // We handle C-style and implicit casts here.
3165 switch (CCK) {
3166 case Sema::CCK_ImplicitConversion:
3167 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003168 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003169 break;
3170 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003171 return;
3172 }
3173
3174 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003175 if (CCK == Sema::CCK_OtherCast) {
3176 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3177 SourceRange range(NCE->getOperatorLoc(),
3178 NCE->getAngleBrackets().getEnd());
3179 SmallString<32> BridgeCall;
3180
3181 SourceManager &SM = S.getSourceManager();
3182 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3183 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3184 BridgeCall += ' ';
3185
3186 BridgeCall += CFBridgeName;
3187 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3188 }
3189 return;
3190 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003191 Expr *castedE = castExpr;
3192 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3193 castedE = CCE->getSubExpr();
3194 castedE = castedE->IgnoreImpCasts();
3195 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00003196
3197 SmallString<32> BridgeCall;
3198
3199 SourceManager &SM = S.getSourceManager();
3200 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3201 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3202 BridgeCall += ' ';
3203
3204 BridgeCall += CFBridgeName;
3205
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003206 if (isa<ParenExpr>(castedE)) {
3207 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003208 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003209 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00003210 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003211 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003212 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003213 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3214 S.PP.getLocForEndOfToken(range.getEnd()),
3215 ")"));
3216 }
3217 return;
3218 }
3219
3220 if (CCK == Sema::CCK_CStyleCast) {
3221 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003222 } else if (CCK == Sema::CCK_OtherCast) {
3223 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3224 std::string castCode = "(";
3225 castCode += bridgeKeyword;
3226 castCode += castType.getAsString();
3227 castCode += ")";
3228 SourceRange Range(NCE->getOperatorLoc(),
3229 NCE->getAngleBrackets().getEnd());
3230 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3231 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003232 } else {
3233 std::string castCode = "(";
3234 castCode += bridgeKeyword;
3235 castCode += castType.getAsString();
3236 castCode += ")";
3237 Expr *castedE = castExpr->IgnoreImpCasts();
3238 SourceRange range = castedE->getSourceRange();
3239 if (isa<ParenExpr>(castedE)) {
3240 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3241 castCode));
3242 } else {
3243 castCode += "(";
3244 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3245 castCode));
3246 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3247 S.PP.getLocForEndOfToken(range.getEnd()),
3248 ")"));
3249 }
3250 }
3251}
3252
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003253template <typename T>
3254static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3255 TypedefNameDecl *TDNDecl = TD->getDecl();
3256 QualType QT = TDNDecl->getUnderlyingType();
3257 if (QT->isPointerType()) {
3258 QT = QT->getPointeeType();
3259 if (const RecordType *RT = QT->getAs<RecordType>())
Fariborz Jahanian9af6a782014-06-11 19:10:46 +00003260 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
Aaron Ballman2084f8f2013-12-19 13:20:36 +00003261 return RD->getAttr<T>();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003262 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003263 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003264}
3265
3266static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3267 TypedefNameDecl *&TDNDecl) {
3268 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3269 TDNDecl = TD->getDecl();
3270 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3271 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3272 return ObjCBAttr;
3273 T = TDNDecl->getUnderlyingType();
3274 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003275 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003276}
3277
John McCall4124c492011-10-17 18:40:02 +00003278static void
3279diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3280 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003281 Expr *castExpr, Expr *realCast,
3282 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003283 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003284 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003285 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00003286
John McCall4124c492011-10-17 18:40:02 +00003287 if (S.makeUnavailableInSystemHeader(loc,
John McCalle4fe2452011-10-01 01:01:08 +00003288 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCall31168b02011-06-15 23:02:42 +00003289 return;
John McCall4124c492011-10-17 18:40:02 +00003290
3291 QualType castExprType = castExpr->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003292 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003293 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3294 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3295 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
Fariborz Jahanian1ad83a32014-06-18 23:22:38 +00003296 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003297 return;
John McCall31168b02011-06-15 23:02:42 +00003298
John McCall640767f2011-06-17 06:50:50 +00003299 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003300 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003301 case ACTC_none:
3302 case ACTC_coreFoundation:
3303 case ACTC_voidPtr:
3304 srcKind = (castExprType->isPointerType() ? 1 : 0);
3305 break;
3306 case ACTC_retainable:
3307 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3308 break;
3309 case ACTC_indirectRetainable:
3310 srcKind = 4;
3311 break;
John McCall31168b02011-06-15 23:02:42 +00003312 }
3313
John McCall4124c492011-10-17 18:40:02 +00003314 // Check whether this could be fixed with a bridge cast.
3315 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3316 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003317
John McCall4124c492011-10-17 18:40:02 +00003318 // Bridge from an ARC type to a CF type.
3319 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003320
John McCall4124c492011-10-17 18:40:02 +00003321 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3322 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3323 << 2 // of C pointer type
3324 << castExprType
3325 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3326 << castType
3327 << castRange
3328 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003329 bool br = S.isKnownName("CFBridgingRelease");
Jordan Rose4502b532012-07-31 01:07:43 +00003330 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003331 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003332 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003333 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003334 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003335 DiagnosticBuilder DiagB =
3336 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3337 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Craig Topperc3ec1492014-05-26 06:22:03 +00003338
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003339 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003340 castType, castExpr, realCast, "__bridge ",
3341 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003342 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003343 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003344 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003345 DiagnosticBuilder DiagB =
3346 (CCK == Sema::CCK_OtherCast && !br) ?
3347 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3348 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3349 diag::note_arc_bridge_transfer)
3350 << castExprType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003351
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003352 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003353 castType, castExpr, realCast, "__bridge_transfer ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003354 br ? "CFBridgingRelease" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003355 }
John McCall4124c492011-10-17 18:40:02 +00003356
3357 return;
3358 }
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003359
John McCall4124c492011-10-17 18:40:02 +00003360 // Bridge from a CF type to an ARC type.
3361 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003362 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003363 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3364 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3365 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3366 << castExprType
3367 << 2 // to C pointer type
3368 << castType
3369 << castRange
3370 << castExpr->getSourceRange();
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003371 ACCResult CreateRule =
3372 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003373 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003374 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003375 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003376 DiagnosticBuilder DiagB =
3377 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3378 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003379 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003380 castType, castExpr, realCast, "__bridge ",
3381 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003382 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003383 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003384 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003385 DiagnosticBuilder DiagB =
3386 (CCK == Sema::CCK_OtherCast && !br) ?
3387 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3388 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3389 diag::note_arc_bridge_retained)
3390 << castType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003391
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003392 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003393 castType, castExpr, realCast, "__bridge_retained ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003394 br ? "CFBridgingRetain" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003395 }
John McCall4124c492011-10-17 18:40:02 +00003396
3397 return;
John McCall31168b02011-06-15 23:02:42 +00003398 }
3399
John McCall4124c492011-10-17 18:40:02 +00003400 S.Diag(loc, diag::err_arc_mismatched_cast)
3401 << (CCK != Sema::CCK_ImplicitConversion)
3402 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003403 << castRange << castExpr->getSourceRange();
3404}
3405
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003406template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003407static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3408 bool &HadTheAttribute, bool warn) {
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003409 QualType T = castExpr->getType();
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003410 HadTheAttribute = false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003411 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3412 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003413 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003414 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003415 HadTheAttribute = true;
Fariborz Jahanianc9e266b2014-12-11 22:56:26 +00003416 if (Parm->isStr("id"))
3417 return true;
3418
Craig Topperc3ec1492014-05-26 06:22:03 +00003419 NamedDecl *Target = nullptr;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003420 // Check for an existing type with this name.
3421 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3422 Sema::LookupOrdinaryName);
3423 if (S.LookupName(R, S.TUScope)) {
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003424 Target = R.getFoundDecl();
3425 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3426 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3427 if (const ObjCObjectPointerType *InterfacePointerType =
3428 castType->getAsObjCInterfacePointerType()) {
3429 ObjCInterfaceDecl *CastClass
3430 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003431 if ((CastClass == ExprClass) ||
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003432 (CastClass && ExprClass->isSuperClassOf(CastClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003433 return true;
3434 if (warn)
3435 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3436 << T << Target->getName() << castType->getPointeeType();
3437 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003438 } else if (castType->isObjCIdType() ||
3439 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3440 castType, ExprClass)))
3441 // ok to cast to 'id'.
3442 // casting to id<p-list> is ok if bridge type adopts all of
3443 // p-list protocols.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003444 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003445 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003446 if (warn) {
3447 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3448 << T << Target->getName() << castType;
3449 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3450 S.Diag(Target->getLocStart(), diag::note_declared_at);
3451 }
3452 return false;
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003453 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003454 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003455 }
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003456 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
Aaron Ballmanc0550742014-01-03 02:07:43 +00003457 << castExpr->getType() << Parm;
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003458 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3459 if (Target)
3460 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003461 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003462 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003463 return false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003464 }
3465 T = TDNDecl->getUnderlyingType();
3466 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003467 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003468}
3469
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003470template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003471static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3472 bool &HadTheAttribute, bool warn) {
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003473 QualType T = castType;
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003474 HadTheAttribute = false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003475 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3476 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003477 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003478 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003479 HadTheAttribute = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003480 NamedDecl *Target = nullptr;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003481 // Check for an existing type with this name.
3482 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3483 Sema::LookupOrdinaryName);
3484 if (S.LookupName(R, S.TUScope)) {
3485 Target = R.getFoundDecl();
3486 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3487 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3488 if (const ObjCObjectPointerType *InterfacePointerType =
3489 castExpr->getType()->getAsObjCInterfacePointerType()) {
3490 ObjCInterfaceDecl *ExprClass
3491 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003492 if ((CastClass == ExprClass) ||
3493 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003494 return true;
3495 if (warn) {
3496 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3497 << castExpr->getType()->getPointeeType() << T;
3498 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3499 }
3500 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003501 } else if (castExpr->getType()->isObjCIdType() ||
3502 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3503 castExpr->getType(), CastClass)))
3504 // ok to cast an 'id' expression to a CFtype.
3505 // ok to cast an 'id<plist>' expression to CFtype provided plist
3506 // adopts all of CFtype's ObjetiveC's class plist.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003507 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003508 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003509 if (warn) {
3510 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3511 << castExpr->getType() << castType;
3512 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3513 S.Diag(Target->getLocStart(), diag::note_declared_at);
3514 }
3515 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003516 }
3517 }
3518 }
3519 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3520 << castExpr->getType() << castType;
3521 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3522 if (Target)
3523 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003524 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003525 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003526 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003527 }
3528 T = TDNDecl->getUnderlyingType();
3529 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003530 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003531}
3532
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003533void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003534 if (!getLangOpts().ObjC1)
3535 return;
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003536 // warn in presence of __bridge casting to or from a toll free bridge cast.
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003537 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3538 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003539 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003540 bool HasObjCBridgeAttr;
3541 bool ObjCBridgeAttrWillNotWarn =
3542 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3543 false);
3544 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3545 return;
3546 bool HasObjCBridgeMutableAttr;
3547 bool ObjCBridgeMutableAttrWillNotWarn =
3548 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3549 HasObjCBridgeMutableAttr, false);
3550 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3551 return;
3552
3553 if (HasObjCBridgeAttr)
3554 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3555 true);
3556 else if (HasObjCBridgeMutableAttr)
3557 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3558 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003559 }
3560 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003561 bool HasObjCBridgeAttr;
3562 bool ObjCBridgeAttrWillNotWarn =
3563 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3564 false);
3565 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3566 return;
3567 bool HasObjCBridgeMutableAttr;
3568 bool ObjCBridgeMutableAttrWillNotWarn =
3569 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3570 HasObjCBridgeMutableAttr, false);
3571 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3572 return;
3573
3574 if (HasObjCBridgeAttr)
3575 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3576 true);
3577 else if (HasObjCBridgeMutableAttr)
3578 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3579 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003580 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003581}
3582
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003583void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3584 QualType SrcType = castExpr->getType();
3585 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3586 if (PRE->isExplicitProperty()) {
3587 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3588 SrcType = PDecl->getType();
3589 }
3590 else if (PRE->isImplicitProperty()) {
3591 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3592 SrcType = Getter->getReturnType();
3593
3594 }
3595 }
3596
3597 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3598 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3599 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3600 return;
3601 CheckObjCBridgeRelatedConversions(castExpr->getLocStart(),
3602 castType, SrcType, castExpr);
3603 return;
3604}
3605
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00003606bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3607 CastKind &Kind) {
3608 if (!getLangOpts().ObjC1)
3609 return false;
3610 ARCConversionTypeClass exprACTC =
3611 classifyTypeForARCConversion(castExpr->getType());
3612 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3613 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3614 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3615 CheckTollFreeBridgeCast(castType, castExpr);
3616 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3617 : CK_CPointerToObjCPointerCast;
3618 return true;
3619 }
3620 return false;
3621}
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003622
3623bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3624 QualType DestType, QualType SrcType,
3625 ObjCInterfaceDecl *&RelatedClass,
3626 ObjCMethodDecl *&ClassMethod,
3627 ObjCMethodDecl *&InstanceMethod,
3628 TypedefNameDecl *&TDNDecl,
3629 bool CfToNs) {
3630 QualType T = CfToNs ? SrcType : DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003631 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3632 if (!ObjCBAttr)
3633 return false;
3634
3635 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3636 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3637 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3638 if (!RCId)
3639 return false;
Craig Topperc3ec1492014-05-26 06:22:03 +00003640 NamedDecl *Target = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003641 // Check for an existing type with this name.
3642 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3643 Sema::LookupOrdinaryName);
3644 if (!LookupName(R, TUScope)) {
3645 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003646 << SrcType << DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003647 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3648 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003649 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003650 Target = R.getFoundDecl();
3651 if (Target && isa<ObjCInterfaceDecl>(Target))
3652 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3653 else {
3654 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3655 << SrcType << DestType;
3656 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3657 if (Target)
3658 Diag(Target->getLocStart(), diag::note_declared_at);
3659 return false;
3660 }
3661
3662 // Check for an existing class method with the given selector name.
3663 if (CfToNs && CMId) {
3664 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3665 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3666 if (!ClassMethod) {
3667 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003668 << SrcType << DestType << Sel << false;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003669 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3670 return false;
3671 }
3672 }
3673
3674 // Check for an existing instance method with the given selector name.
3675 if (!CfToNs && IMId) {
3676 Selector Sel = Context.Selectors.getNullarySelector(IMId);
3677 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3678 if (!InstanceMethod) {
3679 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003680 << SrcType << DestType << Sel << true;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003681 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3682 return false;
3683 }
3684 }
3685 return true;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003686}
3687
3688bool
3689Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003690 QualType DestType, QualType SrcType,
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003691 Expr *&SrcExpr) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003692 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3693 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3694 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3695 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3696 if (!CfToNs && !NsToCf)
3697 return false;
3698
3699 ObjCInterfaceDecl *RelatedClass;
Craig Topperc3ec1492014-05-26 06:22:03 +00003700 ObjCMethodDecl *ClassMethod = nullptr;
3701 ObjCMethodDecl *InstanceMethod = nullptr;
3702 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003703 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
3704 ClassMethod, InstanceMethod, TDNDecl, CfToNs))
3705 return false;
3706
3707 if (CfToNs) {
3708 // Implicit conversion from CF to ObjC object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003709 if (ClassMethod) {
3710 std::string ExpressionString = "[";
3711 ExpressionString += RelatedClass->getNameAsString();
3712 ExpressionString += " ";
3713 ExpressionString += ClassMethod->getSelector().getAsString();
3714 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3715 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003716 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003717 << SrcType << DestType << ClassMethod->getSelector() << false
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003718 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3719 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003720 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3721 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3722
3723 QualType receiverType =
3724 Context.getObjCInterfaceType(RelatedClass);
3725 // Argument.
3726 Expr *args[] = { SrcExpr };
3727 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
3728 ClassMethod->getLocation(),
3729 ClassMethod->getSelector(), ClassMethod,
3730 MultiExprArg(args, 1));
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003731 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003732 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003733 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003734 }
3735 else {
3736 // Implicit conversion from ObjC type to CF object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003737 if (InstanceMethod) {
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003738 std::string ExpressionString;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003739 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003740 if (InstanceMethod->isPropertyAccessor())
3741 if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
3742 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
3743 ExpressionString = ".";
3744 ExpressionString += PDecl->getNameAsString();
3745 Diag(Loc, diag::err_objc_bridged_related_known_method)
3746 << SrcType << DestType << InstanceMethod->getSelector() << true
3747 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3748 }
3749 if (ExpressionString.empty()) {
3750 // Provide a fixit: [ObjectExpr InstanceMethod]
3751 ExpressionString = " ";
3752 ExpressionString += InstanceMethod->getSelector().getAsString();
3753 ExpressionString += "]";
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003754
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003755 Diag(Loc, diag::err_objc_bridged_related_known_method)
3756 << SrcType << DestType << InstanceMethod->getSelector() << true
3757 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3758 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3759 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003760 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3761 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3762
3763 ExprResult msg =
3764 BuildInstanceMessageImplicit(SrcExpr, SrcType,
3765 InstanceMethod->getLocation(),
3766 InstanceMethod->getSelector(),
3767 InstanceMethod, None);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003768 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003769 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003770 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003771 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003772 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003773}
3774
John McCall4124c492011-10-17 18:40:02 +00003775Sema::ARCConversionResult
3776Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003777 Expr *&castExpr, CheckedConversionKind CCK,
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00003778 bool DiagnoseCFAudited,
3779 BinaryOperatorKind Opc) {
John McCall4124c492011-10-17 18:40:02 +00003780 QualType castExprType = castExpr->getType();
3781
3782 // For the purposes of the classification, we assume reference types
3783 // will bind to temporaries.
3784 QualType effCastType = castType;
3785 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3786 effCastType = ref->getPointeeType();
3787
3788 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3789 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003790 if (exprACTC == castACTC) {
3791 // check for viablity and report error if casting an rvalue to a
3792 // life-time qualifier.
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003793 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003794 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003795 (castType != castExprType)) {
3796 const Type *DT = castType.getTypePtr();
3797 QualType QDT = castType;
3798 // We desugar some types but not others. We ignore those
3799 // that cannot happen in a cast; i.e. auto, and those which
3800 // should not be de-sugared; i.e typedef.
3801 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3802 QDT = PT->desugar();
3803 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3804 QDT = TP->desugar();
3805 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3806 QDT = AT->desugar();
3807 if (QDT != castType &&
3808 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3809 SourceLocation loc =
3810 (castRange.isValid() ? castRange.getBegin()
3811 : castExpr->getExprLoc());
3812 Diag(loc, diag::err_arc_nolifetime_behavior);
3813 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003814 }
3815 return ACR_okay;
3816 }
3817
John McCall4124c492011-10-17 18:40:02 +00003818 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
3819
3820 // Allow all of these types to be cast to integer types (but not
3821 // vice-versa).
3822 if (castACTC == ACTC_none && castType->isIntegralType(Context))
3823 return ACR_okay;
3824
3825 // Allow casts between pointers to lifetime types (e.g., __strong id*)
3826 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
3827 // must be explicit.
3828 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
3829 return ACR_okay;
3830 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
3831 CCK != CCK_ImplicitConversion)
3832 return ACR_okay;
3833
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003834 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00003835 // For invalid casts, fall through.
3836 case ACC_invalid:
3837 break;
3838
3839 // Do nothing for both bottom and +0.
3840 case ACC_bottom:
3841 case ACC_plusZero:
3842 return ACR_okay;
3843
3844 // If the result is +1, consume it here.
3845 case ACC_plusOne:
3846 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3847 CK_ARCConsumeObject, castExpr,
Craig Topperc3ec1492014-05-26 06:22:03 +00003848 nullptr, VK_RValue);
John McCall4124c492011-10-17 18:40:02 +00003849 ExprNeedsCleanups = true;
3850 return ACR_okay;
3851 }
3852
3853 // If this is a non-implicit cast from id or block type to a
3854 // CoreFoundation type, delay complaining in case the cast is used
3855 // in an acceptable context.
3856 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3857 CCK != CCK_ImplicitConversion)
3858 return ACR_unbridged;
3859
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003860 // Do not issue bridge cast" diagnostic when implicit casting a cstring
3861 // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
3862 // suitable fix-it.
Fariborz Jahanian283bf892013-12-18 21:04:43 +00003863 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
3864 ConversionToObjCStringLiteralCheck(castType, castExpr))
3865 return ACR_okay;
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003866
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003867 // Do not issue "bridge cast" diagnostic when implicit casting
3868 // a retainable object to a CF type parameter belonging to an audited
3869 // CF API function. Let caller issue a normal type mismatched diagnostic
3870 // instead.
3871 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
3872 castACTC != ACTC_coreFoundation)
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00003873 if (!(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
3874 (Opc == BO_NE || Opc == BO_EQ)))
3875 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3876 castExpr, castExpr, exprACTC, CCK);
John McCall4124c492011-10-17 18:40:02 +00003877 return ACR_okay;
3878}
3879
3880/// Given that we saw an expression with the ARCUnbridgedCastTy
3881/// placeholder type, complain bitterly.
3882void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3883 // We expect the spurious ImplicitCastExpr to already have been stripped.
3884 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3885 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3886
3887 SourceRange castRange;
3888 QualType castType;
3889 CheckedConversionKind CCK;
3890
3891 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3892 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3893 castType = cast->getTypeAsWritten();
3894 CCK = CCK_CStyleCast;
3895 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3896 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3897 castType = cast->getTypeAsWritten();
3898 CCK = CCK_OtherCast;
3899 } else {
3900 castType = cast->getType();
3901 CCK = CCK_ImplicitConversion;
3902 }
3903
3904 ARCConversionTypeClass castACTC =
3905 classifyTypeForARCConversion(castType.getNonReferenceType());
3906
3907 Expr *castExpr = realCast->getSubExpr();
3908 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3909
3910 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003911 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00003912}
3913
3914/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3915/// type, remove the placeholder cast.
3916Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3917 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3918
3919 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3920 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3921 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3922 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3923 assert(uo->getOpcode() == UO_Extension);
3924 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3925 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3926 sub->getValueKind(), sub->getObjectKind(),
3927 uo->getOperatorLoc());
3928 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3929 assert(!gse->isResultDependent());
3930
3931 unsigned n = gse->getNumAssocs();
3932 SmallVector<Expr*, 4> subExprs(n);
3933 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3934 for (unsigned i = 0; i != n; ++i) {
3935 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3936 Expr *sub = gse->getAssocExpr(i);
3937 if (i == gse->getResultIndex())
3938 sub = stripARCUnbridgedCast(sub);
3939 subExprs[i] = sub;
3940 }
3941
3942 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3943 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003944 subTypes, subExprs,
3945 gse->getDefaultLoc(),
John McCall4124c492011-10-17 18:40:02 +00003946 gse->getRParenLoc(),
3947 gse->containsUnexpandedParameterPack(),
3948 gse->getResultIndex());
3949 } else {
3950 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3951 return cast<ImplicitCastExpr>(e)->getSubExpr();
3952 }
3953}
3954
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003955bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3956 QualType exprType) {
3957 QualType canCastType =
3958 Context.getCanonicalType(castType).getUnqualifiedType();
3959 QualType canExprType =
3960 Context.getCanonicalType(exprType).getUnqualifiedType();
3961 if (isa<ObjCObjectPointerType>(canCastType) &&
3962 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3963 canExprType->isObjCObjectPointerType()) {
3964 if (const ObjCObjectPointerType *ObjT =
3965 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00003966 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
3967 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003968 }
3969 return true;
3970}
3971
John McCall4db5c3c2011-07-07 06:58:02 +00003972/// Look for an ObjCReclaimReturnedObject cast and destroy it.
3973static Expr *maybeUndoReclaimObject(Expr *e) {
3974 // For now, we just undo operands that are *immediately* reclaim
3975 // expressions, which prevents the vast majority of potential
3976 // problems here. To catch them all, we'd need to rebuild arbitrary
3977 // value-propagating subexpressions --- we can't reliably rebuild
3978 // in-place because of expression sharing.
3979 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall2d637d22011-09-10 06:18:15 +00003980 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall4db5c3c2011-07-07 06:58:02 +00003981 return ice->getSubExpr();
3982
3983 return e;
3984}
3985
John McCall31168b02011-06-15 23:02:42 +00003986ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3987 ObjCBridgeCastKind Kind,
3988 SourceLocation BridgeKeywordLoc,
3989 TypeSourceInfo *TSInfo,
3990 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00003991 ExprResult SubResult = UsualUnaryConversions(SubExpr);
3992 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003993 SubExpr = SubResult.get();
John McCalleb075542011-08-26 00:48:42 +00003994
John McCall31168b02011-06-15 23:02:42 +00003995 QualType T = TSInfo->getType();
3996 QualType FromType = SubExpr->getType();
3997
John McCall9320b872011-09-09 05:25:32 +00003998 CastKind CK;
3999
John McCall31168b02011-06-15 23:02:42 +00004000 bool MustConsume = false;
4001 if (T->isDependentType() || SubExpr->isTypeDependent()) {
4002 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00004003 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00004004 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
4005 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00004006 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4007 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00004008 switch (Kind) {
4009 case OBC_Bridge:
4010 break;
4011
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004012 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004013 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00004014 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4015 << 2
4016 << FromType
4017 << (T->isBlockPointerType()? 1 : 0)
4018 << T
4019 << SubExpr->getSourceRange()
4020 << Kind;
4021 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4022 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4023 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004024 << FromType << br
John McCall31168b02011-06-15 23:02:42 +00004025 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004026 br ? "CFBridgingRelease "
4027 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00004028
4029 Kind = OBC_Bridge;
4030 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004031 }
John McCall31168b02011-06-15 23:02:42 +00004032
4033 case OBC_BridgeTransfer:
4034 // We must consume the Objective-C object produced by the cast.
4035 MustConsume = true;
4036 break;
4037 }
4038 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4039 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00004040 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00004041 switch (Kind) {
Fariborz Jahanian214567c2014-10-28 17:26:21 +00004042 case OBC_Bridge:
4043 // Reclaiming a value that's going to be __bridge-casted to CF
4044 // is very dangerous, so we don't do it.
4045 SubExpr = maybeUndoReclaimObject(SubExpr);
4046 break;
John McCall31168b02011-06-15 23:02:42 +00004047
4048 case OBC_BridgeRetained:
4049 // Produce the object before casting it.
4050 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00004051 CK_ARCProduceObject,
Craig Topperc3ec1492014-05-26 06:22:03 +00004052 SubExpr, nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004053 break;
4054
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004055 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004056 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00004057 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4058 << (FromType->isBlockPointerType()? 1 : 0)
4059 << FromType
4060 << 2
4061 << T
4062 << SubExpr->getSourceRange()
4063 << Kind;
4064
4065 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4066 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4067 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004068 << T << br
4069 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4070 br ? "CFBridgingRetain " : "__bridge_retained");
John McCall31168b02011-06-15 23:02:42 +00004071
4072 Kind = OBC_Bridge;
4073 break;
4074 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004075 }
John McCall31168b02011-06-15 23:02:42 +00004076 } else {
4077 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4078 << FromType << T << Kind
4079 << SubExpr->getSourceRange()
4080 << TSInfo->getTypeLoc().getSourceRange();
4081 return ExprError();
4082 }
4083
John McCall9320b872011-09-09 05:25:32 +00004084 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00004085 BridgeKeywordLoc,
4086 TSInfo, SubExpr);
4087
4088 if (MustConsume) {
4089 ExprNeedsCleanups = true;
John McCall2d637d22011-09-10 06:18:15 +00004090 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
Craig Topperc3ec1492014-05-26 06:22:03 +00004091 nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004092 }
4093
4094 return Result;
4095}
4096
4097ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4098 SourceLocation LParenLoc,
4099 ObjCBridgeCastKind Kind,
4100 SourceLocation BridgeKeywordLoc,
4101 ParsedType Type,
4102 SourceLocation RParenLoc,
4103 Expr *SubExpr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004104 TypeSourceInfo *TSInfo = nullptr;
John McCall31168b02011-06-15 23:02:42 +00004105 QualType T = GetTypeFromParser(Type, &TSInfo);
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00004106 if (Kind == OBC_Bridge)
4107 CheckTollFreeBridgeCast(T, SubExpr);
John McCall31168b02011-06-15 23:02:42 +00004108 if (!TSInfo)
4109 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4110 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
4111 SubExpr);
4112}