blob: 99905bed34217c117347dc1db7231c58f74f4385 [file] [log] [blame]
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for Objective-C expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnera3fc41d2008-01-04 22:32:30 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
Steve Naroff021ca182008-05-29 21:12:08 +000017#include "clang/AST/ExprObjC.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor0c78ad92010-04-21 19:57:20 +000019#include "clang/AST/TypeLoc.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
21#include "clang/Edit/Commit.h"
22#include "clang/Edit/Rewriters.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000023#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/Initialization.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/Scope.h"
27#include "clang/Sema/ScopeInfo.h"
28#include "llvm/ADT/SmallString.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000029
Chris Lattnera3fc41d2008-01-04 22:32:30 +000030using namespace clang;
John McCall5f2d5562011-02-03 09:00:02 +000031using namespace sema;
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +000032using llvm::makeArrayRef;
Chris Lattnera3fc41d2008-01-04 22:32:30 +000033
John McCallfaf5fb42010-08-26 23:41:50 +000034ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
35 Expr **strings,
36 unsigned NumStrings) {
Chris Lattner163ffd22009-02-18 06:48:40 +000037 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
38
Chris Lattnerd7670d92009-02-18 06:13:04 +000039 // Most ObjC strings are formed out of a single piece. However, we *can*
40 // have strings formed out of multiple @ strings with multiple pptokens in
41 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
42 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner163ffd22009-02-18 06:48:40 +000043 StringLiteral *S = Strings[0];
Mike Stump11289f42009-09-09 15:08:12 +000044
Chris Lattnerd7670d92009-02-18 06:13:04 +000045 // If we have a multi-part string, merge it all together.
46 if (NumStrings != 1) {
Chris Lattnera3fc41d2008-01-04 22:32:30 +000047 // Concatenate objc strings.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000048 SmallString<128> StrBuf;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000049 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump11289f42009-09-09 15:08:12 +000050
Chris Lattner630970d2009-02-18 05:49:11 +000051 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner163ffd22009-02-18 06:48:40 +000052 S = Strings[i];
Mike Stump11289f42009-09-09 15:08:12 +000053
Douglas Gregorfb65e592011-07-27 05:40:30 +000054 // ObjC strings can't be wide or UTF.
55 if (!S->isAscii()) {
Chris Lattnerd7670d92009-02-18 06:13:04 +000056 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
57 << S->getSourceRange();
58 return true;
59 }
Mike Stump11289f42009-09-09 15:08:12 +000060
Benjamin Kramer35b077e2010-08-17 12:54:38 +000061 // Append the string.
62 StrBuf += S->getString();
Mike Stump11289f42009-09-09 15:08:12 +000063
Chris Lattner163ffd22009-02-18 06:48:40 +000064 // Get the locations of the string tokens.
65 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000066 }
Mike Stump11289f42009-09-09 15:08:12 +000067
Chris Lattner163ffd22009-02-18 06:48:40 +000068 // Create the aggregate string with the appropriate content and location
69 // information.
Benjamin Kramercdac7612014-02-25 12:26:20 +000070 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
71 assert(CAT && "String literal not of constant array type!");
72 QualType StrTy = Context.getConstantArrayType(
73 CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1),
74 CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
75 S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
76 /*Pascal=*/false, StrTy, &StrLocs[0],
77 StrLocs.size());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000078 }
Ted Kremeneke65b0862012-03-06 20:05:56 +000079
80 return BuildObjCStringLiteral(AtLocs[0], S);
81}
Mike Stump11289f42009-09-09 15:08:12 +000082
Ted Kremeneke65b0862012-03-06 20:05:56 +000083ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
Chris Lattner6436fb62009-02-18 06:01:06 +000084 // Verify that this composite string is acceptable for ObjC strings.
85 if (CheckObjCString(S))
Chris Lattnera3fc41d2008-01-04 22:32:30 +000086 return true;
Chris Lattnerfffd6a72009-02-18 06:06:56 +000087
88 // Initialize the constant string interface lazily. This assumes
Steve Naroff54e59452009-04-07 14:18:33 +000089 // the NSString interface is seen in this translation unit. Note: We
90 // don't use NSConstantString, since the runtime team considers this
91 // interface private (even though it appears in the header files).
Chris Lattnerfffd6a72009-02-18 06:06:56 +000092 QualType Ty = Context.getObjCConstantStringInterface();
93 if (!Ty.isNull()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +000094 Ty = Context.getObjCObjectPointerType(Ty);
David Blaikiebbafb8a2012-03-11 07:00:24 +000095 } else if (getLangOpts().NoConstantCFStrings) {
Craig Topperc3ec1492014-05-26 06:22:03 +000096 IdentifierInfo *NSIdent=nullptr;
David Blaikiebbafb8a2012-03-11 07:00:24 +000097 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +000098
99 if (StringClass.empty())
100 NSIdent = &Context.Idents.get("NSConstantString");
101 else
102 NSIdent = &Context.Idents.get(StringClass);
103
Ted Kremeneke65b0862012-03-06 20:05:56 +0000104 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Fariborz Jahanian07317632010-04-23 23:19:04 +0000105 LookupOrdinaryName);
106 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
107 Context.setObjCConstantStringInterface(StrIF);
108 Ty = Context.getObjCConstantStringInterface();
109 Ty = Context.getObjCObjectPointerType(Ty);
110 } else {
111 // If there is no NSConstantString interface defined then treat this
112 // as error and recover from it.
113 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
114 << S->getSourceRange();
115 Ty = Context.getObjCIdType();
116 }
Chris Lattner091f6982008-06-21 21:44:18 +0000117 } else {
Patrick Beard0caa3942012-04-19 00:25:12 +0000118 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000119 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000120 LookupOrdinaryName);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000121 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
122 Context.setObjCConstantStringInterface(StrIF);
123 Ty = Context.getObjCConstantStringInterface();
Steve Naroff7cae42b2009-07-10 23:34:53 +0000124 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000125 } else {
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000126 // If there is no NSString interface defined, implicitly declare
127 // a @class NSString; and use that instead. This is to make sure
128 // type of an NSString literal is represented correctly, instead of
129 // being an 'id' type.
130 Ty = Context.getObjCNSStringType();
131 if (Ty.isNull()) {
132 ObjCInterfaceDecl *NSStringIDecl =
133 ObjCInterfaceDecl::Create (Context,
134 Context.getTranslationUnitDecl(),
135 SourceLocation(), NSIdent,
Craig Topperc3ec1492014-05-26 06:22:03 +0000136 nullptr, SourceLocation());
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000137 Ty = Context.getObjCInterfaceType(NSStringIDecl);
138 Context.setObjCNSStringType(Ty);
139 }
140 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000141 }
Chris Lattner091f6982008-06-21 21:44:18 +0000142 }
Mike Stump11289f42009-09-09 15:08:12 +0000143
Ted Kremeneke65b0862012-03-06 20:05:56 +0000144 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
145}
146
Jordy Rose08e500c2012-05-12 17:32:44 +0000147/// \brief Emits an error if the given method does not exist, or if the return
148/// type is not an Objective-C object.
149static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
150 const ObjCInterfaceDecl *Class,
151 Selector Sel, const ObjCMethodDecl *Method) {
152 if (!Method) {
153 // FIXME: Is there a better way to avoid quotes than using getName()?
154 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
155 return false;
156 }
157
158 // Make sure the return type is reasonable.
Alp Toker314cc812014-01-25 16:55:45 +0000159 QualType ReturnType = Method->getReturnType();
Jordy Rose08e500c2012-05-12 17:32:44 +0000160 if (!ReturnType->isObjCObjectPointerType()) {
161 S.Diag(Loc, diag::err_objc_literal_method_sig)
162 << Sel;
163 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
164 << ReturnType;
165 return false;
166 }
167
168 return true;
169}
170
Ted Kremeneke65b0862012-03-06 20:05:56 +0000171/// \brief Retrieve the NSNumber factory method that should be used to create
172/// an Objective-C literal for the given type.
173static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
Patrick Beard0caa3942012-04-19 00:25:12 +0000174 QualType NumberType,
175 bool isLiteral = false,
176 SourceRange R = SourceRange()) {
David Blaikie05785d12013-02-20 22:23:23 +0000177 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
178 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
179
Ted Kremeneke65b0862012-03-06 20:05:56 +0000180 if (!Kind) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000181 if (isLiteral) {
182 S.Diag(Loc, diag::err_invalid_nsnumber_type)
183 << NumberType << R;
184 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000185 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000186 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000187
Ted Kremeneke65b0862012-03-06 20:05:56 +0000188 // If we already looked up this method, we're done.
189 if (S.NSNumberLiteralMethods[*Kind])
190 return S.NSNumberLiteralMethods[*Kind];
191
192 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
193 /*Instance=*/false);
194
Patrick Beard0caa3942012-04-19 00:25:12 +0000195 ASTContext &CX = S.Context;
196
197 // Look up the NSNumber class, if we haven't done so already. It's cached
198 // in the Sema instance.
199 if (!S.NSNumberDecl) {
Jordy Roseaca01f92012-05-12 17:32:52 +0000200 IdentifierInfo *NSNumberId =
201 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber);
Patrick Beard0caa3942012-04-19 00:25:12 +0000202 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId,
203 Loc, Sema::LookupOrdinaryName);
204 S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
205 if (!S.NSNumberDecl) {
206 if (S.getLangOpts().DebuggerObjCLiteral) {
207 // Create a stub definition of NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000208 S.NSNumberDecl = ObjCInterfaceDecl::Create(CX,
209 CX.getTranslationUnitDecl(),
210 SourceLocation(), NSNumberId,
Craig Topperc3ec1492014-05-26 06:22:03 +0000211 nullptr, SourceLocation());
Patrick Beard0caa3942012-04-19 00:25:12 +0000212 } else {
213 // Otherwise, require a declaration of NSNumber.
214 S.Diag(Loc, diag::err_undeclared_nsnumber);
Craig Topperc3ec1492014-05-26 06:22:03 +0000215 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000216 }
217 } else if (!S.NSNumberDecl->hasDefinition()) {
218 S.Diag(Loc, diag::err_undeclared_nsnumber);
Craig Topperc3ec1492014-05-26 06:22:03 +0000219 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000220 }
221
222 // generate the pointer to NSNumber type.
Jordy Roseaca01f92012-05-12 17:32:52 +0000223 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
224 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000225 }
226
Ted Kremeneke65b0862012-03-06 20:05:56 +0000227 // Look for the appropriate method within NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000228 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000229 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000230 // create a stub definition this NSNumber factory method.
Craig Topperc3ec1492014-05-26 06:22:03 +0000231 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000232 Method =
233 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
234 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
235 /*isInstance=*/false, /*isVariadic=*/false,
236 /*isPropertyAccessor=*/false,
237 /*isImplicitlyDeclared=*/true,
238 /*isDefined=*/false, ObjCMethodDecl::Required,
239 /*HasRelatedResultType=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000240 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
241 SourceLocation(), SourceLocation(),
Patrick Beard0caa3942012-04-19 00:25:12 +0000242 &CX.Idents.get("value"),
Craig Topperc3ec1492014-05-26 06:22:03 +0000243 NumberType, /*TInfo=*/nullptr,
244 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000245 Method->setMethodParams(S.Context, value, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000246 }
247
Jordy Rose08e500c2012-05-12 17:32:44 +0000248 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
Craig Topperc3ec1492014-05-26 06:22:03 +0000249 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000250
251 // Note: if the parameter type is out-of-line, we'll catch it later in the
252 // implicit conversion.
253
254 S.NSNumberLiteralMethods[*Kind] = Method;
255 return Method;
256}
257
Patrick Beard0caa3942012-04-19 00:25:12 +0000258/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
259/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremeneke65b0862012-03-06 20:05:56 +0000260ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000261 // Determine the type of the literal.
262 QualType NumberType = Number->getType();
263 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
264 // In C, character literals have type 'int'. That's not the type we want
265 // to use to determine the Objective-c literal kind.
266 switch (Char->getKind()) {
267 case CharacterLiteral::Ascii:
268 NumberType = Context.CharTy;
269 break;
270
271 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000272 NumberType = Context.getWideCharType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000273 break;
274
275 case CharacterLiteral::UTF16:
276 NumberType = Context.Char16Ty;
277 break;
278
279 case CharacterLiteral::UTF32:
280 NumberType = Context.Char32Ty;
281 break;
282 }
283 }
284
Ted Kremeneke65b0862012-03-06 20:05:56 +0000285 // Look for the appropriate method within NSNumber.
286 // Construct the literal.
Patrick Beard2565c592012-05-01 21:47:19 +0000287 SourceRange NR(Number->getSourceRange());
Patrick Beard0caa3942012-04-19 00:25:12 +0000288 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
Patrick Beard2565c592012-05-01 21:47:19 +0000289 true, NR);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000290 if (!Method)
291 return ExprError();
292
293 // Convert the number to the type that the parameter expects.
Patrick Beard2565c592012-05-01 21:47:19 +0000294 ParmVarDecl *ParamDecl = Method->param_begin()[0];
295 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
296 ParamDecl);
297 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
298 SourceLocation(),
299 Owned(Number));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000300 if (ConvertedNumber.isInvalid())
301 return ExprError();
302 Number = ConvertedNumber.get();
303
Patrick Beard2565c592012-05-01 21:47:19 +0000304 // Use the effective source range of the literal, including the leading '@'.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000305 return MaybeBindToTemporary(
Patrick Beard2565c592012-05-01 21:47:19 +0000306 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
307 SourceRange(AtLoc, NR.getEnd())));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000308}
309
310ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
311 SourceLocation ValueLoc,
312 bool Value) {
313 ExprResult Inner;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000314 if (getLangOpts().CPlusPlus) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000315 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
316 } else {
317 // C doesn't actually have a way to represent literal values of type
318 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
319 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
320 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
321 CK_IntegralToBoolean);
322 }
323
324 return BuildObjCNumericLiteral(AtLoc, Inner.get());
325}
326
327/// \brief Check that the given expression is a valid element of an Objective-C
328/// collection literal.
329static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000330 QualType T,
331 bool ArrayLiteral = false) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000332 // If the expression is type-dependent, there's nothing for us to do.
333 if (Element->isTypeDependent())
334 return Element;
335
336 ExprResult Result = S.CheckPlaceholderExpr(Element);
337 if (Result.isInvalid())
338 return ExprError();
339 Element = Result.get();
340
341 // In C++, check for an implicit conversion to an Objective-C object pointer
342 // type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000343 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000344 InitializedEntity Entity
Jordy Roseaca01f92012-05-12 17:32:52 +0000345 = InitializedEntity::InitializeParameter(S.Context, T,
346 /*Consumed=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000347 InitializationKind Kind
Jordy Roseaca01f92012-05-12 17:32:52 +0000348 = InitializationKind::CreateCopy(Element->getLocStart(),
349 SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000350 InitializationSequence Seq(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000351 if (!Seq.Failed())
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000352 return Seq.Perform(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000353 }
354
355 Expr *OrigElement = Element;
356
357 // Perform lvalue-to-rvalue conversion.
358 Result = S.DefaultLvalueConversion(Element);
359 if (Result.isInvalid())
360 return ExprError();
361 Element = Result.get();
362
363 // Make sure that we have an Objective-C pointer type or block.
364 if (!Element->getType()->isObjCObjectPointerType() &&
365 !Element->getType()->isBlockPointerType()) {
366 bool Recovered = false;
367
368 // If this is potentially an Objective-C numeric literal, add the '@'.
369 if (isa<IntegerLiteral>(OrigElement) ||
370 isa<CharacterLiteral>(OrigElement) ||
371 isa<FloatingLiteral>(OrigElement) ||
372 isa<ObjCBoolLiteralExpr>(OrigElement) ||
373 isa<CXXBoolLiteralExpr>(OrigElement)) {
374 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
375 int Which = isa<CharacterLiteral>(OrigElement) ? 1
376 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
377 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
378 : 3;
379
380 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
381 << Which << OrigElement->getSourceRange()
382 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
383
384 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
385 OrigElement);
386 if (Result.isInvalid())
387 return ExprError();
388
389 Element = Result.get();
390 Recovered = true;
391 }
392 }
393 // If this is potentially an Objective-C string literal, add the '@'.
394 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
395 if (String->isAscii()) {
396 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
397 << 0 << OrigElement->getSourceRange()
398 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
399
400 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
401 if (Result.isInvalid())
402 return ExprError();
403
404 Element = Result.get();
405 Recovered = true;
406 }
407 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000408
Ted Kremeneke65b0862012-03-06 20:05:56 +0000409 if (!Recovered) {
410 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
411 << Element->getType();
412 return ExprError();
413 }
414 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000415 if (ArrayLiteral)
Ted Kremenek197fee42013-10-09 22:34:33 +0000416 if (ObjCStringLiteral *getString =
417 dyn_cast<ObjCStringLiteral>(OrigElement)) {
418 if (StringLiteral *SL = getString->getString()) {
419 unsigned numConcat = SL->getNumConcatenated();
420 if (numConcat > 1) {
421 // Only warn if the concatenated string doesn't come from a macro.
422 bool hasMacro = false;
423 for (unsigned i = 0; i < numConcat ; ++i)
424 if (SL->getStrTokenLoc(i).isMacroID()) {
425 hasMacro = true;
426 break;
427 }
428 if (!hasMacro)
429 S.Diag(Element->getLocStart(),
430 diag::warn_concatenated_nsarray_literal)
431 << Element->getType();
432 }
433 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000434 }
435
Ted Kremeneke65b0862012-03-06 20:05:56 +0000436 // Make sure that the element has the type that the container factory
437 // function expects.
438 return S.PerformCopyInitialization(
439 InitializedEntity::InitializeParameter(S.Context, T,
440 /*Consumed=*/false),
441 Element->getLocStart(), Element);
442}
443
Patrick Beard0caa3942012-04-19 00:25:12 +0000444ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
445 if (ValueExpr->isTypeDependent()) {
446 ObjCBoxedExpr *BoxedExpr =
Craig Topperc3ec1492014-05-26 06:22:03 +0000447 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
Patrick Beard0caa3942012-04-19 00:25:12 +0000448 return Owned(BoxedExpr);
449 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000450 ObjCMethodDecl *BoxingMethod = nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000451 QualType BoxedType;
452 // Convert the expression to an RValue, so we can check for pointer types...
453 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
454 if (RValue.isInvalid()) {
455 return ExprError();
456 }
457 ValueExpr = RValue.get();
Patrick Beard2565c592012-05-01 21:47:19 +0000458 QualType ValueType(ValueExpr->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +0000459 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
460 QualType PointeeType = PT->getPointeeType();
461 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
462
463 if (!NSStringDecl) {
464 IdentifierInfo *NSStringId =
465 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
466 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
467 SR.getBegin(), LookupOrdinaryName);
468 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
469 if (!NSStringDecl) {
470 if (getLangOpts().DebuggerObjCLiteral) {
471 // Support boxed expressions in the debugger w/o NSString declaration.
Jordy Roseaca01f92012-05-12 17:32:52 +0000472 DeclContext *TU = Context.getTranslationUnitDecl();
473 NSStringDecl = ObjCInterfaceDecl::Create(Context, TU,
474 SourceLocation(),
475 NSStringId,
Craig Topperc3ec1492014-05-26 06:22:03 +0000476 nullptr, SourceLocation());
Patrick Beard0caa3942012-04-19 00:25:12 +0000477 } else {
478 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
479 return ExprError();
480 }
481 } else if (!NSStringDecl->hasDefinition()) {
482 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
483 return ExprError();
484 }
485 assert(NSStringDecl && "NSStringDecl should not be NULL");
Jordy Roseaca01f92012-05-12 17:32:52 +0000486 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
487 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000488 }
489
490 if (!StringWithUTF8StringMethod) {
491 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
492 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
493
494 // Look for the appropriate method within NSString.
Jordy Rose08e500c2012-05-12 17:32:44 +0000495 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
496 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000497 // Debugger needs to work even if NSString hasn't been defined.
Craig Topperc3ec1492014-05-26 06:22:03 +0000498 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000499 ObjCMethodDecl *M = ObjCMethodDecl::Create(
500 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
501 NSStringPointer, ReturnTInfo, NSStringDecl,
502 /*isInstance=*/false, /*isVariadic=*/false,
503 /*isPropertyAccessor=*/false,
504 /*isImplicitlyDeclared=*/true,
505 /*isDefined=*/false, ObjCMethodDecl::Required,
506 /*HasRelatedResultType=*/false);
Jordy Roseaca01f92012-05-12 17:32:52 +0000507 QualType ConstCharType = Context.CharTy.withConst();
Patrick Beard0caa3942012-04-19 00:25:12 +0000508 ParmVarDecl *value =
509 ParmVarDecl::Create(Context, M,
510 SourceLocation(), SourceLocation(),
511 &Context.Idents.get("value"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000512 Context.getPointerType(ConstCharType),
Craig Topperc3ec1492014-05-26 06:22:03 +0000513 /*TInfo=*/nullptr,
514 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000515 M->setMethodParams(Context, value, None);
Jordy Rose08e500c2012-05-12 17:32:44 +0000516 BoxingMethod = M;
Patrick Beard0caa3942012-04-19 00:25:12 +0000517 }
Jordy Rose890f4572012-05-12 15:53:41 +0000518
Jordy Rose08e500c2012-05-12 17:32:44 +0000519 if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
520 stringWithUTF8String, BoxingMethod))
521 return ExprError();
522
523 StringWithUTF8StringMethod = BoxingMethod;
Patrick Beard0caa3942012-04-19 00:25:12 +0000524 }
525
526 BoxingMethod = StringWithUTF8StringMethod;
527 BoxedType = NSStringPointer;
528 }
Patrick Beard2565c592012-05-01 21:47:19 +0000529 } else if (ValueType->isBuiltinType()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000530 // The other types we support are numeric, char and BOOL/bool. We could also
531 // provide limited support for structure types, such as NSRange, NSRect, and
532 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
533 // for more details.
534
535 // Check for a top-level character literal.
536 if (const CharacterLiteral *Char =
537 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
538 // In C, character literals have type 'int'. That's not the type we want
539 // to use to determine the Objective-c literal kind.
540 switch (Char->getKind()) {
541 case CharacterLiteral::Ascii:
542 ValueType = Context.CharTy;
543 break;
544
545 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000546 ValueType = Context.getWideCharType();
Patrick Beard0caa3942012-04-19 00:25:12 +0000547 break;
548
549 case CharacterLiteral::UTF16:
550 ValueType = Context.Char16Ty;
551 break;
552
553 case CharacterLiteral::UTF32:
554 ValueType = Context.Char32Ty;
555 break;
556 }
557 }
558
559 // FIXME: Do I need to do anything special with BoolTy expressions?
560
561 // Look for the appropriate method within NSNumber.
562 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
563 BoxedType = NSNumberPointer;
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000564
565 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
566 if (!ET->getDecl()->isComplete()) {
567 Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type)
568 << ValueType << ValueExpr->getSourceRange();
569 return ExprError();
570 }
571
572 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(),
573 ET->getDecl()->getIntegerType());
574 BoxedType = NSNumberPointer;
Patrick Beard0caa3942012-04-19 00:25:12 +0000575 }
576
577 if (!BoxingMethod) {
578 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
579 << ValueType << ValueExpr->getSourceRange();
580 return ExprError();
581 }
582
583 // Convert the expression to the type that the parameter requires.
Patrick Beard2565c592012-05-01 21:47:19 +0000584 ParmVarDecl *ParamDecl = BoxingMethod->param_begin()[0];
585 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
586 ParamDecl);
587 ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
588 SourceLocation(),
589 Owned(ValueExpr));
Patrick Beard0caa3942012-04-19 00:25:12 +0000590 if (ConvertedValueExpr.isInvalid())
591 return ExprError();
592 ValueExpr = ConvertedValueExpr.get();
593
594 ObjCBoxedExpr *BoxedExpr =
595 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
596 BoxingMethod, SR);
597 return MaybeBindToTemporary(BoxedExpr);
598}
599
John McCallf2538342012-07-31 05:14:30 +0000600/// Build an ObjC subscript pseudo-object expression, given that
601/// that's supported by the runtime.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000602ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
603 Expr *IndexExpr,
604 ObjCMethodDecl *getterMethod,
605 ObjCMethodDecl *setterMethod) {
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +0000606 assert(!LangOpts.isSubscriptPointerArithmetic());
John McCall5fb5df92012-06-20 06:18:46 +0000607
John McCallf2538342012-07-31 05:14:30 +0000608 // We can't get dependent types here; our callers should have
609 // filtered them out.
610 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
611 "base or index cannot have dependent type here");
612
613 // Filter out placeholders in the index. In theory, overloads could
614 // be preserved here, although that might not actually work correctly.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000615 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
616 if (Result.isInvalid())
617 return ExprError();
618 IndexExpr = Result.get();
619
John McCallf2538342012-07-31 05:14:30 +0000620 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000621 Result = DefaultLvalueConversion(BaseExpr);
622 if (Result.isInvalid())
623 return ExprError();
624 BaseExpr = Result.get();
John McCallf2538342012-07-31 05:14:30 +0000625
626 // Build the pseudo-object expression.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000627 return Owned(ObjCSubscriptRefExpr::Create(Context,
628 BaseExpr,
629 IndexExpr,
630 Context.PseudoObjectTy,
631 getterMethod,
632 setterMethod, RB));
633
634}
635
636ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
637 // Look up the NSArray class, if we haven't done so already.
638 if (!NSArrayDecl) {
639 NamedDecl *IF = LookupSingleName(TUScope,
640 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
641 SR.getBegin(),
642 LookupOrdinaryName);
643 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000644 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000645 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
646 Context.getTranslationUnitDecl(),
647 SourceLocation(),
648 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
Craig Topperc3ec1492014-05-26 06:22:03 +0000649 nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000650
651 if (!NSArrayDecl) {
652 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
653 return ExprError();
654 }
655 }
656
657 // Find the arrayWithObjects:count: method, if we haven't done so already.
658 QualType IdT = Context.getObjCIdType();
659 if (!ArrayWithObjectsMethod) {
660 Selector
661 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
Jordy Rose08e500c2012-05-12 17:32:44 +0000662 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
663 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000664 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000665 Method = ObjCMethodDecl::Create(
666 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
667 Context.getTranslationUnitDecl(), false /*Instance*/,
668 false /*isVariadic*/,
669 /*isPropertyAccessor=*/false,
670 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
671 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000672 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000673 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000674 SourceLocation(),
675 SourceLocation(),
676 &Context.Idents.get("objects"),
677 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000678 /*TInfo=*/nullptr,
679 SC_None, nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000680 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000681 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000682 SourceLocation(),
683 SourceLocation(),
684 &Context.Idents.get("cnt"),
685 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000686 /*TInfo=*/nullptr, SC_None,
687 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000688 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000689 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000690 }
691
Jordy Rose08e500c2012-05-12 17:32:44 +0000692 if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000693 return ExprError();
Jordy Rose08e500c2012-05-12 17:32:44 +0000694
Jordy Rose4af44872012-05-12 17:32:56 +0000695 // Dig out the type that all elements should be converted to.
696 QualType T = Method->param_begin()[0]->getType();
697 const PointerType *PtrT = T->getAs<PointerType>();
698 if (!PtrT ||
699 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
700 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
701 << Sel;
702 Diag(Method->param_begin()[0]->getLocation(),
703 diag::note_objc_literal_method_param)
704 << 0 << T
705 << Context.getPointerType(IdT.withConst());
706 return ExprError();
707 }
708
709 // Check that the 'count' parameter is integral.
710 if (!Method->param_begin()[1]->getType()->isIntegerType()) {
711 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
712 << Sel;
713 Diag(Method->param_begin()[1]->getLocation(),
714 diag::note_objc_literal_method_param)
715 << 1
716 << Method->param_begin()[1]->getType()
717 << "integral";
718 return ExprError();
719 }
720
721 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rose08e500c2012-05-12 17:32:44 +0000722 ArrayWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000723 }
724
Jordy Rose4af44872012-05-12 17:32:56 +0000725 QualType ObjectsType = ArrayWithObjectsMethod->param_begin()[0]->getType();
726 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000727
728 // Check that each of the elements provided is valid in a collection literal,
729 // performing conversions as necessary.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000730 Expr **ElementsBuffer = Elements.data();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000731 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
732 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
733 ElementsBuffer[I],
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000734 RequiredType, true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000735 if (Converted.isInvalid())
736 return ExprError();
737
738 ElementsBuffer[I] = Converted.get();
739 }
740
741 QualType Ty
742 = Context.getObjCObjectPointerType(
743 Context.getObjCInterfaceType(NSArrayDecl));
744
745 return MaybeBindToTemporary(
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000746 ObjCArrayLiteral::Create(Context, Elements, Ty,
747 ArrayWithObjectsMethod, SR));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000748}
749
750ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
751 ObjCDictionaryElement *Elements,
752 unsigned NumElements) {
753 // Look up the NSDictionary class, if we haven't done so already.
754 if (!NSDictionaryDecl) {
755 NamedDecl *IF = LookupSingleName(TUScope,
756 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
757 SR.getBegin(), LookupOrdinaryName);
758 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000759 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000760 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
761 Context.getTranslationUnitDecl(),
762 SourceLocation(),
763 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
Craig Topperc3ec1492014-05-26 06:22:03 +0000764 nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000765
766 if (!NSDictionaryDecl) {
767 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
768 return ExprError();
769 }
770 }
771
772 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
773 // so already.
774 QualType IdT = Context.getObjCIdType();
775 if (!DictionaryWithObjectsMethod) {
776 Selector Sel = NSAPIObj->getNSDictionarySelector(
Jordy Roseaca01f92012-05-12 17:32:52 +0000777 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
Jordy Rose08e500c2012-05-12 17:32:44 +0000778 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
779 if (!Method && getLangOpts().DebuggerObjCLiteral) {
780 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000781 SourceLocation(), SourceLocation(), Sel,
782 IdT,
Craig Topperc3ec1492014-05-26 06:22:03 +0000783 nullptr /*TypeSourceInfo */,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000784 Context.getTranslationUnitDecl(),
785 false /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000786 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000787 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
788 ObjCMethodDecl::Required,
789 false);
790 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000791 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000792 SourceLocation(),
793 SourceLocation(),
794 &Context.Idents.get("objects"),
795 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000796 /*TInfo=*/nullptr, SC_None,
797 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000798 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000799 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000800 SourceLocation(),
801 SourceLocation(),
802 &Context.Idents.get("keys"),
803 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000804 /*TInfo=*/nullptr, SC_None,
805 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000806 Params.push_back(keys);
Jordy Rose08e500c2012-05-12 17:32:44 +0000807 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000808 SourceLocation(),
809 SourceLocation(),
810 &Context.Idents.get("cnt"),
811 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000812 /*TInfo=*/nullptr, SC_None,
813 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000814 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000815 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000816 }
817
Jordy Rose08e500c2012-05-12 17:32:44 +0000818 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
819 Method))
820 return ExprError();
821
Jordy Rose4af44872012-05-12 17:32:56 +0000822 // Dig out the type that all values should be converted to.
823 QualType ValueT = Method->param_begin()[0]->getType();
824 const PointerType *PtrValue = ValueT->getAs<PointerType>();
825 if (!PtrValue ||
826 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000827 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000828 << Sel;
829 Diag(Method->param_begin()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000830 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000831 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000832 << Context.getPointerType(IdT.withConst());
833 return ExprError();
834 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000835
Jordy Rose4af44872012-05-12 17:32:56 +0000836 // Dig out the type that all keys should be converted to.
837 QualType KeyT = Method->param_begin()[1]->getType();
838 const PointerType *PtrKey = KeyT->getAs<PointerType>();
839 if (!PtrKey ||
840 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
841 IdT)) {
842 bool err = true;
843 if (PtrKey) {
844 if (QIDNSCopying.isNull()) {
845 // key argument of selector is id<NSCopying>?
846 if (ObjCProtocolDecl *NSCopyingPDecl =
847 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
848 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
849 QIDNSCopying =
850 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
851 (ObjCProtocolDecl**) PQ,1);
852 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
853 }
854 }
855 if (!QIDNSCopying.isNull())
856 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
857 QIDNSCopying);
858 }
859
860 if (err) {
861 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
862 << Sel;
863 Diag(Method->param_begin()[1]->getLocation(),
864 diag::note_objc_literal_method_param)
865 << 1 << KeyT
866 << Context.getPointerType(IdT.withConst());
867 return ExprError();
868 }
869 }
870
871 // Check that the 'count' parameter is integral.
872 QualType CountType = Method->param_begin()[2]->getType();
873 if (!CountType->isIntegerType()) {
874 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
875 << Sel;
876 Diag(Method->param_begin()[2]->getLocation(),
877 diag::note_objc_literal_method_param)
878 << 2 << CountType
879 << "integral";
880 return ExprError();
881 }
882
883 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
884 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000885 }
886
Jordy Rose4af44872012-05-12 17:32:56 +0000887 QualType ValuesT = DictionaryWithObjectsMethod->param_begin()[0]->getType();
888 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
889 QualType KeysT = DictionaryWithObjectsMethod->param_begin()[1]->getType();
890 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
891
Ted Kremeneke65b0862012-03-06 20:05:56 +0000892 // Check that each of the keys and values provided is valid in a collection
893 // literal, performing conversions as necessary.
894 bool HasPackExpansions = false;
895 for (unsigned I = 0, N = NumElements; I != N; ++I) {
896 // Check the key.
897 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
898 KeyT);
899 if (Key.isInvalid())
900 return ExprError();
901
902 // Check the value.
903 ExprResult Value
904 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
905 if (Value.isInvalid())
906 return ExprError();
907
908 Elements[I].Key = Key.get();
909 Elements[I].Value = Value.get();
910
911 if (Elements[I].EllipsisLoc.isInvalid())
912 continue;
913
914 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
915 !Elements[I].Value->containsUnexpandedParameterPack()) {
916 Diag(Elements[I].EllipsisLoc,
917 diag::err_pack_expansion_without_parameter_packs)
918 << SourceRange(Elements[I].Key->getLocStart(),
919 Elements[I].Value->getLocEnd());
920 return ExprError();
921 }
922
923 HasPackExpansions = true;
924 }
925
926
927 QualType Ty
928 = Context.getObjCObjectPointerType(
Robert Wilhelm88e02492013-08-19 07:57:02 +0000929 Context.getObjCInterfaceType(NSDictionaryDecl));
930 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
931 Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty,
932 DictionaryWithObjectsMethod, SR));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000933}
934
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000935ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregorabd9e962010-04-20 15:39:42 +0000936 TypeSourceInfo *EncodedTypeInfo,
Anders Carlsson315d2292009-06-07 18:45:35 +0000937 SourceLocation RParenLoc) {
Douglas Gregorabd9e962010-04-20 15:39:42 +0000938 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlsson315d2292009-06-07 18:45:35 +0000939 QualType StrTy;
Mike Stump11289f42009-09-09 15:08:12 +0000940 if (EncodedType->isDependentType())
Anders Carlsson315d2292009-06-07 18:45:35 +0000941 StrTy = Context.DependentTy;
942 else {
Fariborz Jahaniand9bc6c32011-06-16 22:34:44 +0000943 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
944 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000945 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000946 diag::err_incomplete_type_objc_at_encode,
947 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000948 return ExprError();
949
Anders Carlsson315d2292009-06-07 18:45:35 +0000950 std::string Str;
951 Context.getObjCEncodingForType(EncodedType, Str);
952
953 // The type of @encode is the same as the type of the corresponding string,
954 // which is an array type.
955 StrTy = Context.CharTy;
956 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +0000957 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlsson315d2292009-06-07 18:45:35 +0000958 StrTy.addConst();
959 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
960 ArrayType::Normal, 0);
961 }
Mike Stump11289f42009-09-09 15:08:12 +0000962
Douglas Gregorabd9e962010-04-20 15:39:42 +0000963 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlsson315d2292009-06-07 18:45:35 +0000964}
965
John McCallfaf5fb42010-08-26 23:41:50 +0000966ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
967 SourceLocation EncodeLoc,
968 SourceLocation LParenLoc,
969 ParsedType ty,
970 SourceLocation RParenLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000971 // FIXME: Preserve type source info ?
Douglas Gregorabd9e962010-04-20 15:39:42 +0000972 TypeSourceInfo *TInfo;
973 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
974 if (!TInfo)
975 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
976 PP.getLocForEndOfToken(LParenLoc));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000977
Douglas Gregorabd9e962010-04-20 15:39:42 +0000978 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000979}
980
Fariborz Jahanian44be1542014-03-12 18:34:01 +0000981static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
982 SourceLocation AtLoc,
983 ObjCMethodDecl *Method,
984 ObjCMethodList &MethList) {
985 ObjCMethodList *M = &MethList;
986 bool Warned = false;
987 for (M = M->getNext(); M; M=M->getNext()) {
988 ObjCMethodDecl *MatchingMethodDecl = M->Method;
989 if (MatchingMethodDecl == Method ||
990 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
991 MatchingMethodDecl->getSelector() != Method->getSelector())
992 continue;
993 if (!S.MatchTwoMethodDeclarations(Method,
994 MatchingMethodDecl, Sema::MMS_loose)) {
995 if (!Warned) {
996 Warned = true;
997 S.Diag(AtLoc, diag::warning_multiple_selectors)
998 << Method->getSelector();
999 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1000 << Method->getDeclName();
1001 }
1002 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1003 << MatchingMethodDecl->getDeclName();
1004 }
1005 }
1006 return Warned;
1007}
1008
1009static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
1010 ObjCMethodDecl *Method) {
Fariborz Jahanian1c433292014-03-27 21:59:01 +00001011 if (S.Diags.getDiagnosticLevel(diag::warning_multiple_selectors,
1012 SourceLocation())
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001013 == DiagnosticsEngine::Ignored)
1014 return;
1015 bool Warned = false;
1016 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1017 e = S.MethodPool.end(); b != e; b++) {
1018 // first, instance methods
1019 ObjCMethodList &InstMethList = b->second.first;
1020 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc,
1021 Method, InstMethList))
1022 Warned = true;
1023
1024 // second, class methods
1025 ObjCMethodList &ClsMethList = b->second.second;
1026 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc,
1027 Method, ClsMethList) ||
1028 Warned)
1029 return;
1030 }
1031}
1032
John McCallfaf5fb42010-08-26 23:41:50 +00001033ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1034 SourceLocation AtLoc,
1035 SourceLocation SelLoc,
1036 SourceLocation LParenLoc,
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001037 SourceLocation RParenLoc) {
1038 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1039 SourceRange(LParenLoc, RParenLoc), false, false);
1040 if (!Method)
1041 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian0571d9b2009-06-16 16:25:00 +00001042 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00001043 if (!Method) {
1044 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1045 Selector MatchedSel = OM->getSelector();
1046 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1047 RParenLoc.getLocWithOffset(-1));
1048 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1049 << Sel << MatchedSel
1050 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1051
1052 } else
1053 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001054 } else
1055 DiagnoseMismatchedSelectors(*this, AtLoc, Method);
Fariborz Jahanian9a881012011-07-13 19:05:43 +00001056
Fariborz Jahanian65a78b52014-05-09 19:51:39 +00001057 if (Method &&
1058 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
1059 !getSourceManager().isInSystemHeader(Method->getLocation())) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001060 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
1061 = ReferencedSelectors.find(Sel);
1062 if (Pos == ReferencedSelectors.end())
1063 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian9a881012011-07-13 19:05:43 +00001064 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001065
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001066 // In ARC, forbid the user from using @selector for
John McCall31168b02011-06-15 23:02:42 +00001067 // retain/release/autorelease/dealloc/retainCount.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001068 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001069 switch (Sel.getMethodFamily()) {
1070 case OMF_retain:
1071 case OMF_release:
1072 case OMF_autorelease:
1073 case OMF_retainCount:
1074 case OMF_dealloc:
1075 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1076 Sel << SourceRange(LParenLoc, RParenLoc);
1077 break;
1078
1079 case OMF_None:
1080 case OMF_alloc:
1081 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00001082 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00001083 case OMF_init:
1084 case OMF_mutableCopy:
1085 case OMF_new:
1086 case OMF_self:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001087 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001088 break;
1089 }
1090 }
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001091 QualType Ty = Context.getObjCSelType();
Daniel Dunbar45858d22010-02-03 20:11:42 +00001092 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001093}
1094
John McCallfaf5fb42010-08-26 23:41:50 +00001095ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1096 SourceLocation AtLoc,
1097 SourceLocation ProtoLoc,
1098 SourceLocation LParenLoc,
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001099 SourceLocation ProtoIdLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00001100 SourceLocation RParenLoc) {
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001101 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001102 if (!PDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001103 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001104 return true;
1105 }
Mike Stump11289f42009-09-09 15:08:12 +00001106
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001107 QualType Ty = Context.getObjCProtoType();
1108 if (Ty.isNull())
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001109 return true;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001110 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001111 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001112}
1113
John McCall5f2d5562011-02-03 09:00:02 +00001114/// Try to capture an implicit reference to 'self'.
Eli Friedman24af8502012-02-03 22:47:37 +00001115ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1116 DeclContext *DC = getFunctionLevelDeclContext();
John McCall5f2d5562011-02-03 09:00:02 +00001117
1118 // If we're not in an ObjC method, error out. Note that, unlike the
1119 // C++ case, we don't require an instance method --- class methods
1120 // still have a 'self', and we really do still need to capture it!
1121 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1122 if (!method)
Craig Topperc3ec1492014-05-26 06:22:03 +00001123 return nullptr;
John McCall5f2d5562011-02-03 09:00:02 +00001124
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001125 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall5f2d5562011-02-03 09:00:02 +00001126
1127 return method;
1128}
1129
Douglas Gregor64910ca2011-09-09 20:05:21 +00001130static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1131 if (T == Context.getObjCInstanceType())
1132 return Context.getObjCIdType();
1133
1134 return T;
1135}
1136
Douglas Gregor33823722011-06-11 01:09:30 +00001137QualType Sema::getMessageSendResultType(QualType ReceiverType,
1138 ObjCMethodDecl *Method,
1139 bool isClassMessage, bool isSuperMessage) {
1140 assert(Method && "Must have a method");
1141 if (!Method->hasRelatedResultType())
1142 return Method->getSendResultType();
1143
1144 // If a method has a related return type:
1145 // - if the method found is an instance method, but the message send
1146 // was a class message send, T is the declared return type of the method
1147 // found
1148 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor64910ca2011-09-09 20:05:21 +00001149 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001150
1151 // - if the receiver is super, T is a pointer to the class of the
1152 // enclosing method definition
1153 if (isSuperMessage) {
1154 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1155 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1156 return Context.getObjCObjectPointerType(
1157 Context.getObjCInterfaceType(Class));
1158 }
1159
1160 // - if the receiver is the name of a class U, T is a pointer to U
1161 if (ReceiverType->getAs<ObjCInterfaceType>() ||
1162 ReceiverType->isObjCQualifiedInterfaceType())
1163 return Context.getObjCObjectPointerType(ReceiverType);
1164 // - if the receiver is of type Class or qualified Class type,
1165 // T is the declared return type of the method.
1166 if (ReceiverType->isObjCClassType() ||
1167 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor64910ca2011-09-09 20:05:21 +00001168 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001169
1170 // - if the receiver is id, qualified id, Class, or qualified Class, T
1171 // is the receiver type, otherwise
1172 // - T is the type of the receiver expression.
1173 return ReceiverType;
1174}
John McCall5f2d5562011-02-03 09:00:02 +00001175
John McCall5ec7e7d2013-03-19 07:04:25 +00001176/// Look for an ObjC method whose result type exactly matches the given type.
1177static const ObjCMethodDecl *
1178findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1179 QualType instancetype) {
Alp Toker314cc812014-01-25 16:55:45 +00001180 if (MD->getReturnType() == instancetype)
1181 return MD;
John McCall5ec7e7d2013-03-19 07:04:25 +00001182
1183 // For these purposes, a method in an @implementation overrides a
1184 // declaration in the @interface.
1185 if (const ObjCImplDecl *impl =
1186 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1187 const ObjCContainerDecl *iface;
1188 if (const ObjCCategoryImplDecl *catImpl =
1189 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1190 iface = catImpl->getCategoryDecl();
1191 } else {
1192 iface = impl->getClassInterface();
1193 }
1194
1195 const ObjCMethodDecl *ifaceMD =
1196 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1197 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1198 }
1199
1200 SmallVector<const ObjCMethodDecl *, 4> overrides;
1201 MD->getOverriddenMethods(overrides);
1202 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1203 if (const ObjCMethodDecl *result =
1204 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1205 return result;
1206 }
1207
Craig Topperc3ec1492014-05-26 06:22:03 +00001208 return nullptr;
John McCall5ec7e7d2013-03-19 07:04:25 +00001209}
1210
1211void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1212 // Only complain if we're in an ObjC method and the required return
1213 // type doesn't match the method's declared return type.
1214 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1215 if (!MD || !MD->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +00001216 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
John McCall5ec7e7d2013-03-19 07:04:25 +00001217 return;
1218
1219 // Look for a method overridden by this method which explicitly uses
1220 // 'instancetype'.
1221 if (const ObjCMethodDecl *overridden =
1222 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
1223 SourceLocation loc;
1224 SourceRange range;
Alp Toker314cc812014-01-25 16:55:45 +00001225 if (TypeSourceInfo *TSI = overridden->getReturnTypeSourceInfo()) {
John McCall5ec7e7d2013-03-19 07:04:25 +00001226 range = TSI->getTypeLoc().getSourceRange();
1227 loc = range.getBegin();
1228 }
1229 if (loc.isInvalid())
1230 loc = overridden->getLocation();
1231 Diag(loc, diag::note_related_result_type_explicit)
1232 << /*current method*/ 1 << range;
1233 return;
1234 }
1235
1236 // Otherwise, if we have an interesting method family, note that.
1237 // This should always trigger if the above didn't.
1238 if (ObjCMethodFamily family = MD->getMethodFamily())
1239 Diag(MD->getLocation(), diag::note_related_result_type_family)
1240 << /*current method*/ 1
1241 << family;
1242}
1243
Douglas Gregor33823722011-06-11 01:09:30 +00001244void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1245 E = E->IgnoreParenImpCasts();
1246 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1247 if (!MsgSend)
1248 return;
1249
1250 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1251 if (!Method)
1252 return;
1253
1254 if (!Method->hasRelatedResultType())
1255 return;
Alp Toker314cc812014-01-25 16:55:45 +00001256
1257 if (Context.hasSameUnqualifiedType(
1258 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
Douglas Gregor33823722011-06-11 01:09:30 +00001259 return;
Alp Toker314cc812014-01-25 16:55:45 +00001260
1261 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
Douglas Gregorbab8a962011-09-08 01:46:34 +00001262 Context.getObjCInstanceType()))
1263 return;
1264
Douglas Gregor33823722011-06-11 01:09:30 +00001265 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1266 << Method->isInstanceMethod() << Method->getSelector()
1267 << MsgSend->getType();
1268}
1269
1270bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001271 MultiExprArg Args,
1272 Selector Sel,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001273 ArrayRef<SourceLocation> SelectorLocs,
1274 ObjCMethodDecl *Method,
Douglas Gregor33823722011-06-11 01:09:30 +00001275 bool isClassMessage, bool isSuperMessage,
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001276 SourceLocation lbrac, SourceLocation rbrac,
John McCall7decc9e2010-11-18 06:31:45 +00001277 QualType &ReturnType, ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001278 SourceLocation SelLoc;
1279 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1280 SelLoc = SelectorLocs.front();
1281 else
1282 SelLoc = lbrac;
1283
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001284 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001285 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001286 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001287 if (Args[i]->isTypeDependent())
1288 continue;
1289
John McCallcc5788c2013-03-04 07:34:02 +00001290 ExprResult result;
1291 if (getLangOpts().DebuggerSupport) {
1292 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001293 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001294 } else {
1295 result = DefaultArgumentPromotion(Args[i]);
1296 }
1297 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001298 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001299 Args[i] = result.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001300 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001301
John McCall31168b02011-06-15 23:02:42 +00001302 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001303 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001304 DiagID = diag::err_arc_method_not_found;
1305 else
1306 DiagID = isClassMessage ? diag::warn_class_method_not_found
1307 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001308 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001309 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahanian06499232013-06-18 17:10:58 +00001310 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001311 if (getLangOpts().ObjCAutoRefCount)
1312 DiagID = diag::error_method_not_found_with_typo;
1313 else
1314 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1315 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001316 Selector MatchedSel = OMD->getSelector();
1317 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001318 Diag(SelLoc, DiagID)
1319 << Sel<< isClassMessage << MatchedSel
Fariborz Jahanian75481672013-06-17 17:10:54 +00001320 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1321 }
1322 else
1323 Diag(SelLoc, DiagID)
1324 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001325 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001326 // Find the class to which we are sending this message.
1327 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian478536b2013-05-15 15:27:35 +00001328 if (ObjCInterfaceDecl *Class =
1329 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl())
1330 Diag(Class->getLocation(), diag::note_receiver_class_declared);
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001331 }
1332 }
John McCall3f4138c2011-07-13 17:56:40 +00001333
1334 // In debuggers, we want to use __unknown_anytype for these
1335 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001336 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001337 ReturnType = Context.UnknownAnyTy;
1338 } else {
1339 ReturnType = Context.getObjCIdType();
1340 }
John McCall7decc9e2010-11-18 06:31:45 +00001341 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001342 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001343 }
Mike Stump11289f42009-09-09 15:08:12 +00001344
Douglas Gregor33823722011-06-11 01:09:30 +00001345 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1346 isSuperMessage);
Alp Toker314cc812014-01-25 16:55:45 +00001347 VK = Expr::getValueKindForType(Method->getReturnType());
Mike Stump11289f42009-09-09 15:08:12 +00001348
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001349 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001350 // Method might have more arguments than selector indicates. This is due
1351 // to addition of c-style arguments in method.
1352 if (Method->param_size() > Sel.getNumArgs())
1353 NumNamedArgs = Method->param_size();
1354 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001355 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001356 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001357 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001358 return false;
1359 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001360
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001361 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001362 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001363 // We can't do any type-checking on a type-dependent argument.
1364 if (Args[i]->isTypeDependent())
1365 continue;
1366
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001367 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001368
John McCall4124c492011-10-17 18:40:02 +00001369 ParmVarDecl *param = Method->param_begin()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001370 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001371
John McCall4124c492011-10-17 18:40:02 +00001372 // Strip the unbridged-cast placeholder expression off unless it's
1373 // a consumed argument.
1374 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1375 !param->hasAttr<CFConsumedAttr>())
1376 argExpr = stripARCUnbridgedCast(argExpr);
1377
John McCallea0a39e2012-11-14 00:49:39 +00001378 // If the parameter is __unknown_anytype, infer its type
1379 // from the argument.
1380 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001381 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001382 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001383 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001384 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001385 } else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001386 Args[i] = argE.get();
John McCallea0a39e2012-11-14 00:49:39 +00001387
John McCallcc5788c2013-03-04 07:34:02 +00001388 // Update the parameter type in-place.
1389 param->setType(paramType);
1390 }
1391 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001392 }
1393
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001394 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall4124c492011-10-17 18:40:02 +00001395 param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001396 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001397 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001398
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001399 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall4124c492011-10-17 18:40:02 +00001400 param);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001401 ExprResult ArgE = PerformCopyInitialization(Entity, SelLoc, Owned(argExpr));
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001402 if (ArgE.isInvalid())
1403 IsError = true;
1404 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001405 Args[i] = ArgE.getAs<Expr>();
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001406 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001407
1408 // Promote additional arguments to variadic methods.
1409 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001410 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001411 if (Args[i]->isTypeDependent())
1412 continue;
1413
Jordy Roseaca01f92012-05-12 17:32:52 +00001414 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
Craig Topperc3ec1492014-05-26 06:22:03 +00001415 nullptr);
John Wiegley01296292011-04-08 18:41:53 +00001416 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001417 Args[i] = Arg.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001418 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001419 } else {
1420 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001421 if (Args.size() != NumNamedArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00001422 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001423 diag::err_typecheck_call_too_many_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001424 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001425 << Method->getSourceRange()
Chris Lattner3b054132008-11-19 05:08:23 +00001426 << SourceRange(Args[NumNamedArgs]->getLocStart(),
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001427 Args.back()->getLocEnd());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001428 }
1429 }
1430
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001431 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001432
1433 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001434 IsError |= CheckObjCMethodCall(
Robert Wilhelm88e02492013-08-19 07:57:02 +00001435 Method, SelLoc, makeArrayRef<const Expr *>(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001436
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001437 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001438}
1439
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001440bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001441 // 'self' is objc 'self' in an objc method only.
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001442 ObjCMethodDecl *Method =
1443 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1444 return isSelfExpr(RExpr, Method);
1445}
1446
1447bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
John McCallfe96e0b2011-11-06 09:01:30 +00001448 if (!method) return false;
1449
John McCall31168b02011-06-15 23:02:42 +00001450 receiver = receiver->IgnoreParenLValueCasts();
1451 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001452 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001453 return true;
1454 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001455}
1456
John McCall526ab472011-10-25 17:37:35 +00001457/// LookupMethodInType - Look up a method in an ObjCObjectType.
1458ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1459 bool isInstance) {
1460 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1461 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1462 // Look it up in the main interface (and categories, etc.)
1463 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1464 return method;
1465
1466 // Okay, look for "private" methods declared in any
1467 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001468 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1469 return method;
John McCall526ab472011-10-25 17:37:35 +00001470 }
1471
1472 // Check qualifiers.
Aaron Ballman1683f7b2014-03-17 15:55:30 +00001473 for (const auto *I : objType->quals())
1474 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
John McCall526ab472011-10-25 17:37:35 +00001475 return method;
1476
Craig Topperc3ec1492014-05-26 06:22:03 +00001477 return nullptr;
John McCall526ab472011-10-25 17:37:35 +00001478}
1479
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001480/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1481/// list of a qualified objective pointer type.
1482ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1483 const ObjCObjectPointerType *OPT,
1484 bool Instance)
1485{
Craig Topperc3ec1492014-05-26 06:22:03 +00001486 ObjCMethodDecl *MD = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +00001487 for (const auto *PROTO : OPT->quals()) {
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001488 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1489 return MD;
1490 }
1491 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001492 return nullptr;
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001493}
1494
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001495static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1496 if (!Receiver)
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001497 return;
1498
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001499 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver))
1500 Receiver = OVE->getSourceExpr();
1501
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001502 Expr *RExpr = Receiver->IgnoreParenImpCasts();
1503 SourceLocation Loc = RExpr->getLocStart();
1504 QualType T = RExpr->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001505 const ObjCPropertyDecl *PDecl = nullptr;
1506 const ObjCMethodDecl *GDecl = nullptr;
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001507 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1508 RExpr = POE->getSyntacticForm();
1509 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1510 if (PRE->isImplicitProperty()) {
1511 GDecl = PRE->getImplicitPropertyGetter();
1512 if (GDecl) {
Alp Toker314cc812014-01-25 16:55:45 +00001513 T = GDecl->getReturnType();
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001514 }
1515 }
1516 else {
1517 PDecl = PRE->getExplicitProperty();
1518 if (PDecl) {
1519 T = PDecl->getType();
1520 }
1521 }
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001522 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001523 }
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001524 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) {
1525 // See if receiver is a method which envokes a synthesized getter
1526 // backing a 'weak' property.
1527 ObjCMethodDecl *Method = ME->getMethodDecl();
Jordan Rose2bd991a2012-10-10 16:42:54 +00001528 if (Method && Method->getSelector().getNumArgs() == 0) {
1529 PDecl = Method->findPropertyDecl();
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001530 if (PDecl)
1531 T = PDecl->getType();
1532 }
1533 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001534
Jordan Rose13d6b712012-09-28 22:21:42 +00001535 if (T.getObjCLifetime() != Qualifiers::OCL_Weak) {
1536 if (!PDecl)
1537 return;
1538 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak))
1539 return;
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001540 }
Jordan Rose13d6b712012-09-28 22:21:42 +00001541
1542 S.Diag(Loc, diag::warn_receiver_is_weak)
1543 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1544
1545 if (PDecl)
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001546 S.Diag(PDecl->getLocation(), diag::note_property_declare);
Jordan Rose13d6b712012-09-28 22:21:42 +00001547 else if (GDecl)
1548 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
1549
1550 S.Diag(Loc, diag::note_arc_assign_to_strong);
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001551}
1552
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001553/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1554/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001555ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001556HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001557 Expr *BaseExpr, SourceLocation OpLoc,
1558 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001559 SourceLocation MemberLoc,
1560 SourceLocation SuperLoc, QualType SuperType,
1561 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001562 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1563 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001564
Benjamin Kramer365082d2012-05-19 16:34:46 +00001565 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001566 Diag(MemberLoc, diag::err_invalid_property_name)
1567 << MemberName << QualType(OPT, 0);
1568 return ExprError();
1569 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001570
1571 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregord6459312011-04-20 18:19:55 +00001572
Douglas Gregor4123a862011-11-14 22:10:01 +00001573 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1574 : BaseExpr->getSourceRange();
1575 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001576 diag::err_property_not_found_forward_class,
1577 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001578 return ExprError();
Douglas Gregor4123a862011-11-14 22:10:01 +00001579
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001580 // Search for a declared property first.
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001581 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001582 // Check whether we can reference this property.
1583 if (DiagnoseUseOfDecl(PD, MemberLoc))
1584 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001585 if (Super)
John McCall526ab472011-10-25 17:37:35 +00001586 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001587 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001588 MemberLoc,
1589 SuperLoc, SuperType));
1590 else
John McCall526ab472011-10-25 17:37:35 +00001591 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001592 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001593 MemberLoc, BaseExpr));
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001594 }
1595 // Check protocols on qualified interfaces.
Aaron Ballman83731462014-03-17 16:14:00 +00001596 for (const auto *I : OPT->quals())
1597 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001598 // Check whether we can reference this property.
1599 if (DiagnoseUseOfDecl(PD, MemberLoc))
1600 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001601
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001602 if (Super)
John McCall526ab472011-10-25 17:37:35 +00001603 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1604 Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001605 VK_LValue,
1606 OK_ObjCProperty,
1607 MemberLoc,
1608 SuperLoc, SuperType));
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001609 else
John McCall526ab472011-10-25 17:37:35 +00001610 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1611 Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001612 VK_LValue,
1613 OK_ObjCProperty,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001614 MemberLoc,
1615 BaseExpr));
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001616 }
1617 // If that failed, look for an "implicit" property by seeing if the nullary
1618 // selector is implemented.
1619
1620 // FIXME: The logic for looking up nullary and unary selectors should be
1621 // shared with the code in ActOnInstanceMessage.
1622
1623 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1624 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001625
1626 // May be founf in property's qualified list.
1627 if (!Getter)
1628 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001629
1630 // If this reference is in an @implementation, check for 'private' methods.
1631 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001632 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001633
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001634 if (Getter) {
1635 // Check if we can reference this property.
1636 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1637 return ExprError();
1638 }
1639 // If we found a getter then this may be a valid dot-reference, we
1640 // will look for the matching setter, in case it is needed.
1641 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001642 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1643 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001644 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001645
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001646 // May be founf in property's qualified list.
1647 if (!Setter)
1648 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1649
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001650 if (!Setter) {
1651 // If this reference is in an @implementation, also check for 'private'
1652 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001653 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001654 }
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001655
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001656 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1657 return ExprError();
1658
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001659 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001660 if (Super)
John McCallb7bd14f2010-12-02 01:19:52 +00001661 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001662 Context.PseudoObjectTy,
1663 VK_LValue, OK_ObjCProperty,
John McCallb7bd14f2010-12-02 01:19:52 +00001664 MemberLoc,
1665 SuperLoc, SuperType));
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001666 else
John McCallb7bd14f2010-12-02 01:19:52 +00001667 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001668 Context.PseudoObjectTy,
1669 VK_LValue, OK_ObjCProperty,
John McCallb7bd14f2010-12-02 01:19:52 +00001670 MemberLoc, BaseExpr));
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001671
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001672 }
1673
1674 // Attempt to correct for typos in property names.
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001675 DeclFilterCCC<ObjCPropertyDecl> Validator;
1676 if (TypoCorrection Corrected = CorrectTypo(
Craig Topperc3ec1492014-05-26 06:22:03 +00001677 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName,
1678 nullptr, nullptr, Validator, CTK_ErrorRecovery, IFace, false, OPT)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001679 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1680 << MemberName << QualType(OPT, 0));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001681 DeclarationName TypoResult = Corrected.getCorrection();
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001682 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1683 TypoResult, MemberLoc,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001684 SuperLoc, SuperType, Super);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001685 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001686 ObjCInterfaceDecl *ClassDeclared;
1687 if (ObjCIvarDecl *Ivar =
1688 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1689 QualType T = Ivar->getType();
1690 if (const ObjCObjectPointerType * OBJPT =
1691 T->getAsObjCInterfacePointerType()) {
Douglas Gregor4123a862011-11-14 22:10:01 +00001692 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001693 diag::err_property_not_as_forward_class,
1694 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001695 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001696 }
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001697 Diag(MemberLoc,
1698 diag::err_ivar_access_using_property_syntax_suggest)
1699 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1700 << FixItHint::CreateReplacement(OpLoc, "->");
1701 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001702 }
Chris Lattner90c58fa2010-04-11 07:51:10 +00001703
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001704 Diag(MemberLoc, diag::err_property_not_found)
1705 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001706 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001707 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001708 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001709 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001710}
1711
1712
1713
John McCalldadc5752010-08-24 06:29:42 +00001714ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001715ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1716 IdentifierInfo &propertyName,
1717 SourceLocation receiverNameLoc,
1718 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001719
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001720 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001721 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1722 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001723
1724 bool IsSuper = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00001725 if (!IFace) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001726 // If the "receiver" is 'super' in a method, handle it as an expression-like
1727 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001728 if (receiverNamePtr->isStr("super")) {
Douglas Gregor33823722011-06-11 01:09:30 +00001729 IsSuper = true;
1730
Eli Friedman24af8502012-02-03 22:47:37 +00001731 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001732 if (CurMethod->isInstanceMethod()) {
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00001733 ObjCInterfaceDecl *Super =
1734 CurMethod->getClassInterface()->getSuperClass();
1735 if (!Super) {
1736 // The current class does not have a superclass.
1737 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1738 << CurMethod->getClassInterface()->getIdentifier();
1739 return ExprError();
1740 }
1741 QualType T = Context.getObjCInterfaceType(Super);
Chris Lattnera36ec422010-04-11 08:28:14 +00001742 T = Context.getObjCObjectPointerType(T);
Craig Topperc3ec1492014-05-26 06:22:03 +00001743
Chris Lattnera36ec422010-04-11 08:28:14 +00001744 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001745 /*BaseExpr*/nullptr,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001746 SourceLocation()/*OpLoc*/,
1747 &propertyName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001748 propertyNameLoc,
1749 receiverNameLoc, T, true);
Chris Lattnera36ec422010-04-11 08:28:14 +00001750 }
Mike Stump11289f42009-09-09 15:08:12 +00001751
Chris Lattnera36ec422010-04-11 08:28:14 +00001752 // Otherwise, if this is a class method, try dispatching to our
1753 // superclass.
1754 IFace = CurMethod->getClassInterface()->getSuperClass();
1755 }
John McCall5f2d5562011-02-03 09:00:02 +00001756 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001757
1758 if (!IFace) {
Alp Tokerec543272013-12-24 09:48:30 +00001759 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1760 << tok::l_paren;
Chris Lattnera36ec422010-04-11 08:28:14 +00001761 return ExprError();
1762 }
1763 }
1764
1765 // Search for a declared property first.
Steve Naroff9527bbf2009-03-09 21:12:44 +00001766 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001767 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001768
1769 // If this reference is in an @implementation, check for 'private' methods.
1770 if (!Getter)
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001771 Getter = IFace->lookupPrivateClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001772
1773 if (Getter) {
1774 // FIXME: refactor/share with ActOnMemberReference().
1775 // Check if we can reference this property.
1776 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1777 return ExprError();
1778 }
Mike Stump11289f42009-09-09 15:08:12 +00001779
Steve Naroff9527bbf2009-03-09 21:12:44 +00001780 // Look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00001781 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001782 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1783 PP.getSelectorTable(),
1784 &propertyName);
Mike Stump11289f42009-09-09 15:08:12 +00001785
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001786 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001787 if (!Setter) {
1788 // If this reference is in an @implementation, also check for 'private'
1789 // methods.
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001790 Setter = IFace->lookupPrivateClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001791 }
1792 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00001793 if (!Setter)
1794 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001795
1796 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1797 return ExprError();
1798
1799 if (Getter || Setter) {
Douglas Gregor33823722011-06-11 01:09:30 +00001800 if (IsSuper)
1801 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001802 Context.PseudoObjectTy,
1803 VK_LValue, OK_ObjCProperty,
Douglas Gregor33823722011-06-11 01:09:30 +00001804 propertyNameLoc,
1805 receiverNameLoc,
1806 Context.getObjCInterfaceType(IFace)));
1807
John McCallb7bd14f2010-12-02 01:19:52 +00001808 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001809 Context.PseudoObjectTy,
1810 VK_LValue, OK_ObjCProperty,
John McCallb7bd14f2010-12-02 01:19:52 +00001811 propertyNameLoc,
1812 receiverNameLoc, IFace));
Steve Naroff9527bbf2009-03-09 21:12:44 +00001813 }
1814 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1815 << &propertyName << Context.getObjCInterfaceType(IFace));
1816}
1817
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001818namespace {
1819
1820class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1821 public:
1822 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1823 // Determine whether "super" is acceptable in the current context.
1824 if (Method && Method->getClassInterface())
1825 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1826 }
1827
Craig Toppere14c0f82014-03-12 04:55:44 +00001828 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001829 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1830 candidate.isKeyword("super");
1831 }
1832};
1833
1834}
1835
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001836Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001837 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001838 SourceLocation NameLoc,
1839 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001840 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00001841 ParsedType &ReceiverType) {
1842 ReceiverType = ParsedType();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001843
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001844 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00001845 // messaging super. If the identifier is "super" and there is a
1846 // trailing dot, it's an instance message.
1847 if (IsSuper && S->isInObjcMethodScope())
1848 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001849
1850 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1851 LookupName(Result, S);
1852
1853 switch (Result.getResultKind()) {
1854 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00001855 // Normal name lookup didn't find anything. If we're in an
1856 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00001857 // FIXME: This is a hack. Ivar lookup should be part of normal
1858 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00001859 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00001860 if (!Method->getClassInterface()) {
1861 // Fall back: let the parser try to parse it as an instance message.
1862 return ObjCInstanceMessage;
1863 }
1864
Douglas Gregorca7136b2010-04-19 20:09:36 +00001865 ObjCInterfaceDecl *ClassDeclared;
1866 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1867 ClassDeclared))
1868 return ObjCInstanceMessage;
1869 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00001870
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001871 // Break out; we'll perform typo correction below.
1872 break;
1873
1874 case LookupResult::NotFoundInCurrentInstantiation:
1875 case LookupResult::FoundOverloaded:
1876 case LookupResult::FoundUnresolvedValue:
1877 case LookupResult::Ambiguous:
1878 Result.suppressDiagnostics();
1879 return ObjCInstanceMessage;
1880
1881 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00001882 // If the identifier is a class or not, and there is a trailing dot,
1883 // it's an instance message.
1884 if (HasTrailingDot)
1885 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001886 // We found something. If it's a type, then we have a class
1887 // message. Otherwise, it's an instance message.
1888 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001889 QualType T;
1890 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1891 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001892 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00001893 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001894 DiagnoseUseOfDecl(Type, NameLoc);
1895 }
1896 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00001897 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001898
Douglas Gregore5798dc2010-04-21 20:38:13 +00001899 // We have a class message, and T is the type we're
1900 // messaging. Build source-location information for it.
1901 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00001902 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00001903 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001904 }
1905 }
1906
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001907 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00001908 if (TypoCorrection Corrected =
1909 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
Craig Topperc3ec1492014-05-26 06:22:03 +00001910 nullptr, Validator, CTK_ErrorRecovery, nullptr, false,
1911 nullptr, false)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001912 if (Corrected.isKeyword()) {
1913 // If we've found the keyword "super" (the only keyword that would be
1914 // returned by CorrectTypo), this is a send to super.
Richard Smithf9b15102013-08-17 00:46:16 +00001915 diagnoseTypo(Corrected,
1916 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001917 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001918 } else if (ObjCInterfaceDecl *Class =
Richard Smithf9b15102013-08-17 00:46:16 +00001919 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001920 // If we found a declaration, correct when it refers to an Objective-C
1921 // class.
Richard Smithf9b15102013-08-17 00:46:16 +00001922 diagnoseTypo(Corrected,
1923 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001924 QualType T = Context.getObjCInterfaceType(Class);
1925 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1926 ReceiverType = CreateParsedType(T, TSInfo);
1927 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001928 }
1929 }
Richard Smithf9b15102013-08-17 00:46:16 +00001930
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001931 // Fall back: let the parser try to parse it as an instance message.
1932 return ObjCInstanceMessage;
1933}
Steve Naroff9527bbf2009-03-09 21:12:44 +00001934
John McCalldadc5752010-08-24 06:29:42 +00001935ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001936 SourceLocation SuperLoc,
1937 Selector Sel,
1938 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00001939 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001940 SourceLocation RBracLoc,
1941 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001942 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00001943 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00001944 if (!Method) {
1945 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1946 return ExprError();
1947 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001948
Douglas Gregor4fdba132010-04-21 20:01:04 +00001949 ObjCInterfaceDecl *Class = Method->getClassInterface();
1950 if (!Class) {
1951 Diag(SuperLoc, diag::error_no_super_class_message)
1952 << Method->getDeclName();
1953 return ExprError();
1954 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001955
Douglas Gregor4fdba132010-04-21 20:01:04 +00001956 ObjCInterfaceDecl *Super = Class->getSuperClass();
1957 if (!Super) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001958 // The current class does not have a superclass.
Ted Kremenek499897b2011-01-23 17:21:34 +00001959 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1960 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001961 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00001962 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001963
Douglas Gregor4fdba132010-04-21 20:01:04 +00001964 // We are in a method whose class has a superclass, so 'super'
1965 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00001966 if (Method->getSelector() == Sel)
1967 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00001968
Jordan Rose2afd6612012-10-19 16:05:26 +00001969 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00001970 // Since we are in an instance method, this is an instance
1971 // message to the superclass instance.
1972 QualType SuperTy = Context.getObjCInterfaceType(Super);
1973 SuperTy = Context.getObjCObjectPointerType(SuperTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00001974 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
1975 Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001976 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001977 }
Douglas Gregor4fdba132010-04-21 20:01:04 +00001978
1979 // Since we are in a class method, this is a class message to
1980 // the superclass.
Craig Topperc3ec1492014-05-26 06:22:03 +00001981 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
Douglas Gregor4fdba132010-04-21 20:01:04 +00001982 Context.getObjCInterfaceType(Super),
Craig Topperc3ec1492014-05-26 06:22:03 +00001983 SuperLoc, Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001984 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001985}
1986
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001987
1988ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1989 bool isSuperReceiver,
1990 SourceLocation Loc,
1991 Selector Sel,
1992 ObjCMethodDecl *Method,
1993 MultiExprArg Args) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001994 TypeSourceInfo *receiverTypeInfo = nullptr;
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001995 if (!ReceiverType.isNull())
1996 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1997
1998 return BuildClassMessage(receiverTypeInfo, ReceiverType,
1999 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2000 Sel, Method, Loc, Loc, Loc, Args,
2001 /*isImplicit=*/true);
2002
2003}
2004
Ted Kremeneke65b0862012-03-06 20:05:56 +00002005static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2006 unsigned DiagID,
2007 bool (*refactor)(const ObjCMessageExpr *,
2008 const NSAPI &, edit::Commit &)) {
2009 SourceLocation MsgLoc = Msg->getExprLoc();
2010 if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
2011 return;
2012
2013 SourceManager &SM = S.SourceMgr;
2014 edit::Commit ECommit(SM, S.LangOpts);
2015 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2016 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2017 << Msg->getSelector() << Msg->getSourceRange();
2018 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2019 if (!ECommit.isCommitable())
2020 return;
2021 for (edit::Commit::edit_iterator
2022 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2023 const edit::Commit::Edit &Edit = *I;
2024 switch (Edit.Kind) {
2025 case edit::Commit::Act_Insert:
2026 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2027 Edit.Text,
2028 Edit.BeforePrev));
2029 break;
2030 case edit::Commit::Act_InsertFromRange:
2031 Builder.AddFixItHint(
2032 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2033 Edit.getInsertFromRange(SM),
2034 Edit.BeforePrev));
2035 break;
2036 case edit::Commit::Act_Remove:
2037 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2038 break;
2039 }
2040 }
2041 }
2042}
2043
2044static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2045 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2046 edit::rewriteObjCRedundantCallWithLiteral);
2047}
2048
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002049/// \brief Build an Objective-C class message expression.
2050///
2051/// This routine takes care of both normal class messages and
2052/// class messages to the superclass.
2053///
2054/// \param ReceiverTypeInfo Type source information that describes the
2055/// receiver of this message. This may be NULL, in which case we are
2056/// sending to the superclass and \p SuperLoc must be a valid source
2057/// location.
2058
2059/// \param ReceiverType The type of the object receiving the
2060/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2061/// type as that refers to. For a superclass send, this is the type of
2062/// the superclass.
2063///
2064/// \param SuperLoc The location of the "super" keyword in a
2065/// superclass message.
2066///
2067/// \param Sel The selector to which the message is being sent.
2068///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002069/// \param Method The method that this class message is invoking, if
2070/// already known.
2071///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002072/// \param LBracLoc The location of the opening square bracket ']'.
2073///
James Dennettffad8b72012-06-22 08:10:18 +00002074/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002075///
James Dennettffad8b72012-06-22 08:10:18 +00002076/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002077ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002078 QualType ReceiverType,
2079 SourceLocation SuperLoc,
2080 Selector Sel,
2081 ObjCMethodDecl *Method,
2082 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002083 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002084 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002085 MultiExprArg ArgsIn,
2086 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002087 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002088 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002089 if (LBracLoc.isInvalid()) {
2090 Diag(Loc, diag::err_missing_open_square_message_send)
2091 << FixItHint::CreateInsertion(Loc, "[");
2092 LBracLoc = Loc;
2093 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002094 SourceLocation SelLoc;
2095 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2096 SelLoc = SelectorLocs.front();
2097 else
2098 SelLoc = Loc;
2099
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002100 if (ReceiverType->isDependentType()) {
2101 // If the receiver type is dependent, we can't type-check anything
2102 // at this point. Build a dependent expression.
2103 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002104 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002105 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCall7decc9e2010-11-18 06:31:45 +00002106 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
2107 VK_RValue, LBracLoc, ReceiverTypeInfo,
Craig Topperc3ec1492014-05-26 06:22:03 +00002108 Sel, SelectorLocs, /*Method=*/nullptr,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002109 makeArrayRef(Args, NumArgs),RBracLoc,
2110 isImplicit));
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002111 }
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002112
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002113 // Find the class to which we are sending this message.
Craig Topperc3ec1492014-05-26 06:22:03 +00002114 ObjCInterfaceDecl *Class = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00002115 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2116 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002117 Diag(Loc, diag::err_invalid_receiver_class_message)
2118 << ReceiverType;
2119 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002120 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002121 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002122 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002123 if (!getLangOpts().CPlusPlus)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002124 (void)DiagnoseUseOfDecl(Class, SelLoc);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002125 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002126 if (!Method) {
Douglas Gregor4123a862011-11-14 22:10:01 +00002127 SourceRange TypeRange
2128 = SuperLoc.isValid()? SourceRange(SuperLoc)
2129 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002130 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002131 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002132 ? diag::err_arc_receiver_forward_class
2133 : diag::warn_receiver_forward_class),
2134 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002135 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorb5186b12010-04-22 17:01:48 +00002136 Method = LookupFactoryMethodInGlobalPool(Sel,
2137 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002138 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002139 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2140 << Method->getDeclName();
2141 }
2142 if (!Method)
2143 Method = Class->lookupClassMethod(Sel);
2144
2145 // If we have an implementation in scope, check "private" methods.
2146 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002147 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002148
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002149 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002150 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002151 }
Mike Stump11289f42009-09-09 15:08:12 +00002152
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002153 // Check the argument types and determine the result type.
2154 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002155 ExprValueKind VK = VK_RValue;
2156
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002157 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002158 Expr **Args = ArgsIn.data();
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002159 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2160 Sel, SelectorLocs,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00002161 Method, true,
Douglas Gregor33823722011-06-11 01:09:30 +00002162 SuperLoc.isValid(), LBracLoc, RBracLoc,
2163 ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002164 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002165
Alp Toker314cc812014-01-25 16:55:45 +00002166 if (Method && !Method->getReturnType()->isVoidType() &&
2167 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002168 diag::err_illegal_message_expr_incomplete_type))
2169 return ExprError();
2170
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002171 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002172 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002173 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002174 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002175 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002176 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002177 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002178 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002179 else {
John McCall7decc9e2010-11-18 06:31:45 +00002180 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002181 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002182 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002183 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002184 if (!isImplicit)
2185 checkCocoaAPI(*this, Result);
2186 }
Douglas Gregoraae38d62010-05-22 05:17:18 +00002187 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002188}
2189
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002190// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002191// ArgExprs is optional - if it is present, the number of expressions
2192// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002193ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002194 ParsedType Receiver,
2195 Selector Sel,
2196 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002197 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002198 SourceLocation RBracLoc,
2199 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002200 TypeSourceInfo *ReceiverTypeInfo;
2201 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2202 if (ReceiverType.isNull())
2203 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002204
Mike Stump11289f42009-09-09 15:08:12 +00002205
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002206 if (!ReceiverTypeInfo)
2207 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2208
2209 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002210 /*SuperLoc=*/SourceLocation(), Sel,
2211 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2212 Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002213}
2214
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002215ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2216 QualType ReceiverType,
2217 SourceLocation Loc,
2218 Selector Sel,
2219 ObjCMethodDecl *Method,
2220 MultiExprArg Args) {
2221 return BuildInstanceMessage(Receiver, ReceiverType,
2222 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2223 Sel, Method, Loc, Loc, Loc, Args,
2224 /*isImplicit=*/true);
2225}
2226
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002227/// \brief Build an Objective-C instance message expression.
2228///
2229/// This routine takes care of both normal instance messages and
2230/// instance messages to the superclass instance.
2231///
2232/// \param Receiver The expression that computes the object that will
2233/// receive this message. This may be empty, in which case we are
2234/// sending to the superclass instance and \p SuperLoc must be a valid
2235/// source location.
2236///
2237/// \param ReceiverType The (static) type of the object receiving the
2238/// message. When a \p Receiver expression is provided, this is the
2239/// same type as that expression. For a superclass instance send, this
2240/// is a pointer to the type of the superclass.
2241///
2242/// \param SuperLoc The location of the "super" keyword in a
2243/// superclass instance message.
2244///
2245/// \param Sel The selector to which the message is being sent.
2246///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002247/// \param Method The method that this instance message is invoking, if
2248/// already known.
2249///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002250/// \param LBracLoc The location of the opening square bracket ']'.
2251///
James Dennettffad8b72012-06-22 08:10:18 +00002252/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002253///
James Dennettffad8b72012-06-22 08:10:18 +00002254/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002255ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002256 QualType ReceiverType,
2257 SourceLocation SuperLoc,
2258 Selector Sel,
2259 ObjCMethodDecl *Method,
2260 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002261 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002262 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002263 MultiExprArg ArgsIn,
2264 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002265 // The location of the receiver.
2266 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002267 SourceRange RecRange =
2268 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2269 SourceLocation SelLoc;
2270 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2271 SelLoc = SelectorLocs.front();
2272 else
2273 SelLoc = Loc;
2274
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002275 if (LBracLoc.isInvalid()) {
2276 Diag(Loc, diag::err_missing_open_square_message_send)
2277 << FixItHint::CreateInsertion(Loc, "[");
2278 LBracLoc = Loc;
2279 }
2280
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002281 // If we have a receiver expression, perform appropriate promotions
2282 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002283 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002284 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002285 ExprResult Result;
2286 if (Receiver->getType() == Context.UnknownAnyTy)
2287 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2288 else
2289 Result = CheckPlaceholderExpr(Receiver);
2290 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002291 Receiver = Result.get();
John McCall4124c492011-10-17 18:40:02 +00002292 }
2293
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002294 if (Receiver->isTypeDependent()) {
2295 // If the receiver is type-dependent, we can't type-check anything
2296 // at this point. Build a dependent expression.
2297 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002298 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002299 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2300 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00002301 VK_RValue, LBracLoc, Receiver, Sel,
Craig Topperc3ec1492014-05-26 06:22:03 +00002302 SelectorLocs, /*Method=*/nullptr,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002303 makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002304 RBracLoc, isImplicit));
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002305 }
2306
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002307 // If necessary, apply function/array conversion to the receiver.
2308 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002309 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2310 if (Result.isInvalid())
2311 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002312 Receiver = Result.get();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002313 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002314
2315 // If the receiver is an ObjC pointer, a block pointer, or an
2316 // __attribute__((NSObject)) pointer, we don't need to do any
2317 // special conversion in order to look up a receiver.
2318 if (ReceiverType->isObjCRetainableType()) {
2319 // do nothing
2320 } else if (!getLangOpts().ObjCAutoRefCount &&
2321 !Context.getObjCIdType().isNull() &&
2322 (ReceiverType->isPointerType() ||
2323 ReceiverType->isIntegerType())) {
2324 // Implicitly convert integers and pointers to 'id' but emit a warning.
2325 // But not in ARC.
2326 Diag(Loc, diag::warn_bad_receiver_type)
2327 << ReceiverType
2328 << Receiver->getSourceRange();
2329 if (ReceiverType->isPointerType()) {
2330 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002331 CK_CPointerToObjCPointerCast).get();
John McCall80c93a02013-03-01 09:20:14 +00002332 } else {
2333 // TODO: specialized warning on null receivers?
2334 bool IsNull = Receiver->isNullPointerConstant(Context,
2335 Expr::NPC_ValueDependentIsNull);
2336 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2337 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002338 Kind).get();
John McCall80c93a02013-03-01 09:20:14 +00002339 }
2340 ReceiverType = Receiver->getType();
2341 } else if (getLangOpts().CPlusPlus) {
Douglas Gregor4b60a152013-11-07 22:34:54 +00002342 // The receiver must be a complete type.
2343 if (RequireCompleteType(Loc, Receiver->getType(),
2344 diag::err_incomplete_receiver_type))
2345 return ExprError();
2346
John McCall80c93a02013-03-01 09:20:14 +00002347 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2348 if (result.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002349 Receiver = result.get();
John McCall80c93a02013-03-01 09:20:14 +00002350 ReceiverType = Receiver->getType();
2351 }
2352 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002353 }
2354
John McCall80c93a02013-03-01 09:20:14 +00002355 // There's a somewhat weird interaction here where we assume that we
2356 // won't actually have a method unless we also don't need to do some
2357 // of the more detailed type-checking on the receiver.
2358
Douglas Gregorb5186b12010-04-22 17:01:48 +00002359 if (!Method) {
2360 // Handle messages to id.
Fariborz Jahanian32e59ba2010-08-10 18:10:50 +00002361 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002362 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002363 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2364 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002365 SourceRange(LBracLoc, RBracLoc),
2366 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002367 if (!Method)
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002368 Method = LookupFactoryMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002369 SourceRange(LBracLoc,RBracLoc),
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002370 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002371 } else if (ReceiverType->isObjCClassType() ||
2372 ReceiverType->isObjCQualifiedClassType()) {
2373 // Handle messages to Class.
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002374 // We allow sending a message to a qualified Class ("Class<foo>"), which
2375 // is ok as long as one of the protocols implements the selector (if not, warn).
2376 if (const ObjCObjectPointerType *QClassTy
2377 = ReceiverType->getAsObjCQualifiedClassType()) {
2378 // Search protocols for class methods.
2379 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2380 if (!Method) {
2381 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2382 // warn if instance method found for a Class message.
2383 if (Method) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002384 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002385 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002386 Diag(Method->getLocation(), diag::note_method_declared_at)
2387 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002388 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002389 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002390 } else {
2391 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2392 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2393 // First check the public methods in the class interface.
2394 Method = ClassDecl->lookupClassMethod(Sel);
2395
2396 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002397 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002398 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002399 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002400 return ExprError();
2401 }
2402 if (!Method) {
2403 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002404 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002405 Method = LookupFactoryMethodInGlobalPool(Sel,
2406 SourceRange(LBracLoc, RBracLoc),
2407 true);
2408 if (!Method) {
2409 // If no class (factory) method was found, check if an _instance_
2410 // method of the same name exists in the root class only.
2411 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002412 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002413 true);
2414 if (Method)
2415 if (const ObjCInterfaceDecl *ID =
2416 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2417 if (ID->getSuperClass())
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002418 Diag(SelLoc, diag::warn_root_inst_method_not_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002419 << Sel << SourceRange(LBracLoc, RBracLoc);
2420 }
2421 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002422 }
2423 }
2424 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002425 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002426 ObjCInterfaceDecl *ClassDecl = nullptr;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002427
2428 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2429 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002430 // And as long as message is not deprecated/unavailable (warn if it is).
Douglas Gregorb5186b12010-04-22 17:01:48 +00002431 if (const ObjCObjectPointerType *QIdTy
2432 = ReceiverType->getAsObjCQualifiedIdType()) {
2433 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002434 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2435 if (!Method)
2436 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002437 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002438 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002439 } else if (const ObjCObjectPointerType *OCIType
2440 = ReceiverType->getAsObjCInterfacePointerType()) {
2441 // We allow sending a message to a pointer to an interface (an object).
2442 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002443
Douglas Gregor4123a862011-11-14 22:10:01 +00002444 // Try to complete the type. Under ARC, this is a hard error from which
2445 // we don't try to recover.
Craig Topperc3ec1492014-05-26 06:22:03 +00002446 const ObjCInterfaceDecl *forwardClass = nullptr;
Douglas Gregor4123a862011-11-14 22:10:01 +00002447 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002448 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002449 ? diag::err_arc_receiver_forward_instance
2450 : diag::warn_receiver_forward_instance,
2451 Receiver? Receiver->getSourceRange()
2452 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002453 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002454 return ExprError();
2455
2456 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanianc934de62012-02-03 01:02:44 +00002457 Diag(Receiver ? Receiver->getLocStart()
2458 : SuperLoc, diag::note_receiver_is_id);
Craig Topperc3ec1492014-05-26 06:22:03 +00002459 Method = nullptr;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002460 } else {
2461 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002462 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002463
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002464 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002465 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002466 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2467
Douglas Gregorb5186b12010-04-22 17:01:48 +00002468 if (!Method) {
2469 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002470 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002471
David Blaikiebbafb8a2012-03-11 07:00:24 +00002472 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002473 Diag(SelLoc, diag::err_arc_may_not_respond)
2474 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002475 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002476 return ExprError();
2477 }
2478
Douglas Gregor486b74e2011-09-27 16:10:05 +00002479 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002480 // If we still haven't found a method, look in the global pool. This
2481 // behavior isn't very desirable, however we need it for GCC
2482 // compatibility. FIXME: should we deviate??
2483 if (OCIType->qual_empty()) {
2484 Method = LookupInstanceMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002485 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002486 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002487 Diag(SelLoc, diag::warn_maynot_respond)
2488 << OCIType->getInterfaceDecl()->getIdentifier()
2489 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002490 }
2491 }
2492 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002493 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002494 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002495 } else {
John McCall80c93a02013-03-01 09:20:14 +00002496 // Reject other random receiver types (e.g. structs).
2497 Diag(Loc, diag::err_bad_receiver_type)
2498 << ReceiverType << Receiver->getSourceRange();
2499 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002500 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002501 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002502 }
Mike Stump11289f42009-09-09 15:08:12 +00002503
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002504 FunctionScopeInfo *DIFunctionScopeInfo =
2505 (Method && Method->getMethodFamily() == OMF_init)
Craig Topperc3ec1492014-05-26 06:22:03 +00002506 ? getEnclosingFunction() : nullptr;
2507
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002508 if (DIFunctionScopeInfo &&
2509 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002510 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2511 bool isDesignatedInitChain = false;
2512 if (SuperLoc.isValid()) {
2513 if (const ObjCObjectPointerType *
2514 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2515 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
Argyrios Kyrtzidisd664a342013-12-13 03:48:17 +00002516 // Either we know this is a designated initializer or we
2517 // conservatively assume it because we don't know for sure.
2518 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2519 ID->isDesignatedInitializer(Sel)) {
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002520 isDesignatedInitChain = true;
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002521 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002522 }
2523 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002524 }
2525 }
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002526 if (!isDesignatedInitChain) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002527 const ObjCMethodDecl *InitMethod = nullptr;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002528 bool isDesignated =
2529 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2530 assert(isDesignated && InitMethod);
2531 (void)isDesignated;
2532 Diag(SelLoc, SuperLoc.isValid() ?
2533 diag::warn_objc_designated_init_non_designated_init_call :
2534 diag::warn_objc_designated_init_non_super_designated_init_call);
2535 Diag(InitMethod->getLocation(),
2536 diag::note_objc_designated_init_marked_here);
2537 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002538 }
2539
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002540 if (DIFunctionScopeInfo &&
2541 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002542 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2543 if (SuperLoc.isValid()) {
2544 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2545 } else {
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002546 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002547 }
2548 }
2549
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002550 // Check the message arguments.
2551 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002552 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002553 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002554 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00002555 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2556 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002557 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2558 Sel, SelectorLocs, Method,
Douglas Gregor33823722011-06-11 01:09:30 +00002559 ClassMessage, SuperLoc.isValid(),
John McCall7decc9e2010-11-18 06:31:45 +00002560 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002561 return ExprError();
Alp Toker314cc812014-01-25 16:55:45 +00002562
2563 if (Method && !Method->getReturnType()->isVoidType() &&
2564 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002565 diag::err_illegal_message_expr_incomplete_type))
2566 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00002567
John McCall31168b02011-06-15 23:02:42 +00002568 // In ARC, forbid the user from sending messages to
2569 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002570 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002571 ObjCMethodFamily family =
2572 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2573 switch (family) {
2574 case OMF_init:
2575 if (Method)
2576 checkInitMethod(Method, ReceiverType);
2577
2578 case OMF_None:
2579 case OMF_alloc:
2580 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00002581 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002582 case OMF_mutableCopy:
2583 case OMF_new:
2584 case OMF_self:
2585 break;
2586
2587 case OMF_dealloc:
2588 case OMF_retain:
2589 case OMF_release:
2590 case OMF_autorelease:
2591 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002592 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2593 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00002594 break;
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002595
2596 case OMF_performSelector:
2597 if (Method && NumArgs >= 1) {
2598 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2599 Selector ArgSel = SelExp->getSelector();
2600 ObjCMethodDecl *SelMethod =
2601 LookupInstanceMethodInGlobalPool(ArgSel,
2602 SelExp->getSourceRange());
2603 if (!SelMethod)
2604 SelMethod =
2605 LookupFactoryMethodInGlobalPool(ArgSel,
2606 SelExp->getSourceRange());
2607 if (SelMethod) {
2608 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2609 switch (SelFamily) {
2610 case OMF_alloc:
2611 case OMF_copy:
2612 case OMF_mutableCopy:
2613 case OMF_new:
2614 case OMF_self:
2615 case OMF_init:
2616 // Issue error, unless ns_returns_not_retained.
2617 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2618 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002619 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002620 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002621 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2622 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002623 }
2624 break;
2625 default:
2626 // +0 call. OK. unless ns_returns_retained.
2627 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2628 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002629 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002630 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002631 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2632 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002633 }
2634 break;
2635 }
2636 }
2637 } else {
2638 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002639 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002640 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2641 }
2642 }
2643 break;
John McCall31168b02011-06-15 23:02:42 +00002644 }
2645 }
2646
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002647 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00002648 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002649 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002650 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002651 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002652 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002653 makeArrayRef(Args, NumArgs), RBracLoc,
2654 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002655 else {
John McCall7decc9e2010-11-18 06:31:45 +00002656 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002657 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002658 makeArrayRef(Args, NumArgs), RBracLoc,
2659 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002660 if (!isImplicit)
2661 checkCocoaAPI(*this, Result);
2662 }
John McCall31168b02011-06-15 23:02:42 +00002663
David Blaikiebbafb8a2012-03-11 07:00:24 +00002664 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahaniand155c782012-04-19 23:49:39 +00002665 DiagnoseARCUseOfWeakReceiver(*this, Receiver);
Fariborz Jahanian6bd22262012-04-04 20:05:25 +00002666
John McCall31168b02011-06-15 23:02:42 +00002667 // In ARC, annotate delegate init calls.
2668 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00002669 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00002670 // Only consider init calls *directly* in init implementations,
2671 // not within blocks.
2672 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2673 if (method && method->getMethodFamily() == OMF_init) {
2674 // The implicit assignment to self means we also don't want to
2675 // consume the result.
2676 Result->setDelegateInitCall(true);
2677 return Owned(Result);
2678 }
2679 }
2680
2681 // In ARC, check for message sends which are likely to introduce
2682 // retain cycles.
2683 checkRetainCycles(Result);
Jordan Rose22487652012-10-11 16:06:21 +00002684
2685 if (!isImplicit && Method) {
2686 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2687 bool IsWeak =
2688 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2689 if (!IsWeak && Sel.isUnarySelector())
2690 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
2691
2692 if (IsWeak) {
2693 DiagnosticsEngine::Level Level =
2694 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
2695 LBracLoc);
2696 if (Level != DiagnosticsEngine::Ignored)
2697 getCurFunction()->recordUseOfWeak(Result, Prop);
2698
2699 }
2700 }
2701 }
John McCall31168b02011-06-15 23:02:42 +00002702 }
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00002703
Douglas Gregoraae38d62010-05-22 05:17:18 +00002704 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002705}
2706
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002707static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2708 if (ObjCSelectorExpr *OSE =
2709 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2710 Selector Sel = OSE->getSelector();
2711 SourceLocation Loc = OSE->getAtLoc();
2712 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
2713 = S.ReferencedSelectors.find(Sel);
2714 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
2715 S.ReferencedSelectors.erase(Pos);
2716 }
2717}
2718
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002719// ActOnInstanceMessage - used for both unary and keyword messages.
2720// ArgExprs is optional - if it is present, the number of expressions
2721// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002722ExprResult Sema::ActOnInstanceMessage(Scope *S,
2723 Expr *Receiver,
2724 Selector Sel,
2725 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002726 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00002727 SourceLocation RBracLoc,
2728 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002729 if (!Receiver)
2730 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002731
2732 // A ParenListExpr can show up while doing error recovery with invalid code.
2733 if (isa<ParenListExpr>(Receiver)) {
2734 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
2735 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002736 Receiver = Result.get();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002737 }
Fariborz Jahanian17748062013-01-22 19:05:17 +00002738
2739 if (RespondsToSelectorSel.isNull()) {
2740 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
2741 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
2742 }
2743 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002744 RemoveSelectorFromWarningCache(*this, Args[0]);
Craig Topperc3ec1492014-05-26 06:22:03 +00002745
John McCallb268a282010-08-23 23:25:46 +00002746 return BuildInstanceMessage(Receiver, Receiver->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002747 /*SuperLoc=*/SourceLocation(), Sel,
2748 /*Method=*/nullptr, LBracLoc, SelectorLocs,
2749 RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002750}
Chris Lattner2a3569b2008-04-07 05:30:13 +00002751
John McCall31168b02011-06-15 23:02:42 +00002752enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00002753 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00002754 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00002755
2756 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00002757 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00002758
2759 /// id*, id***, void (^*)(),
2760 ACTC_indirectRetainable,
2761
2762 /// void* might be a normal C type, or it might a CF type.
2763 ACTC_voidPtr,
2764
2765 /// struct A*
2766 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00002767};
John McCalle4fe2452011-10-01 01:01:08 +00002768static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2769 return (ACTC == ACTC_retainable ||
2770 ACTC == ACTC_coreFoundation ||
2771 ACTC == ACTC_voidPtr);
2772}
2773static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2774 return ACTC == ACTC_none ||
2775 ACTC == ACTC_voidPtr ||
2776 ACTC == ACTC_coreFoundation;
2777}
2778
John McCall31168b02011-06-15 23:02:42 +00002779static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00002780 bool isIndirect = false;
John McCall31168b02011-06-15 23:02:42 +00002781
2782 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00002783 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00002784 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002785 isIndirect = true;
2786 }
John McCall31168b02011-06-15 23:02:42 +00002787
2788 // Drill through pointers and arrays recursively.
2789 while (true) {
2790 if (const PointerType *ptr = type->getAs<PointerType>()) {
2791 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002792
2793 // The first level of pointer may be the innermost pointer on a CF type.
2794 if (!isIndirect) {
2795 if (type->isVoidType()) return ACTC_voidPtr;
2796 if (type->isRecordType()) return ACTC_coreFoundation;
2797 }
John McCall31168b02011-06-15 23:02:42 +00002798 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2799 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2800 } else {
2801 break;
2802 }
John McCalle4fe2452011-10-01 01:01:08 +00002803 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00002804 }
2805
John McCalle4fe2452011-10-01 01:01:08 +00002806 if (isIndirect) {
2807 if (type->isObjCARCBridgableType())
2808 return ACTC_indirectRetainable;
2809 return ACTC_none;
2810 }
2811
2812 if (type->isObjCARCBridgableType())
2813 return ACTC_retainable;
2814
2815 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00002816}
2817
2818namespace {
John McCalle4fe2452011-10-01 01:01:08 +00002819 /// A result from the cast checker.
2820 enum ACCResult {
2821 /// Cannot be casted.
2822 ACC_invalid,
2823
2824 /// Can be safely retained or not retained.
2825 ACC_bottom,
2826
2827 /// Can be casted at +0.
2828 ACC_plusZero,
2829
2830 /// Can be casted at +1.
2831 ACC_plusOne
2832 };
2833 ACCResult merge(ACCResult left, ACCResult right) {
2834 if (left == right) return left;
2835 if (left == ACC_bottom) return right;
2836 if (right == ACC_bottom) return left;
2837 return ACC_invalid;
2838 }
2839
2840 /// A checker which white-lists certain expressions whose conversion
2841 /// to or from retainable type would otherwise be forbidden in ARC.
2842 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2843 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2844
John McCall31168b02011-06-15 23:02:42 +00002845 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00002846 ARCConversionTypeClass SourceClass;
2847 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002848 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00002849
2850 static bool isCFType(QualType type) {
2851 // Someday this can use ns_bridged. For now, it has to do this.
2852 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00002853 }
John McCalle4fe2452011-10-01 01:01:08 +00002854
2855 public:
2856 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002857 ARCConversionTypeClass target, bool diagnose)
2858 : Context(Context), SourceClass(source), TargetClass(target),
2859 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00002860
2861 using super::Visit;
2862 ACCResult Visit(Expr *e) {
2863 return super::Visit(e->IgnoreParens());
2864 }
2865
2866 ACCResult VisitStmt(Stmt *s) {
2867 return ACC_invalid;
2868 }
2869
2870 /// Null pointer constants can be casted however you please.
2871 ACCResult VisitExpr(Expr *e) {
2872 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2873 return ACC_bottom;
2874 return ACC_invalid;
2875 }
2876
2877 /// Objective-C string literals can be safely casted.
2878 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2879 // If we're casting to any retainable type, go ahead. Global
2880 // strings are immune to retains, so this is bottom.
2881 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2882
2883 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002884 }
2885
John McCalle4fe2452011-10-01 01:01:08 +00002886 /// Look through certain implicit and explicit casts.
2887 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002888 switch (e->getCastKind()) {
2889 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00002890 return ACC_bottom;
2891
John McCall31168b02011-06-15 23:02:42 +00002892 case CK_NoOp:
2893 case CK_LValueToRValue:
2894 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002895 case CK_CPointerToObjCPointerCast:
2896 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002897 case CK_AnyPointerToBlockPointerCast:
2898 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00002899
John McCall31168b02011-06-15 23:02:42 +00002900 default:
John McCalle4fe2452011-10-01 01:01:08 +00002901 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002902 }
2903 }
John McCalle4fe2452011-10-01 01:01:08 +00002904
2905 /// Look through unary extension.
2906 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002907 return Visit(e->getSubExpr());
2908 }
John McCalle4fe2452011-10-01 01:01:08 +00002909
2910 /// Ignore the LHS of a comma operator.
2911 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002912 return Visit(e->getRHS());
2913 }
John McCalle4fe2452011-10-01 01:01:08 +00002914
2915 /// Conditional operators are okay if both sides are okay.
2916 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2917 ACCResult left = Visit(e->getTrueExpr());
2918 if (left == ACC_invalid) return ACC_invalid;
2919 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00002920 }
John McCalle4fe2452011-10-01 01:01:08 +00002921
John McCallfe96e0b2011-11-06 09:01:30 +00002922 /// Look through pseudo-objects.
2923 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2924 // If we're getting here, we should always have a result.
2925 return Visit(e->getResultExpr());
2926 }
2927
John McCalle4fe2452011-10-01 01:01:08 +00002928 /// Statement expressions are okay if their result expression is okay.
2929 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002930 return Visit(e->getSubStmt()->body_back());
2931 }
John McCall31168b02011-06-15 23:02:42 +00002932
John McCalle4fe2452011-10-01 01:01:08 +00002933 /// Some declaration references are okay.
2934 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2935 // References to global constants from system headers are okay.
2936 // These are things like 'kCFStringTransformToLatin'. They are
2937 // can also be assumed to be immune to retains.
2938 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2939 if (isAnyRetainable(TargetClass) &&
2940 isAnyRetainable(SourceClass) &&
2941 var &&
2942 var->getStorageClass() == SC_Extern &&
2943 var->getType().isConstQualified() &&
2944 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2945 return ACC_bottom;
2946 }
2947
2948 // Nothing else.
2949 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00002950 }
John McCalle4fe2452011-10-01 01:01:08 +00002951
2952 /// Some calls are okay.
2953 ACCResult VisitCallExpr(CallExpr *e) {
2954 if (FunctionDecl *fn = e->getDirectCallee())
2955 if (ACCResult result = checkCallToFunction(fn))
2956 return result;
2957
2958 return super::VisitCallExpr(e);
2959 }
2960
2961 ACCResult checkCallToFunction(FunctionDecl *fn) {
2962 // Require a CF*Ref return type.
Alp Toker314cc812014-01-25 16:55:45 +00002963 if (!isCFType(fn->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00002964 return ACC_invalid;
2965
2966 if (!isAnyRetainable(TargetClass))
2967 return ACC_invalid;
2968
2969 // Honor an explicit 'not retained' attribute.
2970 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2971 return ACC_plusZero;
2972
2973 // Honor an explicit 'retained' attribute, except that for
2974 // now we're not going to permit implicit handling of +1 results,
2975 // because it's a bit frightening.
2976 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00002977 return Diagnose ? ACC_plusOne
2978 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00002979
2980 // Recognize this specific builtin function, which is used by CFSTR.
2981 unsigned builtinID = fn->getBuiltinID();
2982 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2983 return ACC_bottom;
2984
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00002985 // Otherwise, don't do anything implicit with an unaudited function.
2986 if (!fn->hasAttr<CFAuditedTransferAttr>())
2987 return ACC_invalid;
2988
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002989 // Otherwise, it's +0 unless it follows the create convention.
2990 if (ento::coreFoundation::followsCreateRule(fn))
2991 return Diagnose ? ACC_plusOne
2992 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00002993
John McCalle4fe2452011-10-01 01:01:08 +00002994 return ACC_plusZero;
2995 }
2996
2997 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
2998 return checkCallToMethod(e->getMethodDecl());
2999 }
3000
3001 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3002 ObjCMethodDecl *method;
3003 if (e->isExplicitProperty())
3004 method = e->getExplicitProperty()->getGetterMethodDecl();
3005 else
3006 method = e->getImplicitPropertyGetter();
3007 return checkCallToMethod(method);
3008 }
3009
3010 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3011 if (!method) return ACC_invalid;
3012
3013 // Check for message sends to functions returning CF types. We
3014 // just obey the Cocoa conventions with these, even though the
3015 // return type is CF.
Alp Toker314cc812014-01-25 16:55:45 +00003016 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003017 return ACC_invalid;
3018
3019 // If the method is explicitly marked not-retained, it's +0.
3020 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3021 return ACC_plusZero;
3022
3023 // If the method is explicitly marked as returning retained, or its
3024 // selector follows a +1 Cocoa convention, treat it as +1.
3025 if (method->hasAttr<CFReturnsRetainedAttr>())
3026 return ACC_plusOne;
3027
3028 switch (method->getSelector().getMethodFamily()) {
3029 case OMF_alloc:
3030 case OMF_copy:
3031 case OMF_mutableCopy:
3032 case OMF_new:
3033 return ACC_plusOne;
3034
3035 default:
3036 // Otherwise, treat it as +0.
3037 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00003038 }
3039 }
John McCalle4fe2452011-10-01 01:01:08 +00003040 };
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00003041}
3042
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003043bool Sema::isKnownName(StringRef name) {
3044 if (name.empty())
3045 return false;
3046 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003047 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003048 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003049}
3050
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003051static void addFixitForObjCARCConversion(Sema &S,
3052 DiagnosticBuilder &DiagB,
3053 Sema::CheckedConversionKind CCK,
3054 SourceLocation afterLParen,
3055 QualType castType,
3056 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003057 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003058 const char *bridgeKeyword,
3059 const char *CFBridgeName) {
3060 // We handle C-style and implicit casts here.
3061 switch (CCK) {
3062 case Sema::CCK_ImplicitConversion:
3063 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003064 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003065 break;
3066 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003067 return;
3068 }
3069
3070 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003071 if (CCK == Sema::CCK_OtherCast) {
3072 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3073 SourceRange range(NCE->getOperatorLoc(),
3074 NCE->getAngleBrackets().getEnd());
3075 SmallString<32> BridgeCall;
3076
3077 SourceManager &SM = S.getSourceManager();
3078 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3079 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3080 BridgeCall += ' ';
3081
3082 BridgeCall += CFBridgeName;
3083 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3084 }
3085 return;
3086 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003087 Expr *castedE = castExpr;
3088 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3089 castedE = CCE->getSubExpr();
3090 castedE = castedE->IgnoreImpCasts();
3091 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00003092
3093 SmallString<32> BridgeCall;
3094
3095 SourceManager &SM = S.getSourceManager();
3096 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3097 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3098 BridgeCall += ' ';
3099
3100 BridgeCall += CFBridgeName;
3101
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003102 if (isa<ParenExpr>(castedE)) {
3103 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003104 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003105 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00003106 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003107 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003108 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003109 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3110 S.PP.getLocForEndOfToken(range.getEnd()),
3111 ")"));
3112 }
3113 return;
3114 }
3115
3116 if (CCK == Sema::CCK_CStyleCast) {
3117 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003118 } else if (CCK == Sema::CCK_OtherCast) {
3119 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3120 std::string castCode = "(";
3121 castCode += bridgeKeyword;
3122 castCode += castType.getAsString();
3123 castCode += ")";
3124 SourceRange Range(NCE->getOperatorLoc(),
3125 NCE->getAngleBrackets().getEnd());
3126 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3127 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003128 } else {
3129 std::string castCode = "(";
3130 castCode += bridgeKeyword;
3131 castCode += castType.getAsString();
3132 castCode += ")";
3133 Expr *castedE = castExpr->IgnoreImpCasts();
3134 SourceRange range = castedE->getSourceRange();
3135 if (isa<ParenExpr>(castedE)) {
3136 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3137 castCode));
3138 } else {
3139 castCode += "(";
3140 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3141 castCode));
3142 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3143 S.PP.getLocForEndOfToken(range.getEnd()),
3144 ")"));
3145 }
3146 }
3147}
3148
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003149template <typename T>
3150static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3151 TypedefNameDecl *TDNDecl = TD->getDecl();
3152 QualType QT = TDNDecl->getUnderlyingType();
3153 if (QT->isPointerType()) {
3154 QT = QT->getPointeeType();
3155 if (const RecordType *RT = QT->getAs<RecordType>())
3156 if (RecordDecl *RD = RT->getDecl())
Aaron Ballman2084f8f2013-12-19 13:20:36 +00003157 return RD->getAttr<T>();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003158 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003159 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003160}
3161
3162static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3163 TypedefNameDecl *&TDNDecl) {
3164 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3165 TDNDecl = TD->getDecl();
3166 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3167 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3168 return ObjCBAttr;
3169 T = TDNDecl->getUnderlyingType();
3170 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003171 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003172}
3173
John McCall4124c492011-10-17 18:40:02 +00003174static void
3175diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3176 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003177 Expr *castExpr, Expr *realCast,
3178 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003179 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003180 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003181 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00003182
John McCall4124c492011-10-17 18:40:02 +00003183 if (S.makeUnavailableInSystemHeader(loc,
John McCalle4fe2452011-10-01 01:01:08 +00003184 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCall31168b02011-06-15 23:02:42 +00003185 return;
John McCall4124c492011-10-17 18:40:02 +00003186
3187 QualType castExprType = castExpr->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003188 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003189 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3190 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3191 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
3192 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
3193 return;
John McCall31168b02011-06-15 23:02:42 +00003194
John McCall640767f2011-06-17 06:50:50 +00003195 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003196 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003197 case ACTC_none:
3198 case ACTC_coreFoundation:
3199 case ACTC_voidPtr:
3200 srcKind = (castExprType->isPointerType() ? 1 : 0);
3201 break;
3202 case ACTC_retainable:
3203 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3204 break;
3205 case ACTC_indirectRetainable:
3206 srcKind = 4;
3207 break;
John McCall31168b02011-06-15 23:02:42 +00003208 }
3209
John McCall4124c492011-10-17 18:40:02 +00003210 // Check whether this could be fixed with a bridge cast.
3211 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3212 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003213
John McCall4124c492011-10-17 18:40:02 +00003214 // Bridge from an ARC type to a CF type.
3215 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003216
John McCall4124c492011-10-17 18:40:02 +00003217 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3218 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3219 << 2 // of C pointer type
3220 << castExprType
3221 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3222 << castType
3223 << castRange
3224 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003225 bool br = S.isKnownName("CFBridgingRelease");
Jordan Rose4502b532012-07-31 01:07:43 +00003226 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003227 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003228 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003229 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003230 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003231 DiagnosticBuilder DiagB =
3232 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3233 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Craig Topperc3ec1492014-05-26 06:22:03 +00003234
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003235 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003236 castType, castExpr, realCast, "__bridge ",
3237 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003238 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003239 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003240 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003241 DiagnosticBuilder DiagB =
3242 (CCK == Sema::CCK_OtherCast && !br) ?
3243 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3244 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3245 diag::note_arc_bridge_transfer)
3246 << castExprType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003247
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003248 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003249 castType, castExpr, realCast, "__bridge_transfer ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003250 br ? "CFBridgingRelease" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003251 }
John McCall4124c492011-10-17 18:40:02 +00003252
3253 return;
3254 }
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003255
John McCall4124c492011-10-17 18:40:02 +00003256 // Bridge from a CF type to an ARC type.
3257 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003258 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003259 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3260 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3261 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3262 << castExprType
3263 << 2 // to C pointer type
3264 << castType
3265 << castRange
3266 << castExpr->getSourceRange();
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003267 ACCResult CreateRule =
3268 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003269 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003270 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003271 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003272 DiagnosticBuilder DiagB =
3273 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3274 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003275 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003276 castType, castExpr, realCast, "__bridge ",
3277 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003278 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003279 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003280 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003281 DiagnosticBuilder DiagB =
3282 (CCK == Sema::CCK_OtherCast && !br) ?
3283 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3284 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3285 diag::note_arc_bridge_retained)
3286 << castType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003287
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003288 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003289 castType, castExpr, realCast, "__bridge_retained ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003290 br ? "CFBridgingRetain" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003291 }
John McCall4124c492011-10-17 18:40:02 +00003292
3293 return;
John McCall31168b02011-06-15 23:02:42 +00003294 }
3295
John McCall4124c492011-10-17 18:40:02 +00003296 S.Diag(loc, diag::err_arc_mismatched_cast)
3297 << (CCK != Sema::CCK_ImplicitConversion)
3298 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003299 << castRange << castExpr->getSourceRange();
3300}
3301
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003302template <typename TB>
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003303static void CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr) {
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003304 QualType T = castExpr->getType();
3305 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3306 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003307 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003308 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003309 NamedDecl *Target = nullptr;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003310 // Check for an existing type with this name.
3311 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3312 Sema::LookupOrdinaryName);
3313 if (S.LookupName(R, S.TUScope)) {
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003314 Target = R.getFoundDecl();
3315 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3316 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3317 if (const ObjCObjectPointerType *InterfacePointerType =
3318 castType->getAsObjCInterfacePointerType()) {
3319 ObjCInterfaceDecl *CastClass
3320 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003321 if ((CastClass == ExprClass) ||
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003322 (CastClass && ExprClass->isSuperClassOf(CastClass)))
3323 return;
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003324 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
Fariborz Jahanian509f31e2013-11-19 01:23:07 +00003325 << T << Target->getName() << castType->getPointeeType();
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003326 return;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003327 } else if (castType->isObjCIdType() ||
3328 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3329 castType, ExprClass)))
3330 // ok to cast to 'id'.
3331 // casting to id<p-list> is ok if bridge type adopts all of
3332 // p-list protocols.
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003333 return;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003334 else {
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003335 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
Fariborz Jahanian509f31e2013-11-19 01:23:07 +00003336 << T << Target->getName() << castType;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003337 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3338 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003339 return;
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003340 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003341 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003342 }
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003343 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
Aaron Ballmanc0550742014-01-03 02:07:43 +00003344 << castExpr->getType() << Parm;
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003345 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3346 if (Target)
3347 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003348 }
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003349 return;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003350 }
3351 T = TDNDecl->getUnderlyingType();
3352 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003353}
3354
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003355template <typename TB>
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003356static void CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr) {
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003357 QualType T = castType;
3358 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3359 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003360 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003361 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003362 NamedDecl *Target = nullptr;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003363 // Check for an existing type with this name.
3364 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3365 Sema::LookupOrdinaryName);
3366 if (S.LookupName(R, S.TUScope)) {
3367 Target = R.getFoundDecl();
3368 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3369 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3370 if (const ObjCObjectPointerType *InterfacePointerType =
3371 castExpr->getType()->getAsObjCInterfacePointerType()) {
3372 ObjCInterfaceDecl *ExprClass
3373 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003374 if ((CastClass == ExprClass) ||
3375 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003376 return;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003377 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
Fariborz Jahanian509f31e2013-11-19 01:23:07 +00003378 << castExpr->getType()->getPointeeType() << T;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003379 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003380 return;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003381 } else if (castExpr->getType()->isObjCIdType() ||
3382 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3383 castExpr->getType(), CastClass)))
3384 // ok to cast an 'id' expression to a CFtype.
3385 // ok to cast an 'id<plist>' expression to CFtype provided plist
3386 // adopts all of CFtype's ObjetiveC's class plist.
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003387 return;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003388 else {
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003389 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3390 << castExpr->getType() << castType;
3391 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003392 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003393 return;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003394 }
3395 }
3396 }
3397 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3398 << castExpr->getType() << castType;
3399 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3400 if (Target)
3401 S.Diag(Target->getLocStart(), diag::note_declared_at);
3402 }
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003403 return;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003404 }
3405 T = TDNDecl->getUnderlyingType();
3406 }
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003407}
3408
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003409void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003410 if (!getLangOpts().ObjC1)
3411 return;
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003412 // warn in presence of __bridge casting to or from a toll free bridge cast.
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003413 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3414 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003415 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003416 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr);
3417 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003418 }
3419 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003420 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr);
3421 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003422 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003423}
3424
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00003425bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3426 CastKind &Kind) {
3427 if (!getLangOpts().ObjC1)
3428 return false;
3429 ARCConversionTypeClass exprACTC =
3430 classifyTypeForARCConversion(castExpr->getType());
3431 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3432 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3433 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3434 CheckTollFreeBridgeCast(castType, castExpr);
3435 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3436 : CK_CPointerToObjCPointerCast;
3437 return true;
3438 }
3439 return false;
3440}
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003441
3442bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3443 QualType DestType, QualType SrcType,
3444 ObjCInterfaceDecl *&RelatedClass,
3445 ObjCMethodDecl *&ClassMethod,
3446 ObjCMethodDecl *&InstanceMethod,
3447 TypedefNameDecl *&TDNDecl,
3448 bool CfToNs) {
3449 QualType T = CfToNs ? SrcType : DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003450 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3451 if (!ObjCBAttr)
3452 return false;
3453
3454 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3455 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3456 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3457 if (!RCId)
3458 return false;
Craig Topperc3ec1492014-05-26 06:22:03 +00003459 NamedDecl *Target = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003460 // Check for an existing type with this name.
3461 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3462 Sema::LookupOrdinaryName);
3463 if (!LookupName(R, TUScope)) {
3464 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003465 << SrcType << DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003466 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3467 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003468 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003469 Target = R.getFoundDecl();
3470 if (Target && isa<ObjCInterfaceDecl>(Target))
3471 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3472 else {
3473 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3474 << SrcType << DestType;
3475 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3476 if (Target)
3477 Diag(Target->getLocStart(), diag::note_declared_at);
3478 return false;
3479 }
3480
3481 // Check for an existing class method with the given selector name.
3482 if (CfToNs && CMId) {
3483 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3484 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3485 if (!ClassMethod) {
3486 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003487 << SrcType << DestType << Sel << false;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003488 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3489 return false;
3490 }
3491 }
3492
3493 // Check for an existing instance method with the given selector name.
3494 if (!CfToNs && IMId) {
3495 Selector Sel = Context.Selectors.getNullarySelector(IMId);
3496 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3497 if (!InstanceMethod) {
3498 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003499 << SrcType << DestType << Sel << true;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003500 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3501 return false;
3502 }
3503 }
3504 return true;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003505}
3506
3507bool
3508Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003509 QualType DestType, QualType SrcType,
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003510 Expr *&SrcExpr) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003511 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3512 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3513 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3514 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3515 if (!CfToNs && !NsToCf)
3516 return false;
3517
3518 ObjCInterfaceDecl *RelatedClass;
Craig Topperc3ec1492014-05-26 06:22:03 +00003519 ObjCMethodDecl *ClassMethod = nullptr;
3520 ObjCMethodDecl *InstanceMethod = nullptr;
3521 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003522 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
3523 ClassMethod, InstanceMethod, TDNDecl, CfToNs))
3524 return false;
3525
3526 if (CfToNs) {
3527 // Implicit conversion from CF to ObjC object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003528 if (ClassMethod) {
3529 std::string ExpressionString = "[";
3530 ExpressionString += RelatedClass->getNameAsString();
3531 ExpressionString += " ";
3532 ExpressionString += ClassMethod->getSelector().getAsString();
3533 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3534 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003535 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003536 << SrcType << DestType << ClassMethod->getSelector() << false
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003537 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3538 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003539 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3540 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3541
3542 QualType receiverType =
3543 Context.getObjCInterfaceType(RelatedClass);
3544 // Argument.
3545 Expr *args[] = { SrcExpr };
3546 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
3547 ClassMethod->getLocation(),
3548 ClassMethod->getSelector(), ClassMethod,
3549 MultiExprArg(args, 1));
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003550 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003551 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003552 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003553 }
3554 else {
3555 // Implicit conversion from ObjC type to CF object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003556 if (InstanceMethod) {
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003557 std::string ExpressionString;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003558 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003559 if (InstanceMethod->isPropertyAccessor())
3560 if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
3561 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
3562 ExpressionString = ".";
3563 ExpressionString += PDecl->getNameAsString();
3564 Diag(Loc, diag::err_objc_bridged_related_known_method)
3565 << SrcType << DestType << InstanceMethod->getSelector() << true
3566 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3567 }
3568 if (ExpressionString.empty()) {
3569 // Provide a fixit: [ObjectExpr InstanceMethod]
3570 ExpressionString = " ";
3571 ExpressionString += InstanceMethod->getSelector().getAsString();
3572 ExpressionString += "]";
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003573
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003574 Diag(Loc, diag::err_objc_bridged_related_known_method)
3575 << SrcType << DestType << InstanceMethod->getSelector() << true
3576 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3577 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3578 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003579 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3580 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3581
3582 ExprResult msg =
3583 BuildInstanceMessageImplicit(SrcExpr, SrcType,
3584 InstanceMethod->getLocation(),
3585 InstanceMethod->getSelector(),
3586 InstanceMethod, None);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003587 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003588 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003589 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003590 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003591 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003592}
3593
John McCall4124c492011-10-17 18:40:02 +00003594Sema::ARCConversionResult
3595Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003596 Expr *&castExpr, CheckedConversionKind CCK,
3597 bool DiagnoseCFAudited) {
John McCall4124c492011-10-17 18:40:02 +00003598 QualType castExprType = castExpr->getType();
3599
3600 // For the purposes of the classification, we assume reference types
3601 // will bind to temporaries.
3602 QualType effCastType = castType;
3603 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3604 effCastType = ref->getPointeeType();
3605
3606 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3607 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003608 if (exprACTC == castACTC) {
3609 // check for viablity and report error if casting an rvalue to a
3610 // life-time qualifier.
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003611 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003612 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003613 (castType != castExprType)) {
3614 const Type *DT = castType.getTypePtr();
3615 QualType QDT = castType;
3616 // We desugar some types but not others. We ignore those
3617 // that cannot happen in a cast; i.e. auto, and those which
3618 // should not be de-sugared; i.e typedef.
3619 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3620 QDT = PT->desugar();
3621 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3622 QDT = TP->desugar();
3623 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3624 QDT = AT->desugar();
3625 if (QDT != castType &&
3626 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3627 SourceLocation loc =
3628 (castRange.isValid() ? castRange.getBegin()
3629 : castExpr->getExprLoc());
3630 Diag(loc, diag::err_arc_nolifetime_behavior);
3631 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003632 }
3633 return ACR_okay;
3634 }
3635
John McCall4124c492011-10-17 18:40:02 +00003636 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
3637
3638 // Allow all of these types to be cast to integer types (but not
3639 // vice-versa).
3640 if (castACTC == ACTC_none && castType->isIntegralType(Context))
3641 return ACR_okay;
3642
3643 // Allow casts between pointers to lifetime types (e.g., __strong id*)
3644 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
3645 // must be explicit.
3646 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
3647 return ACR_okay;
3648 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
3649 CCK != CCK_ImplicitConversion)
3650 return ACR_okay;
3651
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003652 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00003653 // For invalid casts, fall through.
3654 case ACC_invalid:
3655 break;
3656
3657 // Do nothing for both bottom and +0.
3658 case ACC_bottom:
3659 case ACC_plusZero:
3660 return ACR_okay;
3661
3662 // If the result is +1, consume it here.
3663 case ACC_plusOne:
3664 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3665 CK_ARCConsumeObject, castExpr,
Craig Topperc3ec1492014-05-26 06:22:03 +00003666 nullptr, VK_RValue);
John McCall4124c492011-10-17 18:40:02 +00003667 ExprNeedsCleanups = true;
3668 return ACR_okay;
3669 }
3670
3671 // If this is a non-implicit cast from id or block type to a
3672 // CoreFoundation type, delay complaining in case the cast is used
3673 // in an acceptable context.
3674 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3675 CCK != CCK_ImplicitConversion)
3676 return ACR_unbridged;
3677
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003678 // Do not issue bridge cast" diagnostic when implicit casting a cstring
3679 // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
3680 // suitable fix-it.
Fariborz Jahanian283bf892013-12-18 21:04:43 +00003681 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
3682 ConversionToObjCStringLiteralCheck(castType, castExpr))
3683 return ACR_okay;
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003684
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003685 // Do not issue "bridge cast" diagnostic when implicit casting
3686 // a retainable object to a CF type parameter belonging to an audited
3687 // CF API function. Let caller issue a normal type mismatched diagnostic
3688 // instead.
3689 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
3690 castACTC != ACTC_coreFoundation)
3691 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3692 castExpr, castExpr, exprACTC, CCK);
John McCall4124c492011-10-17 18:40:02 +00003693 return ACR_okay;
3694}
3695
3696/// Given that we saw an expression with the ARCUnbridgedCastTy
3697/// placeholder type, complain bitterly.
3698void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3699 // We expect the spurious ImplicitCastExpr to already have been stripped.
3700 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3701 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3702
3703 SourceRange castRange;
3704 QualType castType;
3705 CheckedConversionKind CCK;
3706
3707 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3708 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3709 castType = cast->getTypeAsWritten();
3710 CCK = CCK_CStyleCast;
3711 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3712 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3713 castType = cast->getTypeAsWritten();
3714 CCK = CCK_OtherCast;
3715 } else {
3716 castType = cast->getType();
3717 CCK = CCK_ImplicitConversion;
3718 }
3719
3720 ARCConversionTypeClass castACTC =
3721 classifyTypeForARCConversion(castType.getNonReferenceType());
3722
3723 Expr *castExpr = realCast->getSubExpr();
3724 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3725
3726 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003727 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00003728}
3729
3730/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3731/// type, remove the placeholder cast.
3732Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3733 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3734
3735 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3736 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3737 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3738 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3739 assert(uo->getOpcode() == UO_Extension);
3740 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3741 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3742 sub->getValueKind(), sub->getObjectKind(),
3743 uo->getOperatorLoc());
3744 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3745 assert(!gse->isResultDependent());
3746
3747 unsigned n = gse->getNumAssocs();
3748 SmallVector<Expr*, 4> subExprs(n);
3749 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3750 for (unsigned i = 0; i != n; ++i) {
3751 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3752 Expr *sub = gse->getAssocExpr(i);
3753 if (i == gse->getResultIndex())
3754 sub = stripARCUnbridgedCast(sub);
3755 subExprs[i] = sub;
3756 }
3757
3758 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3759 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003760 subTypes, subExprs,
3761 gse->getDefaultLoc(),
John McCall4124c492011-10-17 18:40:02 +00003762 gse->getRParenLoc(),
3763 gse->containsUnexpandedParameterPack(),
3764 gse->getResultIndex());
3765 } else {
3766 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3767 return cast<ImplicitCastExpr>(e)->getSubExpr();
3768 }
3769}
3770
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003771bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3772 QualType exprType) {
3773 QualType canCastType =
3774 Context.getCanonicalType(castType).getUnqualifiedType();
3775 QualType canExprType =
3776 Context.getCanonicalType(exprType).getUnqualifiedType();
3777 if (isa<ObjCObjectPointerType>(canCastType) &&
3778 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3779 canExprType->isObjCObjectPointerType()) {
3780 if (const ObjCObjectPointerType *ObjT =
3781 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00003782 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
3783 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003784 }
3785 return true;
3786}
3787
John McCall4db5c3c2011-07-07 06:58:02 +00003788/// Look for an ObjCReclaimReturnedObject cast and destroy it.
3789static Expr *maybeUndoReclaimObject(Expr *e) {
3790 // For now, we just undo operands that are *immediately* reclaim
3791 // expressions, which prevents the vast majority of potential
3792 // problems here. To catch them all, we'd need to rebuild arbitrary
3793 // value-propagating subexpressions --- we can't reliably rebuild
3794 // in-place because of expression sharing.
3795 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall2d637d22011-09-10 06:18:15 +00003796 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall4db5c3c2011-07-07 06:58:02 +00003797 return ice->getSubExpr();
3798
3799 return e;
3800}
3801
John McCall31168b02011-06-15 23:02:42 +00003802ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3803 ObjCBridgeCastKind Kind,
3804 SourceLocation BridgeKeywordLoc,
3805 TypeSourceInfo *TSInfo,
3806 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00003807 ExprResult SubResult = UsualUnaryConversions(SubExpr);
3808 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003809 SubExpr = SubResult.get();
John McCalleb075542011-08-26 00:48:42 +00003810
John McCall31168b02011-06-15 23:02:42 +00003811 QualType T = TSInfo->getType();
3812 QualType FromType = SubExpr->getType();
3813
John McCall9320b872011-09-09 05:25:32 +00003814 CastKind CK;
3815
John McCall31168b02011-06-15 23:02:42 +00003816 bool MustConsume = false;
3817 if (T->isDependentType() || SubExpr->isTypeDependent()) {
3818 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00003819 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00003820 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3821 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00003822 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3823 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00003824 switch (Kind) {
3825 case OBC_Bridge:
3826 break;
3827
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003828 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003829 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00003830 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3831 << 2
3832 << FromType
3833 << (T->isBlockPointerType()? 1 : 0)
3834 << T
3835 << SubExpr->getSourceRange()
3836 << Kind;
3837 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3838 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3839 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003840 << FromType << br
John McCall31168b02011-06-15 23:02:42 +00003841 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003842 br ? "CFBridgingRelease "
3843 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00003844
3845 Kind = OBC_Bridge;
3846 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003847 }
John McCall31168b02011-06-15 23:02:42 +00003848
3849 case OBC_BridgeTransfer:
3850 // We must consume the Objective-C object produced by the cast.
3851 MustConsume = true;
3852 break;
3853 }
3854 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3855 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00003856 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00003857 switch (Kind) {
3858 case OBC_Bridge:
John McCall4db5c3c2011-07-07 06:58:02 +00003859 // Reclaiming a value that's going to be __bridge-casted to CF
3860 // is very dangerous, so we don't do it.
3861 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCall31168b02011-06-15 23:02:42 +00003862 break;
3863
3864 case OBC_BridgeRetained:
3865 // Produce the object before casting it.
3866 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00003867 CK_ARCProduceObject,
Craig Topperc3ec1492014-05-26 06:22:03 +00003868 SubExpr, nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00003869 break;
3870
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003871 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003872 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00003873 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3874 << (FromType->isBlockPointerType()? 1 : 0)
3875 << FromType
3876 << 2
3877 << T
3878 << SubExpr->getSourceRange()
3879 << Kind;
3880
3881 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3882 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3883 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003884 << T << br
3885 << FixItHint::CreateReplacement(BridgeKeywordLoc,
3886 br ? "CFBridgingRetain " : "__bridge_retained");
John McCall31168b02011-06-15 23:02:42 +00003887
3888 Kind = OBC_Bridge;
3889 break;
3890 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003891 }
John McCall31168b02011-06-15 23:02:42 +00003892 } else {
3893 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3894 << FromType << T << Kind
3895 << SubExpr->getSourceRange()
3896 << TSInfo->getTypeLoc().getSourceRange();
3897 return ExprError();
3898 }
3899
John McCall9320b872011-09-09 05:25:32 +00003900 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00003901 BridgeKeywordLoc,
3902 TSInfo, SubExpr);
3903
3904 if (MustConsume) {
3905 ExprNeedsCleanups = true;
John McCall2d637d22011-09-10 06:18:15 +00003906 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
Craig Topperc3ec1492014-05-26 06:22:03 +00003907 nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00003908 }
3909
3910 return Result;
3911}
3912
3913ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
3914 SourceLocation LParenLoc,
3915 ObjCBridgeCastKind Kind,
3916 SourceLocation BridgeKeywordLoc,
3917 ParsedType Type,
3918 SourceLocation RParenLoc,
3919 Expr *SubExpr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003920 TypeSourceInfo *TSInfo = nullptr;
John McCall31168b02011-06-15 23:02:42 +00003921 QualType T = GetTypeFromParser(Type, &TSInfo);
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003922 if (Kind == OBC_Bridge)
3923 CheckTollFreeBridgeCast(T, SubExpr);
John McCall31168b02011-06-15 23:02:42 +00003924 if (!TSInfo)
3925 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3926 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
3927 SubExpr);
3928}