blob: 6cc1658934d48276717d592eeaa5290b08d2ebd1 [file] [log] [blame]
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for Objective-C expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnera3fc41d2008-01-04 22:32:30 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
Steve Naroff021ca182008-05-29 21:12:08 +000017#include "clang/AST/ExprObjC.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor0c78ad92010-04-21 19:57:20 +000019#include "clang/AST/TypeLoc.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
21#include "clang/Edit/Commit.h"
22#include "clang/Edit/Rewriters.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000023#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/Initialization.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/Scope.h"
27#include "clang/Sema/ScopeInfo.h"
28#include "llvm/ADT/SmallString.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000029
Chris Lattnera3fc41d2008-01-04 22:32:30 +000030using namespace clang;
John McCall5f2d5562011-02-03 09:00:02 +000031using namespace sema;
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +000032using llvm::makeArrayRef;
Chris Lattnera3fc41d2008-01-04 22:32:30 +000033
John McCallfaf5fb42010-08-26 23:41:50 +000034ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
35 Expr **strings,
36 unsigned NumStrings) {
Chris Lattner163ffd22009-02-18 06:48:40 +000037 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
38
Chris Lattnerd7670d92009-02-18 06:13:04 +000039 // Most ObjC strings are formed out of a single piece. However, we *can*
40 // have strings formed out of multiple @ strings with multiple pptokens in
41 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
42 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner163ffd22009-02-18 06:48:40 +000043 StringLiteral *S = Strings[0];
Mike Stump11289f42009-09-09 15:08:12 +000044
Chris Lattnerd7670d92009-02-18 06:13:04 +000045 // If we have a multi-part string, merge it all together.
46 if (NumStrings != 1) {
Chris Lattnera3fc41d2008-01-04 22:32:30 +000047 // Concatenate objc strings.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000048 SmallString<128> StrBuf;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000049 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump11289f42009-09-09 15:08:12 +000050
Chris Lattner630970d2009-02-18 05:49:11 +000051 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner163ffd22009-02-18 06:48:40 +000052 S = Strings[i];
Mike Stump11289f42009-09-09 15:08:12 +000053
Douglas Gregorfb65e592011-07-27 05:40:30 +000054 // ObjC strings can't be wide or UTF.
55 if (!S->isAscii()) {
Chris Lattnerd7670d92009-02-18 06:13:04 +000056 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
57 << S->getSourceRange();
58 return true;
59 }
Mike Stump11289f42009-09-09 15:08:12 +000060
Benjamin Kramer35b077e2010-08-17 12:54:38 +000061 // Append the string.
62 StrBuf += S->getString();
Mike Stump11289f42009-09-09 15:08:12 +000063
Chris Lattner163ffd22009-02-18 06:48:40 +000064 // Get the locations of the string tokens.
65 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000066 }
Mike Stump11289f42009-09-09 15:08:12 +000067
Chris Lattner163ffd22009-02-18 06:48:40 +000068 // Create the aggregate string with the appropriate content and location
69 // information.
Benjamin Kramercdac7612014-02-25 12:26:20 +000070 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
71 assert(CAT && "String literal not of constant array type!");
72 QualType StrTy = Context.getConstantArrayType(
73 CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1),
74 CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
75 S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
76 /*Pascal=*/false, StrTy, &StrLocs[0],
77 StrLocs.size());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000078 }
Ted Kremeneke65b0862012-03-06 20:05:56 +000079
80 return BuildObjCStringLiteral(AtLocs[0], S);
81}
Mike Stump11289f42009-09-09 15:08:12 +000082
Ted Kremeneke65b0862012-03-06 20:05:56 +000083ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
Chris Lattner6436fb62009-02-18 06:01:06 +000084 // Verify that this composite string is acceptable for ObjC strings.
85 if (CheckObjCString(S))
Chris Lattnera3fc41d2008-01-04 22:32:30 +000086 return true;
Chris Lattnerfffd6a72009-02-18 06:06:56 +000087
88 // Initialize the constant string interface lazily. This assumes
Steve Naroff54e59452009-04-07 14:18:33 +000089 // the NSString interface is seen in this translation unit. Note: We
90 // don't use NSConstantString, since the runtime team considers this
91 // interface private (even though it appears in the header files).
Chris Lattnerfffd6a72009-02-18 06:06:56 +000092 QualType Ty = Context.getObjCConstantStringInterface();
93 if (!Ty.isNull()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +000094 Ty = Context.getObjCObjectPointerType(Ty);
David Blaikiebbafb8a2012-03-11 07:00:24 +000095 } else if (getLangOpts().NoConstantCFStrings) {
Craig Topperc3ec1492014-05-26 06:22:03 +000096 IdentifierInfo *NSIdent=nullptr;
David Blaikiebbafb8a2012-03-11 07:00:24 +000097 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +000098
99 if (StringClass.empty())
100 NSIdent = &Context.Idents.get("NSConstantString");
101 else
102 NSIdent = &Context.Idents.get(StringClass);
103
Ted Kremeneke65b0862012-03-06 20:05:56 +0000104 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Fariborz Jahanian07317632010-04-23 23:19:04 +0000105 LookupOrdinaryName);
106 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
107 Context.setObjCConstantStringInterface(StrIF);
108 Ty = Context.getObjCConstantStringInterface();
109 Ty = Context.getObjCObjectPointerType(Ty);
110 } else {
111 // If there is no NSConstantString interface defined then treat this
112 // as error and recover from it.
113 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
114 << S->getSourceRange();
115 Ty = Context.getObjCIdType();
116 }
Chris Lattner091f6982008-06-21 21:44:18 +0000117 } else {
Patrick Beard0caa3942012-04-19 00:25:12 +0000118 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000119 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000120 LookupOrdinaryName);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000121 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
122 Context.setObjCConstantStringInterface(StrIF);
123 Ty = Context.getObjCConstantStringInterface();
Steve Naroff7cae42b2009-07-10 23:34:53 +0000124 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000125 } else {
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000126 // If there is no NSString interface defined, implicitly declare
127 // a @class NSString; and use that instead. This is to make sure
128 // type of an NSString literal is represented correctly, instead of
129 // being an 'id' type.
130 Ty = Context.getObjCNSStringType();
131 if (Ty.isNull()) {
132 ObjCInterfaceDecl *NSStringIDecl =
133 ObjCInterfaceDecl::Create (Context,
134 Context.getTranslationUnitDecl(),
135 SourceLocation(), NSIdent,
Craig Topperc3ec1492014-05-26 06:22:03 +0000136 nullptr, SourceLocation());
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000137 Ty = Context.getObjCInterfaceType(NSStringIDecl);
138 Context.setObjCNSStringType(Ty);
139 }
140 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000141 }
Chris Lattner091f6982008-06-21 21:44:18 +0000142 }
Mike Stump11289f42009-09-09 15:08:12 +0000143
Ted Kremeneke65b0862012-03-06 20:05:56 +0000144 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
145}
146
Jordy Rose08e500c2012-05-12 17:32:44 +0000147/// \brief Emits an error if the given method does not exist, or if the return
148/// type is not an Objective-C object.
149static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
150 const ObjCInterfaceDecl *Class,
151 Selector Sel, const ObjCMethodDecl *Method) {
152 if (!Method) {
153 // FIXME: Is there a better way to avoid quotes than using getName()?
154 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
155 return false;
156 }
157
158 // Make sure the return type is reasonable.
Alp Toker314cc812014-01-25 16:55:45 +0000159 QualType ReturnType = Method->getReturnType();
Jordy Rose08e500c2012-05-12 17:32:44 +0000160 if (!ReturnType->isObjCObjectPointerType()) {
161 S.Diag(Loc, diag::err_objc_literal_method_sig)
162 << Sel;
163 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
164 << ReturnType;
165 return false;
166 }
167
168 return true;
169}
170
Ted Kremeneke65b0862012-03-06 20:05:56 +0000171/// \brief Retrieve the NSNumber factory method that should be used to create
172/// an Objective-C literal for the given type.
173static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
Patrick Beard0caa3942012-04-19 00:25:12 +0000174 QualType NumberType,
175 bool isLiteral = false,
176 SourceRange R = SourceRange()) {
David Blaikie05785d12013-02-20 22:23:23 +0000177 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
178 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
179
Ted Kremeneke65b0862012-03-06 20:05:56 +0000180 if (!Kind) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000181 if (isLiteral) {
182 S.Diag(Loc, diag::err_invalid_nsnumber_type)
183 << NumberType << R;
184 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000185 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000186 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000187
Ted Kremeneke65b0862012-03-06 20:05:56 +0000188 // If we already looked up this method, we're done.
189 if (S.NSNumberLiteralMethods[*Kind])
190 return S.NSNumberLiteralMethods[*Kind];
191
192 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
193 /*Instance=*/false);
194
Patrick Beard0caa3942012-04-19 00:25:12 +0000195 ASTContext &CX = S.Context;
196
197 // Look up the NSNumber class, if we haven't done so already. It's cached
198 // in the Sema instance.
199 if (!S.NSNumberDecl) {
Jordy Roseaca01f92012-05-12 17:32:52 +0000200 IdentifierInfo *NSNumberId =
201 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber);
Patrick Beard0caa3942012-04-19 00:25:12 +0000202 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId,
203 Loc, Sema::LookupOrdinaryName);
204 S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
205 if (!S.NSNumberDecl) {
206 if (S.getLangOpts().DebuggerObjCLiteral) {
207 // Create a stub definition of NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000208 S.NSNumberDecl = ObjCInterfaceDecl::Create(CX,
209 CX.getTranslationUnitDecl(),
210 SourceLocation(), NSNumberId,
Craig Topperc3ec1492014-05-26 06:22:03 +0000211 nullptr, SourceLocation());
Patrick Beard0caa3942012-04-19 00:25:12 +0000212 } else {
213 // Otherwise, require a declaration of NSNumber.
214 S.Diag(Loc, diag::err_undeclared_nsnumber);
Craig Topperc3ec1492014-05-26 06:22:03 +0000215 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000216 }
217 } else if (!S.NSNumberDecl->hasDefinition()) {
218 S.Diag(Loc, diag::err_undeclared_nsnumber);
Craig Topperc3ec1492014-05-26 06:22:03 +0000219 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000220 }
221
222 // generate the pointer to NSNumber type.
Jordy Roseaca01f92012-05-12 17:32:52 +0000223 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
224 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000225 }
226
Ted Kremeneke65b0862012-03-06 20:05:56 +0000227 // Look for the appropriate method within NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000228 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000229 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000230 // create a stub definition this NSNumber factory method.
Craig Topperc3ec1492014-05-26 06:22:03 +0000231 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000232 Method =
233 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
234 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
235 /*isInstance=*/false, /*isVariadic=*/false,
236 /*isPropertyAccessor=*/false,
237 /*isImplicitlyDeclared=*/true,
238 /*isDefined=*/false, ObjCMethodDecl::Required,
239 /*HasRelatedResultType=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000240 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
241 SourceLocation(), SourceLocation(),
Patrick Beard0caa3942012-04-19 00:25:12 +0000242 &CX.Idents.get("value"),
Craig Topperc3ec1492014-05-26 06:22:03 +0000243 NumberType, /*TInfo=*/nullptr,
244 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000245 Method->setMethodParams(S.Context, value, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000246 }
247
Jordy Rose08e500c2012-05-12 17:32:44 +0000248 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
Craig Topperc3ec1492014-05-26 06:22:03 +0000249 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000250
251 // Note: if the parameter type is out-of-line, we'll catch it later in the
252 // implicit conversion.
253
254 S.NSNumberLiteralMethods[*Kind] = Method;
255 return Method;
256}
257
Patrick Beard0caa3942012-04-19 00:25:12 +0000258/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
259/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremeneke65b0862012-03-06 20:05:56 +0000260ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000261 // Determine the type of the literal.
262 QualType NumberType = Number->getType();
263 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
264 // In C, character literals have type 'int'. That's not the type we want
265 // to use to determine the Objective-c literal kind.
266 switch (Char->getKind()) {
267 case CharacterLiteral::Ascii:
268 NumberType = Context.CharTy;
269 break;
270
271 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000272 NumberType = Context.getWideCharType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000273 break;
274
275 case CharacterLiteral::UTF16:
276 NumberType = Context.Char16Ty;
277 break;
278
279 case CharacterLiteral::UTF32:
280 NumberType = Context.Char32Ty;
281 break;
282 }
283 }
284
Ted Kremeneke65b0862012-03-06 20:05:56 +0000285 // Look for the appropriate method within NSNumber.
286 // Construct the literal.
Patrick Beard2565c592012-05-01 21:47:19 +0000287 SourceRange NR(Number->getSourceRange());
Patrick Beard0caa3942012-04-19 00:25:12 +0000288 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
Patrick Beard2565c592012-05-01 21:47:19 +0000289 true, NR);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000290 if (!Method)
291 return ExprError();
292
293 // Convert the number to the type that the parameter expects.
Alp Toker03376dc2014-07-07 09:02:20 +0000294 ParmVarDecl *ParamDecl = Method->parameters()[0];
Patrick Beard2565c592012-05-01 21:47:19 +0000295 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
296 ParamDecl);
297 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
298 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000299 Number);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000300 if (ConvertedNumber.isInvalid())
301 return ExprError();
302 Number = ConvertedNumber.get();
303
Patrick Beard2565c592012-05-01 21:47:19 +0000304 // Use the effective source range of the literal, including the leading '@'.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000305 return MaybeBindToTemporary(
Patrick Beard2565c592012-05-01 21:47:19 +0000306 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
307 SourceRange(AtLoc, NR.getEnd())));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000308}
309
310ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
311 SourceLocation ValueLoc,
312 bool Value) {
313 ExprResult Inner;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000314 if (getLangOpts().CPlusPlus) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000315 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
316 } else {
317 // C doesn't actually have a way to represent literal values of type
318 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
319 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
320 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
321 CK_IntegralToBoolean);
322 }
323
324 return BuildObjCNumericLiteral(AtLoc, Inner.get());
325}
326
327/// \brief Check that the given expression is a valid element of an Objective-C
328/// collection literal.
329static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000330 QualType T,
331 bool ArrayLiteral = false) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000332 // If the expression is type-dependent, there's nothing for us to do.
333 if (Element->isTypeDependent())
334 return Element;
335
336 ExprResult Result = S.CheckPlaceholderExpr(Element);
337 if (Result.isInvalid())
338 return ExprError();
339 Element = Result.get();
340
341 // In C++, check for an implicit conversion to an Objective-C object pointer
342 // type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000343 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000344 InitializedEntity Entity
Jordy Roseaca01f92012-05-12 17:32:52 +0000345 = InitializedEntity::InitializeParameter(S.Context, T,
346 /*Consumed=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000347 InitializationKind Kind
Jordy Roseaca01f92012-05-12 17:32:52 +0000348 = InitializationKind::CreateCopy(Element->getLocStart(),
349 SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000350 InitializationSequence Seq(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000351 if (!Seq.Failed())
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000352 return Seq.Perform(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000353 }
354
355 Expr *OrigElement = Element;
356
357 // Perform lvalue-to-rvalue conversion.
358 Result = S.DefaultLvalueConversion(Element);
359 if (Result.isInvalid())
360 return ExprError();
361 Element = Result.get();
362
363 // Make sure that we have an Objective-C pointer type or block.
364 if (!Element->getType()->isObjCObjectPointerType() &&
365 !Element->getType()->isBlockPointerType()) {
366 bool Recovered = false;
367
368 // If this is potentially an Objective-C numeric literal, add the '@'.
369 if (isa<IntegerLiteral>(OrigElement) ||
370 isa<CharacterLiteral>(OrigElement) ||
371 isa<FloatingLiteral>(OrigElement) ||
372 isa<ObjCBoolLiteralExpr>(OrigElement) ||
373 isa<CXXBoolLiteralExpr>(OrigElement)) {
374 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
375 int Which = isa<CharacterLiteral>(OrigElement) ? 1
376 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
377 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
378 : 3;
379
380 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
381 << Which << OrigElement->getSourceRange()
382 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
383
384 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
385 OrigElement);
386 if (Result.isInvalid())
387 return ExprError();
388
389 Element = Result.get();
390 Recovered = true;
391 }
392 }
393 // If this is potentially an Objective-C string literal, add the '@'.
394 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
395 if (String->isAscii()) {
396 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
397 << 0 << OrigElement->getSourceRange()
398 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
399
400 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
401 if (Result.isInvalid())
402 return ExprError();
403
404 Element = Result.get();
405 Recovered = true;
406 }
407 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000408
Ted Kremeneke65b0862012-03-06 20:05:56 +0000409 if (!Recovered) {
410 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
411 << Element->getType();
412 return ExprError();
413 }
414 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000415 if (ArrayLiteral)
Ted Kremenek197fee42013-10-09 22:34:33 +0000416 if (ObjCStringLiteral *getString =
417 dyn_cast<ObjCStringLiteral>(OrigElement)) {
418 if (StringLiteral *SL = getString->getString()) {
419 unsigned numConcat = SL->getNumConcatenated();
420 if (numConcat > 1) {
421 // Only warn if the concatenated string doesn't come from a macro.
422 bool hasMacro = false;
423 for (unsigned i = 0; i < numConcat ; ++i)
424 if (SL->getStrTokenLoc(i).isMacroID()) {
425 hasMacro = true;
426 break;
427 }
428 if (!hasMacro)
429 S.Diag(Element->getLocStart(),
430 diag::warn_concatenated_nsarray_literal)
431 << Element->getType();
432 }
433 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000434 }
435
Ted Kremeneke65b0862012-03-06 20:05:56 +0000436 // Make sure that the element has the type that the container factory
437 // function expects.
438 return S.PerformCopyInitialization(
439 InitializedEntity::InitializeParameter(S.Context, T,
440 /*Consumed=*/false),
441 Element->getLocStart(), Element);
442}
443
Patrick Beard0caa3942012-04-19 00:25:12 +0000444ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
445 if (ValueExpr->isTypeDependent()) {
446 ObjCBoxedExpr *BoxedExpr =
Craig Topperc3ec1492014-05-26 06:22:03 +0000447 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000448 return BoxedExpr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000449 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000450 ObjCMethodDecl *BoxingMethod = nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000451 QualType BoxedType;
452 // Convert the expression to an RValue, so we can check for pointer types...
453 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
454 if (RValue.isInvalid()) {
455 return ExprError();
456 }
457 ValueExpr = RValue.get();
Patrick Beard2565c592012-05-01 21:47:19 +0000458 QualType ValueType(ValueExpr->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +0000459 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
460 QualType PointeeType = PT->getPointeeType();
461 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
462
463 if (!NSStringDecl) {
464 IdentifierInfo *NSStringId =
465 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
466 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
467 SR.getBegin(), LookupOrdinaryName);
468 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
469 if (!NSStringDecl) {
470 if (getLangOpts().DebuggerObjCLiteral) {
471 // Support boxed expressions in the debugger w/o NSString declaration.
Jordy Roseaca01f92012-05-12 17:32:52 +0000472 DeclContext *TU = Context.getTranslationUnitDecl();
473 NSStringDecl = ObjCInterfaceDecl::Create(Context, TU,
474 SourceLocation(),
475 NSStringId,
Craig Topperc3ec1492014-05-26 06:22:03 +0000476 nullptr, SourceLocation());
Patrick Beard0caa3942012-04-19 00:25:12 +0000477 } else {
478 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
479 return ExprError();
480 }
481 } else if (!NSStringDecl->hasDefinition()) {
482 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
483 return ExprError();
484 }
485 assert(NSStringDecl && "NSStringDecl should not be NULL");
Jordy Roseaca01f92012-05-12 17:32:52 +0000486 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
487 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000488 }
489
490 if (!StringWithUTF8StringMethod) {
491 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
492 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
493
494 // Look for the appropriate method within NSString.
Jordy Rose08e500c2012-05-12 17:32:44 +0000495 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
496 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000497 // Debugger needs to work even if NSString hasn't been defined.
Craig Topperc3ec1492014-05-26 06:22:03 +0000498 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000499 ObjCMethodDecl *M = ObjCMethodDecl::Create(
500 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
501 NSStringPointer, ReturnTInfo, NSStringDecl,
502 /*isInstance=*/false, /*isVariadic=*/false,
503 /*isPropertyAccessor=*/false,
504 /*isImplicitlyDeclared=*/true,
505 /*isDefined=*/false, ObjCMethodDecl::Required,
506 /*HasRelatedResultType=*/false);
Jordy Roseaca01f92012-05-12 17:32:52 +0000507 QualType ConstCharType = Context.CharTy.withConst();
Patrick Beard0caa3942012-04-19 00:25:12 +0000508 ParmVarDecl *value =
509 ParmVarDecl::Create(Context, M,
510 SourceLocation(), SourceLocation(),
511 &Context.Idents.get("value"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000512 Context.getPointerType(ConstCharType),
Craig Topperc3ec1492014-05-26 06:22:03 +0000513 /*TInfo=*/nullptr,
514 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000515 M->setMethodParams(Context, value, None);
Jordy Rose08e500c2012-05-12 17:32:44 +0000516 BoxingMethod = M;
Patrick Beard0caa3942012-04-19 00:25:12 +0000517 }
Jordy Rose890f4572012-05-12 15:53:41 +0000518
Jordy Rose08e500c2012-05-12 17:32:44 +0000519 if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
520 stringWithUTF8String, BoxingMethod))
521 return ExprError();
522
523 StringWithUTF8StringMethod = BoxingMethod;
Patrick Beard0caa3942012-04-19 00:25:12 +0000524 }
525
526 BoxingMethod = StringWithUTF8StringMethod;
527 BoxedType = NSStringPointer;
528 }
Patrick Beard2565c592012-05-01 21:47:19 +0000529 } else if (ValueType->isBuiltinType()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000530 // The other types we support are numeric, char and BOOL/bool. We could also
531 // provide limited support for structure types, such as NSRange, NSRect, and
532 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
533 // for more details.
534
535 // Check for a top-level character literal.
536 if (const CharacterLiteral *Char =
537 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
538 // In C, character literals have type 'int'. That's not the type we want
539 // to use to determine the Objective-c literal kind.
540 switch (Char->getKind()) {
541 case CharacterLiteral::Ascii:
542 ValueType = Context.CharTy;
543 break;
544
545 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000546 ValueType = Context.getWideCharType();
Patrick Beard0caa3942012-04-19 00:25:12 +0000547 break;
548
549 case CharacterLiteral::UTF16:
550 ValueType = Context.Char16Ty;
551 break;
552
553 case CharacterLiteral::UTF32:
554 ValueType = Context.Char32Ty;
555 break;
556 }
557 }
Fariborz Jahanian5d64abb2014-06-18 20:49:02 +0000558 CheckForIntOverflow(ValueExpr);
Patrick Beard0caa3942012-04-19 00:25:12 +0000559 // FIXME: Do I need to do anything special with BoolTy expressions?
560
561 // Look for the appropriate method within NSNumber.
562 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
563 BoxedType = NSNumberPointer;
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000564
565 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
566 if (!ET->getDecl()->isComplete()) {
567 Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type)
568 << ValueType << ValueExpr->getSourceRange();
569 return ExprError();
570 }
571
572 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(),
573 ET->getDecl()->getIntegerType());
574 BoxedType = NSNumberPointer;
Patrick Beard0caa3942012-04-19 00:25:12 +0000575 }
576
577 if (!BoxingMethod) {
578 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
579 << ValueType << ValueExpr->getSourceRange();
580 return ExprError();
581 }
582
583 // Convert the expression to the type that the parameter requires.
Alp Toker03376dc2014-07-07 09:02:20 +0000584 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
Patrick Beard2565c592012-05-01 21:47:19 +0000585 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
586 ParamDecl);
587 ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
588 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000589 ValueExpr);
Patrick Beard0caa3942012-04-19 00:25:12 +0000590 if (ConvertedValueExpr.isInvalid())
591 return ExprError();
592 ValueExpr = ConvertedValueExpr.get();
593
594 ObjCBoxedExpr *BoxedExpr =
595 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
596 BoxingMethod, SR);
597 return MaybeBindToTemporary(BoxedExpr);
598}
599
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000600static ObjCMethodDecl *FindAllocMethod(Sema &S, ObjCInterfaceDecl *NSClass) {
601 ObjCMethodDecl *Method = nullptr;
602 ASTContext &Context = S.Context;
603
604 // Find +[NSClass alloc] method.
605 IdentifierInfo *II = &Context.Idents.get("alloc");
606 Selector AllocSel = Context.Selectors.getSelector(0, &II);
607 Method = NSClass->lookupClassMethod(AllocSel);
608 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
609 Method = ObjCMethodDecl::Create(Context,
610 SourceLocation(), SourceLocation(), AllocSel,
611 Context.getObjCIdType(),
612 nullptr /*TypeSourceInfo */,
613 Context.getTranslationUnitDecl(),
614 false /*Instance*/, false/*isVariadic*/,
615 /*isPropertyAccessor=*/false,
616 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
617 ObjCMethodDecl::Required,
618 false);
619 SmallVector<ParmVarDecl *, 1> Params;
620 Method->setMethodParams(Context, Params, None);
621 }
622 return Method;
623}
624
John McCallf2538342012-07-31 05:14:30 +0000625/// Build an ObjC subscript pseudo-object expression, given that
626/// that's supported by the runtime.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000627ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
628 Expr *IndexExpr,
629 ObjCMethodDecl *getterMethod,
630 ObjCMethodDecl *setterMethod) {
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +0000631 assert(!LangOpts.isSubscriptPointerArithmetic());
John McCall5fb5df92012-06-20 06:18:46 +0000632
John McCallf2538342012-07-31 05:14:30 +0000633 // We can't get dependent types here; our callers should have
634 // filtered them out.
635 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
636 "base or index cannot have dependent type here");
637
638 // Filter out placeholders in the index. In theory, overloads could
639 // be preserved here, although that might not actually work correctly.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000640 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
641 if (Result.isInvalid())
642 return ExprError();
643 IndexExpr = Result.get();
644
John McCallf2538342012-07-31 05:14:30 +0000645 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000646 Result = DefaultLvalueConversion(BaseExpr);
647 if (Result.isInvalid())
648 return ExprError();
649 BaseExpr = Result.get();
John McCallf2538342012-07-31 05:14:30 +0000650
651 // Build the pseudo-object expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000652 return ObjCSubscriptRefExpr::Create(Context, BaseExpr, IndexExpr,
653 Context.PseudoObjectTy, getterMethod,
654 setterMethod, RB);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000655}
656
657ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000658 bool Arc = getLangOpts().ObjCAutoRefCount;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000659 // Look up the NSArray class, if we haven't done so already.
660 if (!NSArrayDecl) {
661 NamedDecl *IF = LookupSingleName(TUScope,
662 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
663 SR.getBegin(),
664 LookupOrdinaryName);
665 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000666 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000667 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
668 Context.getTranslationUnitDecl(),
669 SourceLocation(),
670 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
Craig Topperc3ec1492014-05-26 06:22:03 +0000671 nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000672
673 if (!NSArrayDecl) {
674 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
675 return ExprError();
676 }
677 }
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000678 if (Arc && !ArrayAllocObjectsMethod) {
679 // Find +[NSArray alloc] method.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000680 ArrayAllocObjectsMethod = FindAllocMethod(*this, NSArrayDecl);
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000681 if (!ArrayAllocObjectsMethod) {
682 Diag(SR.getBegin(), diag::err_undeclared_alloc);
683 return ExprError();
684 }
685 }
686 // Find the arrayWithObjects:count: method, if we haven't done so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000687 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000688 if (!ArrayWithObjectsMethod) {
689 Selector
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000690 Sel = NSAPIObj->getNSArraySelector(
691 Arc? NSAPI::NSArr_initWithObjectsCount : NSAPI::NSArr_arrayWithObjectsCount);
692 ObjCMethodDecl *Method =
693 Arc? NSArrayDecl->lookupInstanceMethod(Sel)
694 : NSArrayDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000695 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000696 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000697 Method = ObjCMethodDecl::Create(
698 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000699 Context.getTranslationUnitDecl(),
700 Arc /*Instance for Arc, Class for MRR*/,
Alp Toker314cc812014-01-25 16:55:45 +0000701 false /*isVariadic*/,
702 /*isPropertyAccessor=*/false,
703 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
704 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000705 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000706 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000707 SourceLocation(),
708 SourceLocation(),
709 &Context.Idents.get("objects"),
710 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000711 /*TInfo=*/nullptr,
712 SC_None, nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000713 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000714 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000715 SourceLocation(),
716 SourceLocation(),
717 &Context.Idents.get("cnt"),
718 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000719 /*TInfo=*/nullptr, SC_None,
720 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000721 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000722 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000723 }
724
Jordy Rose08e500c2012-05-12 17:32:44 +0000725 if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000726 return ExprError();
Jordy Rose08e500c2012-05-12 17:32:44 +0000727
Jordy Rose4af44872012-05-12 17:32:56 +0000728 // Dig out the type that all elements should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000729 QualType T = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000730 const PointerType *PtrT = T->getAs<PointerType>();
731 if (!PtrT ||
732 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
733 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
734 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000735 Diag(Method->parameters()[0]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000736 diag::note_objc_literal_method_param)
737 << 0 << T
738 << Context.getPointerType(IdT.withConst());
739 return ExprError();
740 }
741
742 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000743 if (!Method->parameters()[1]->getType()->isIntegerType()) {
Jordy Rose4af44872012-05-12 17:32:56 +0000744 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
745 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000746 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000747 diag::note_objc_literal_method_param)
748 << 1
Alp Toker03376dc2014-07-07 09:02:20 +0000749 << Method->parameters()[1]->getType()
Jordy Rose4af44872012-05-12 17:32:56 +0000750 << "integral";
751 return ExprError();
752 }
753
754 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rose08e500c2012-05-12 17:32:44 +0000755 ArrayWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000756 }
757
Alp Toker03376dc2014-07-07 09:02:20 +0000758 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000759 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000760
761 // Check that each of the elements provided is valid in a collection literal,
762 // performing conversions as necessary.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000763 Expr **ElementsBuffer = Elements.data();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000764 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
765 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
766 ElementsBuffer[I],
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000767 RequiredType, true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000768 if (Converted.isInvalid())
769 return ExprError();
770
771 ElementsBuffer[I] = Converted.get();
772 }
773
774 QualType Ty
775 = Context.getObjCObjectPointerType(
776 Context.getObjCInterfaceType(NSArrayDecl));
777
778 return MaybeBindToTemporary(
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000779 ObjCArrayLiteral::Create(Context, Elements, Ty,
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000780 ArrayWithObjectsMethod,
781 ArrayAllocObjectsMethod, SR));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000782}
783
784ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
785 ObjCDictionaryElement *Elements,
786 unsigned NumElements) {
Fariborz Jahanian2a25dba2014-08-06 23:40:31 +0000787 bool Arc = getLangOpts().ObjCAutoRefCount;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000788 // Look up the NSDictionary class, if we haven't done so already.
789 if (!NSDictionaryDecl) {
790 NamedDecl *IF = LookupSingleName(TUScope,
791 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
792 SR.getBegin(), LookupOrdinaryName);
793 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000794 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000795 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
796 Context.getTranslationUnitDecl(),
797 SourceLocation(),
798 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
Craig Topperc3ec1492014-05-26 06:22:03 +0000799 nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000800
801 if (!NSDictionaryDecl) {
802 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
803 return ExprError();
804 }
805 }
806
Fariborz Jahanian2a25dba2014-08-06 23:40:31 +0000807 if (Arc && !DictAllocObjectsMethod) {
808 // Find +[NSDictionary alloc] method.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000809 DictAllocObjectsMethod = FindAllocMethod(*this, NSDictionaryDecl);
Fariborz Jahanian2a25dba2014-08-06 23:40:31 +0000810 if (!DictAllocObjectsMethod) {
811 Diag(SR.getBegin(), diag::err_undeclared_alloc);
812 return ExprError();
813 }
814 }
815
Fariborz Jahaniand45e7ce2014-08-07 20:57:35 +0000816 // Find the dictionaryWithObjects:forKeys:count: or initWithObjects:forKeys:count:
817 // (for arc) method, if we haven't done so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000818 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000819 if (!DictionaryWithObjectsMethod) {
Fariborz Jahaniand45e7ce2014-08-07 20:57:35 +0000820 Selector Sel =
821 NSAPIObj->getNSDictionarySelector(Arc? NSAPI::NSDict_initWithObjectsForKeysCount
822 : NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
823 ObjCMethodDecl *Method =
824 Arc ? NSDictionaryDecl->lookupInstanceMethod(Sel)
825 : NSDictionaryDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000826 if (!Method && getLangOpts().DebuggerObjCLiteral) {
827 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000828 SourceLocation(), SourceLocation(), Sel,
829 IdT,
Craig Topperc3ec1492014-05-26 06:22:03 +0000830 nullptr /*TypeSourceInfo */,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000831 Context.getTranslationUnitDecl(),
Fariborz Jahaniand45e7ce2014-08-07 20:57:35 +0000832 Arc /*Instance for Arc, Class for MRR*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000833 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000834 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
835 ObjCMethodDecl::Required,
836 false);
837 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000838 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000839 SourceLocation(),
840 SourceLocation(),
841 &Context.Idents.get("objects"),
842 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000843 /*TInfo=*/nullptr, SC_None,
844 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000845 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000846 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000847 SourceLocation(),
848 SourceLocation(),
849 &Context.Idents.get("keys"),
850 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000851 /*TInfo=*/nullptr, SC_None,
852 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000853 Params.push_back(keys);
Jordy Rose08e500c2012-05-12 17:32:44 +0000854 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000855 SourceLocation(),
856 SourceLocation(),
857 &Context.Idents.get("cnt"),
858 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000859 /*TInfo=*/nullptr, SC_None,
860 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000861 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000862 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000863 }
864
Jordy Rose08e500c2012-05-12 17:32:44 +0000865 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
866 Method))
867 return ExprError();
868
Jordy Rose4af44872012-05-12 17:32:56 +0000869 // Dig out the type that all values should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000870 QualType ValueT = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000871 const PointerType *PtrValue = ValueT->getAs<PointerType>();
872 if (!PtrValue ||
873 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000874 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000875 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000876 Diag(Method->parameters()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000877 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000878 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000879 << Context.getPointerType(IdT.withConst());
880 return ExprError();
881 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000882
Jordy Rose4af44872012-05-12 17:32:56 +0000883 // Dig out the type that all keys should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000884 QualType KeyT = Method->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000885 const PointerType *PtrKey = KeyT->getAs<PointerType>();
886 if (!PtrKey ||
887 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
888 IdT)) {
889 bool err = true;
890 if (PtrKey) {
891 if (QIDNSCopying.isNull()) {
892 // key argument of selector is id<NSCopying>?
893 if (ObjCProtocolDecl *NSCopyingPDecl =
894 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
895 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
896 QIDNSCopying =
897 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
898 (ObjCProtocolDecl**) PQ,1);
899 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
900 }
901 }
902 if (!QIDNSCopying.isNull())
903 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
904 QIDNSCopying);
905 }
906
907 if (err) {
908 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
909 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000910 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000911 diag::note_objc_literal_method_param)
912 << 1 << KeyT
913 << Context.getPointerType(IdT.withConst());
914 return ExprError();
915 }
916 }
917
918 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000919 QualType CountType = Method->parameters()[2]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000920 if (!CountType->isIntegerType()) {
921 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
922 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000923 Diag(Method->parameters()[2]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000924 diag::note_objc_literal_method_param)
925 << 2 << CountType
926 << "integral";
927 return ExprError();
928 }
929
930 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
931 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000932 }
933
Alp Toker03376dc2014-07-07 09:02:20 +0000934 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000935 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
Alp Toker03376dc2014-07-07 09:02:20 +0000936 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000937 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
938
Ted Kremeneke65b0862012-03-06 20:05:56 +0000939 // Check that each of the keys and values provided is valid in a collection
940 // literal, performing conversions as necessary.
941 bool HasPackExpansions = false;
942 for (unsigned I = 0, N = NumElements; I != N; ++I) {
943 // Check the key.
944 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
945 KeyT);
946 if (Key.isInvalid())
947 return ExprError();
948
949 // Check the value.
950 ExprResult Value
951 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
952 if (Value.isInvalid())
953 return ExprError();
954
955 Elements[I].Key = Key.get();
956 Elements[I].Value = Value.get();
957
958 if (Elements[I].EllipsisLoc.isInvalid())
959 continue;
960
961 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
962 !Elements[I].Value->containsUnexpandedParameterPack()) {
963 Diag(Elements[I].EllipsisLoc,
964 diag::err_pack_expansion_without_parameter_packs)
965 << SourceRange(Elements[I].Key->getLocStart(),
966 Elements[I].Value->getLocEnd());
967 return ExprError();
968 }
969
970 HasPackExpansions = true;
971 }
972
973
974 QualType Ty
975 = Context.getObjCObjectPointerType(
Robert Wilhelm88e02492013-08-19 07:57:02 +0000976 Context.getObjCInterfaceType(NSDictionaryDecl));
977 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
978 Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty,
Fariborz Jahanian2a25dba2014-08-06 23:40:31 +0000979 DictionaryWithObjectsMethod, DictAllocObjectsMethod, SR));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000980}
981
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000982ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregorabd9e962010-04-20 15:39:42 +0000983 TypeSourceInfo *EncodedTypeInfo,
Anders Carlsson315d2292009-06-07 18:45:35 +0000984 SourceLocation RParenLoc) {
Douglas Gregorabd9e962010-04-20 15:39:42 +0000985 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlsson315d2292009-06-07 18:45:35 +0000986 QualType StrTy;
Mike Stump11289f42009-09-09 15:08:12 +0000987 if (EncodedType->isDependentType())
Anders Carlsson315d2292009-06-07 18:45:35 +0000988 StrTy = Context.DependentTy;
989 else {
Fariborz Jahaniand9bc6c32011-06-16 22:34:44 +0000990 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
991 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000992 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000993 diag::err_incomplete_type_objc_at_encode,
994 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000995 return ExprError();
996
Anders Carlsson315d2292009-06-07 18:45:35 +0000997 std::string Str;
998 Context.getObjCEncodingForType(EncodedType, Str);
999
1000 // The type of @encode is the same as the type of the corresponding string,
1001 // which is an array type.
1002 StrTy = Context.CharTy;
1003 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001004 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlsson315d2292009-06-07 18:45:35 +00001005 StrTy.addConst();
1006 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
1007 ArrayType::Normal, 0);
1008 }
Mike Stump11289f42009-09-09 15:08:12 +00001009
Douglas Gregorabd9e962010-04-20 15:39:42 +00001010 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlsson315d2292009-06-07 18:45:35 +00001011}
1012
John McCallfaf5fb42010-08-26 23:41:50 +00001013ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1014 SourceLocation EncodeLoc,
1015 SourceLocation LParenLoc,
1016 ParsedType ty,
1017 SourceLocation RParenLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001018 // FIXME: Preserve type source info ?
Douglas Gregorabd9e962010-04-20 15:39:42 +00001019 TypeSourceInfo *TInfo;
1020 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1021 if (!TInfo)
1022 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
1023 PP.getLocForEndOfToken(LParenLoc));
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001024
Douglas Gregorabd9e962010-04-20 15:39:42 +00001025 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001026}
1027
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001028static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1029 SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001030 SourceLocation LParenLoc,
1031 SourceLocation RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001032 ObjCMethodDecl *Method,
1033 ObjCMethodList &MethList) {
1034 ObjCMethodList *M = &MethList;
1035 bool Warned = false;
1036 for (M = M->getNext(); M; M=M->getNext()) {
1037 ObjCMethodDecl *MatchingMethodDecl = M->Method;
1038 if (MatchingMethodDecl == Method ||
1039 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1040 MatchingMethodDecl->getSelector() != Method->getSelector())
1041 continue;
1042 if (!S.MatchTwoMethodDeclarations(Method,
1043 MatchingMethodDecl, Sema::MMS_loose)) {
1044 if (!Warned) {
1045 Warned = true;
1046 S.Diag(AtLoc, diag::warning_multiple_selectors)
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001047 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1048 << FixItHint::CreateInsertion(RParenLoc, ")");
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001049 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1050 << Method->getDeclName();
1051 }
1052 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1053 << MatchingMethodDecl->getDeclName();
1054 }
1055 }
1056 return Warned;
1057}
1058
1059static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001060 ObjCMethodDecl *Method,
1061 SourceLocation LParenLoc,
1062 SourceLocation RParenLoc,
1063 bool WarnMultipleSelectors) {
1064 if (!WarnMultipleSelectors ||
1065 S.Diags.isIgnored(diag::warning_multiple_selectors, SourceLocation()))
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001066 return;
1067 bool Warned = false;
1068 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1069 e = S.MethodPool.end(); b != e; b++) {
1070 // first, instance methods
1071 ObjCMethodList &InstMethList = b->second.first;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001072 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001073 Method, InstMethList))
1074 Warned = true;
1075
1076 // second, class methods
1077 ObjCMethodList &ClsMethList = b->second.second;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001078 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1079 Method, ClsMethList) || Warned)
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001080 return;
1081 }
1082}
1083
John McCallfaf5fb42010-08-26 23:41:50 +00001084ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1085 SourceLocation AtLoc,
1086 SourceLocation SelLoc,
1087 SourceLocation LParenLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001088 SourceLocation RParenLoc,
1089 bool WarnMultipleSelectors) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001090 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1091 SourceRange(LParenLoc, RParenLoc), false, false);
1092 if (!Method)
1093 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian0571d9b2009-06-16 16:25:00 +00001094 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00001095 if (!Method) {
1096 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1097 Selector MatchedSel = OM->getSelector();
1098 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1099 RParenLoc.getLocWithOffset(-1));
1100 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1101 << Sel << MatchedSel
1102 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1103
1104 } else
1105 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001106 } else
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001107 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1108 WarnMultipleSelectors);
Fariborz Jahanian9a881012011-07-13 19:05:43 +00001109
Fariborz Jahanian65a78b52014-05-09 19:51:39 +00001110 if (Method &&
1111 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
1112 !getSourceManager().isInSystemHeader(Method->getLocation())) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001113 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
1114 = ReferencedSelectors.find(Sel);
1115 if (Pos == ReferencedSelectors.end())
1116 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian9a881012011-07-13 19:05:43 +00001117 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001118
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001119 // In ARC, forbid the user from using @selector for
John McCall31168b02011-06-15 23:02:42 +00001120 // retain/release/autorelease/dealloc/retainCount.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001121 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001122 switch (Sel.getMethodFamily()) {
1123 case OMF_retain:
1124 case OMF_release:
1125 case OMF_autorelease:
1126 case OMF_retainCount:
1127 case OMF_dealloc:
1128 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1129 Sel << SourceRange(LParenLoc, RParenLoc);
1130 break;
1131
1132 case OMF_None:
1133 case OMF_alloc:
1134 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00001135 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00001136 case OMF_init:
1137 case OMF_mutableCopy:
1138 case OMF_new:
1139 case OMF_self:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001140 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001141 break;
1142 }
1143 }
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001144 QualType Ty = Context.getObjCSelType();
Daniel Dunbar45858d22010-02-03 20:11:42 +00001145 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001146}
1147
John McCallfaf5fb42010-08-26 23:41:50 +00001148ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1149 SourceLocation AtLoc,
1150 SourceLocation ProtoLoc,
1151 SourceLocation LParenLoc,
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001152 SourceLocation ProtoIdLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00001153 SourceLocation RParenLoc) {
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001154 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001155 if (!PDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001156 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001157 return true;
1158 }
Fariborz Jahaniana57d91c22014-07-25 19:45:01 +00001159 if (PDecl->hasDefinition())
1160 PDecl = PDecl->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00001161
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001162 QualType Ty = Context.getObjCProtoType();
1163 if (Ty.isNull())
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001164 return true;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001165 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001166 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001167}
1168
John McCall5f2d5562011-02-03 09:00:02 +00001169/// Try to capture an implicit reference to 'self'.
Eli Friedman24af8502012-02-03 22:47:37 +00001170ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1171 DeclContext *DC = getFunctionLevelDeclContext();
John McCall5f2d5562011-02-03 09:00:02 +00001172
1173 // If we're not in an ObjC method, error out. Note that, unlike the
1174 // C++ case, we don't require an instance method --- class methods
1175 // still have a 'self', and we really do still need to capture it!
1176 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1177 if (!method)
Craig Topperc3ec1492014-05-26 06:22:03 +00001178 return nullptr;
John McCall5f2d5562011-02-03 09:00:02 +00001179
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001180 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall5f2d5562011-02-03 09:00:02 +00001181
1182 return method;
1183}
1184
Douglas Gregor64910ca2011-09-09 20:05:21 +00001185static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1186 if (T == Context.getObjCInstanceType())
1187 return Context.getObjCIdType();
1188
1189 return T;
1190}
1191
Douglas Gregor33823722011-06-11 01:09:30 +00001192QualType Sema::getMessageSendResultType(QualType ReceiverType,
1193 ObjCMethodDecl *Method,
1194 bool isClassMessage, bool isSuperMessage) {
1195 assert(Method && "Must have a method");
1196 if (!Method->hasRelatedResultType())
1197 return Method->getSendResultType();
1198
1199 // If a method has a related return type:
1200 // - if the method found is an instance method, but the message send
1201 // was a class message send, T is the declared return type of the method
1202 // found
1203 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor64910ca2011-09-09 20:05:21 +00001204 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001205
1206 // - if the receiver is super, T is a pointer to the class of the
1207 // enclosing method definition
1208 if (isSuperMessage) {
1209 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1210 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1211 return Context.getObjCObjectPointerType(
1212 Context.getObjCInterfaceType(Class));
1213 }
1214
1215 // - if the receiver is the name of a class U, T is a pointer to U
1216 if (ReceiverType->getAs<ObjCInterfaceType>() ||
1217 ReceiverType->isObjCQualifiedInterfaceType())
1218 return Context.getObjCObjectPointerType(ReceiverType);
1219 // - if the receiver is of type Class or qualified Class type,
1220 // T is the declared return type of the method.
1221 if (ReceiverType->isObjCClassType() ||
1222 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor64910ca2011-09-09 20:05:21 +00001223 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001224
1225 // - if the receiver is id, qualified id, Class, or qualified Class, T
1226 // is the receiver type, otherwise
1227 // - T is the type of the receiver expression.
1228 return ReceiverType;
1229}
John McCall5f2d5562011-02-03 09:00:02 +00001230
John McCall5ec7e7d2013-03-19 07:04:25 +00001231/// Look for an ObjC method whose result type exactly matches the given type.
1232static const ObjCMethodDecl *
1233findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1234 QualType instancetype) {
Alp Toker314cc812014-01-25 16:55:45 +00001235 if (MD->getReturnType() == instancetype)
1236 return MD;
John McCall5ec7e7d2013-03-19 07:04:25 +00001237
1238 // For these purposes, a method in an @implementation overrides a
1239 // declaration in the @interface.
1240 if (const ObjCImplDecl *impl =
1241 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1242 const ObjCContainerDecl *iface;
1243 if (const ObjCCategoryImplDecl *catImpl =
1244 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1245 iface = catImpl->getCategoryDecl();
1246 } else {
1247 iface = impl->getClassInterface();
1248 }
1249
1250 const ObjCMethodDecl *ifaceMD =
1251 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1252 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1253 }
1254
1255 SmallVector<const ObjCMethodDecl *, 4> overrides;
1256 MD->getOverriddenMethods(overrides);
1257 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1258 if (const ObjCMethodDecl *result =
1259 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1260 return result;
1261 }
1262
Craig Topperc3ec1492014-05-26 06:22:03 +00001263 return nullptr;
John McCall5ec7e7d2013-03-19 07:04:25 +00001264}
1265
1266void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1267 // Only complain if we're in an ObjC method and the required return
1268 // type doesn't match the method's declared return type.
1269 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1270 if (!MD || !MD->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +00001271 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
John McCall5ec7e7d2013-03-19 07:04:25 +00001272 return;
1273
1274 // Look for a method overridden by this method which explicitly uses
1275 // 'instancetype'.
1276 if (const ObjCMethodDecl *overridden =
1277 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +00001278 SourceRange range = overridden->getReturnTypeSourceRange();
1279 SourceLocation loc = range.getBegin();
John McCall5ec7e7d2013-03-19 07:04:25 +00001280 if (loc.isInvalid())
1281 loc = overridden->getLocation();
1282 Diag(loc, diag::note_related_result_type_explicit)
1283 << /*current method*/ 1 << range;
1284 return;
1285 }
1286
1287 // Otherwise, if we have an interesting method family, note that.
1288 // This should always trigger if the above didn't.
1289 if (ObjCMethodFamily family = MD->getMethodFamily())
1290 Diag(MD->getLocation(), diag::note_related_result_type_family)
1291 << /*current method*/ 1
1292 << family;
1293}
1294
Douglas Gregor33823722011-06-11 01:09:30 +00001295void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1296 E = E->IgnoreParenImpCasts();
1297 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1298 if (!MsgSend)
1299 return;
1300
1301 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1302 if (!Method)
1303 return;
1304
1305 if (!Method->hasRelatedResultType())
1306 return;
Alp Toker314cc812014-01-25 16:55:45 +00001307
1308 if (Context.hasSameUnqualifiedType(
1309 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
Douglas Gregor33823722011-06-11 01:09:30 +00001310 return;
Alp Toker314cc812014-01-25 16:55:45 +00001311
1312 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
Douglas Gregorbab8a962011-09-08 01:46:34 +00001313 Context.getObjCInstanceType()))
1314 return;
1315
Douglas Gregor33823722011-06-11 01:09:30 +00001316 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1317 << Method->isInstanceMethod() << Method->getSelector()
1318 << MsgSend->getType();
1319}
1320
1321bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001322 MultiExprArg Args,
1323 Selector Sel,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001324 ArrayRef<SourceLocation> SelectorLocs,
1325 ObjCMethodDecl *Method,
Douglas Gregor33823722011-06-11 01:09:30 +00001326 bool isClassMessage, bool isSuperMessage,
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001327 SourceLocation lbrac, SourceLocation rbrac,
John McCall7decc9e2010-11-18 06:31:45 +00001328 QualType &ReturnType, ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001329 SourceLocation SelLoc;
1330 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1331 SelLoc = SelectorLocs.front();
1332 else
1333 SelLoc = lbrac;
1334
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001335 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001336 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001337 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001338 if (Args[i]->isTypeDependent())
1339 continue;
1340
John McCallcc5788c2013-03-04 07:34:02 +00001341 ExprResult result;
1342 if (getLangOpts().DebuggerSupport) {
1343 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001344 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001345 } else {
1346 result = DefaultArgumentPromotion(Args[i]);
1347 }
1348 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001349 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001350 Args[i] = result.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001351 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001352
John McCall31168b02011-06-15 23:02:42 +00001353 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001354 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001355 DiagID = diag::err_arc_method_not_found;
1356 else
1357 DiagID = isClassMessage ? diag::warn_class_method_not_found
1358 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001359 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001360 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahanian06499232013-06-18 17:10:58 +00001361 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001362 if (getLangOpts().ObjCAutoRefCount)
1363 DiagID = diag::error_method_not_found_with_typo;
1364 else
1365 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1366 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001367 Selector MatchedSel = OMD->getSelector();
1368 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian5ab87502014-08-12 22:16:41 +00001369 if (MatchedSel.isUnarySelector())
1370 Diag(SelLoc, DiagID)
1371 << Sel<< isClassMessage << MatchedSel
1372 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1373 else
1374 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001375 }
1376 else
1377 Diag(SelLoc, DiagID)
1378 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001379 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001380 // Find the class to which we are sending this message.
1381 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian478536b2013-05-15 15:27:35 +00001382 if (ObjCInterfaceDecl *Class =
1383 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl())
1384 Diag(Class->getLocation(), diag::note_receiver_class_declared);
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001385 }
1386 }
John McCall3f4138c2011-07-13 17:56:40 +00001387
1388 // In debuggers, we want to use __unknown_anytype for these
1389 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001390 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001391 ReturnType = Context.UnknownAnyTy;
1392 } else {
1393 ReturnType = Context.getObjCIdType();
1394 }
John McCall7decc9e2010-11-18 06:31:45 +00001395 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001396 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001397 }
Mike Stump11289f42009-09-09 15:08:12 +00001398
Douglas Gregor33823722011-06-11 01:09:30 +00001399 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1400 isSuperMessage);
Alp Toker314cc812014-01-25 16:55:45 +00001401 VK = Expr::getValueKindForType(Method->getReturnType());
Mike Stump11289f42009-09-09 15:08:12 +00001402
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001403 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001404 // Method might have more arguments than selector indicates. This is due
1405 // to addition of c-style arguments in method.
1406 if (Method->param_size() > Sel.getNumArgs())
1407 NumNamedArgs = Method->param_size();
1408 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001409 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001410 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001411 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001412 return false;
1413 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001414
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001415 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001416 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001417 // We can't do any type-checking on a type-dependent argument.
1418 if (Args[i]->isTypeDependent())
1419 continue;
1420
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001421 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001422
Alp Toker03376dc2014-07-07 09:02:20 +00001423 ParmVarDecl *param = Method->parameters()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001424 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001425
John McCall4124c492011-10-17 18:40:02 +00001426 // Strip the unbridged-cast placeholder expression off unless it's
1427 // a consumed argument.
1428 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1429 !param->hasAttr<CFConsumedAttr>())
1430 argExpr = stripARCUnbridgedCast(argExpr);
1431
John McCallea0a39e2012-11-14 00:49:39 +00001432 // If the parameter is __unknown_anytype, infer its type
1433 // from the argument.
1434 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001435 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001436 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001437 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001438 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001439 } else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001440 Args[i] = argE.get();
John McCallea0a39e2012-11-14 00:49:39 +00001441
John McCallcc5788c2013-03-04 07:34:02 +00001442 // Update the parameter type in-place.
1443 param->setType(paramType);
1444 }
1445 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001446 }
1447
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001448 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall4124c492011-10-17 18:40:02 +00001449 param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001450 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001451 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001452
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001453 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall4124c492011-10-17 18:40:02 +00001454 param);
Fariborz Jahaniana1db7df2014-07-31 17:39:50 +00001455 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001456 if (ArgE.isInvalid())
1457 IsError = true;
1458 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001459 Args[i] = ArgE.getAs<Expr>();
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001460 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001461
1462 // Promote additional arguments to variadic methods.
1463 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001464 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001465 if (Args[i]->isTypeDependent())
1466 continue;
1467
Jordy Roseaca01f92012-05-12 17:32:52 +00001468 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
Craig Topperc3ec1492014-05-26 06:22:03 +00001469 nullptr);
John Wiegley01296292011-04-08 18:41:53 +00001470 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001471 Args[i] = Arg.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001472 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001473 } else {
1474 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001475 if (Args.size() != NumNamedArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00001476 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001477 diag::err_typecheck_call_too_many_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001478 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001479 << Method->getSourceRange()
Chris Lattner3b054132008-11-19 05:08:23 +00001480 << SourceRange(Args[NumNamedArgs]->getLocStart(),
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001481 Args.back()->getLocEnd());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001482 }
1483 }
1484
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001485 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001486
1487 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001488 IsError |= CheckObjCMethodCall(
Robert Wilhelm88e02492013-08-19 07:57:02 +00001489 Method, SelLoc, makeArrayRef<const Expr *>(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001490
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001491 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001492}
1493
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001494bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001495 // 'self' is objc 'self' in an objc method only.
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001496 ObjCMethodDecl *Method =
1497 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1498 return isSelfExpr(RExpr, Method);
1499}
1500
1501bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
John McCallfe96e0b2011-11-06 09:01:30 +00001502 if (!method) return false;
1503
John McCall31168b02011-06-15 23:02:42 +00001504 receiver = receiver->IgnoreParenLValueCasts();
1505 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001506 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001507 return true;
1508 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001509}
1510
John McCall526ab472011-10-25 17:37:35 +00001511/// LookupMethodInType - Look up a method in an ObjCObjectType.
1512ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1513 bool isInstance) {
1514 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1515 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1516 // Look it up in the main interface (and categories, etc.)
1517 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1518 return method;
1519
1520 // Okay, look for "private" methods declared in any
1521 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001522 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1523 return method;
John McCall526ab472011-10-25 17:37:35 +00001524 }
1525
1526 // Check qualifiers.
Aaron Ballman1683f7b2014-03-17 15:55:30 +00001527 for (const auto *I : objType->quals())
1528 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
John McCall526ab472011-10-25 17:37:35 +00001529 return method;
1530
Craig Topperc3ec1492014-05-26 06:22:03 +00001531 return nullptr;
John McCall526ab472011-10-25 17:37:35 +00001532}
1533
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001534/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1535/// list of a qualified objective pointer type.
1536ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1537 const ObjCObjectPointerType *OPT,
1538 bool Instance)
1539{
Craig Topperc3ec1492014-05-26 06:22:03 +00001540 ObjCMethodDecl *MD = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +00001541 for (const auto *PROTO : OPT->quals()) {
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001542 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1543 return MD;
1544 }
1545 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001546 return nullptr;
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001547}
1548
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001549static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1550 if (!Receiver)
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001551 return;
1552
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001553 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver))
1554 Receiver = OVE->getSourceExpr();
1555
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001556 Expr *RExpr = Receiver->IgnoreParenImpCasts();
1557 SourceLocation Loc = RExpr->getLocStart();
1558 QualType T = RExpr->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001559 const ObjCPropertyDecl *PDecl = nullptr;
1560 const ObjCMethodDecl *GDecl = nullptr;
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001561 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1562 RExpr = POE->getSyntacticForm();
1563 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1564 if (PRE->isImplicitProperty()) {
1565 GDecl = PRE->getImplicitPropertyGetter();
1566 if (GDecl) {
Alp Toker314cc812014-01-25 16:55:45 +00001567 T = GDecl->getReturnType();
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001568 }
1569 }
1570 else {
1571 PDecl = PRE->getExplicitProperty();
1572 if (PDecl) {
1573 T = PDecl->getType();
1574 }
1575 }
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001576 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001577 }
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001578 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) {
1579 // See if receiver is a method which envokes a synthesized getter
1580 // backing a 'weak' property.
1581 ObjCMethodDecl *Method = ME->getMethodDecl();
Jordan Rose2bd991a2012-10-10 16:42:54 +00001582 if (Method && Method->getSelector().getNumArgs() == 0) {
1583 PDecl = Method->findPropertyDecl();
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001584 if (PDecl)
1585 T = PDecl->getType();
1586 }
1587 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001588
Jordan Rose13d6b712012-09-28 22:21:42 +00001589 if (T.getObjCLifetime() != Qualifiers::OCL_Weak) {
1590 if (!PDecl)
1591 return;
1592 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak))
1593 return;
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001594 }
Jordan Rose13d6b712012-09-28 22:21:42 +00001595
1596 S.Diag(Loc, diag::warn_receiver_is_weak)
1597 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1598
1599 if (PDecl)
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001600 S.Diag(PDecl->getLocation(), diag::note_property_declare);
Jordan Rose13d6b712012-09-28 22:21:42 +00001601 else if (GDecl)
1602 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
1603
1604 S.Diag(Loc, diag::note_arc_assign_to_strong);
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001605}
1606
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001607/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1608/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001609ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001610HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001611 Expr *BaseExpr, SourceLocation OpLoc,
1612 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001613 SourceLocation MemberLoc,
1614 SourceLocation SuperLoc, QualType SuperType,
1615 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001616 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1617 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001618
Benjamin Kramer365082d2012-05-19 16:34:46 +00001619 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001620 Diag(MemberLoc, diag::err_invalid_property_name)
1621 << MemberName << QualType(OPT, 0);
1622 return ExprError();
1623 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001624
1625 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregord6459312011-04-20 18:19:55 +00001626
Douglas Gregor4123a862011-11-14 22:10:01 +00001627 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1628 : BaseExpr->getSourceRange();
1629 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001630 diag::err_property_not_found_forward_class,
1631 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001632 return ExprError();
Douglas Gregor4123a862011-11-14 22:10:01 +00001633
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001634 // Search for a declared property first.
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001635 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001636 // Check whether we can reference this property.
1637 if (DiagnoseUseOfDecl(PD, MemberLoc))
1638 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001639 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001640 return new (Context)
1641 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1642 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001643 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001644 return new (Context)
1645 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1646 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001647 }
1648 // Check protocols on qualified interfaces.
Aaron Ballman83731462014-03-17 16:14:00 +00001649 for (const auto *I : OPT->quals())
1650 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001651 // Check whether we can reference this property.
1652 if (DiagnoseUseOfDecl(PD, MemberLoc))
1653 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001654
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001655 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001656 return new (Context) ObjCPropertyRefExpr(
1657 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1658 SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001659 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001660 return new (Context)
1661 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1662 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001663 }
1664 // If that failed, look for an "implicit" property by seeing if the nullary
1665 // selector is implemented.
1666
1667 // FIXME: The logic for looking up nullary and unary selectors should be
1668 // shared with the code in ActOnInstanceMessage.
1669
1670 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1671 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001672
1673 // May be founf in property's qualified list.
1674 if (!Getter)
1675 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001676
1677 // If this reference is in an @implementation, check for 'private' methods.
1678 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001679 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001680
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001681 if (Getter) {
1682 // Check if we can reference this property.
1683 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1684 return ExprError();
1685 }
1686 // If we found a getter then this may be a valid dot-reference, we
1687 // will look for the matching setter, in case it is needed.
1688 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001689 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1690 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001691 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001692
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001693 // May be founf in property's qualified list.
1694 if (!Setter)
1695 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1696
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001697 if (!Setter) {
1698 // If this reference is in an @implementation, also check for 'private'
1699 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001700 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001701 }
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001702
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001703 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1704 return ExprError();
1705
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001706 // Special warning if member name used in a property-dot for a setter accessor
1707 // does not use a property with same name; e.g. obj.X = ... for a property with
1708 // name 'x'.
1709 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor()
1710 && !IFace->FindPropertyDeclaration(Member)) {
1711 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl())
1712 Diag(MemberLoc,
1713 diag::warn_property_access_suggest)
1714 << MemberName << QualType(OPT, 0) << PDecl->getName()
1715 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
1716 }
1717
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001718 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001719 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001720 return new (Context)
1721 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1722 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001723 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001724 return new (Context)
1725 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1726 OK_ObjCProperty, MemberLoc, BaseExpr);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001727
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001728 }
1729
1730 // Attempt to correct for typos in property names.
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001731 DeclFilterCCC<ObjCPropertyDecl> Validator;
1732 if (TypoCorrection Corrected = CorrectTypo(
Craig Topperc3ec1492014-05-26 06:22:03 +00001733 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName,
1734 nullptr, nullptr, Validator, CTK_ErrorRecovery, IFace, false, OPT)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001735 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1736 << MemberName << QualType(OPT, 0));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001737 DeclarationName TypoResult = Corrected.getCorrection();
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001738 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1739 TypoResult, MemberLoc,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001740 SuperLoc, SuperType, Super);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001741 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001742 ObjCInterfaceDecl *ClassDeclared;
1743 if (ObjCIvarDecl *Ivar =
1744 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1745 QualType T = Ivar->getType();
1746 if (const ObjCObjectPointerType * OBJPT =
1747 T->getAsObjCInterfacePointerType()) {
Douglas Gregor4123a862011-11-14 22:10:01 +00001748 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001749 diag::err_property_not_as_forward_class,
1750 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001751 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001752 }
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001753 Diag(MemberLoc,
1754 diag::err_ivar_access_using_property_syntax_suggest)
1755 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1756 << FixItHint::CreateReplacement(OpLoc, "->");
1757 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001758 }
Chris Lattner90c58fa2010-04-11 07:51:10 +00001759
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001760 Diag(MemberLoc, diag::err_property_not_found)
1761 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001762 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001763 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001764 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001765 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001766}
1767
1768
1769
John McCalldadc5752010-08-24 06:29:42 +00001770ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001771ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1772 IdentifierInfo &propertyName,
1773 SourceLocation receiverNameLoc,
1774 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001775
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001776 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001777 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1778 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001779
1780 bool IsSuper = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00001781 if (!IFace) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001782 // If the "receiver" is 'super' in a method, handle it as an expression-like
1783 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001784 if (receiverNamePtr->isStr("super")) {
Douglas Gregor33823722011-06-11 01:09:30 +00001785 IsSuper = true;
1786
Eli Friedman24af8502012-02-03 22:47:37 +00001787 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001788 if (CurMethod->isInstanceMethod()) {
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00001789 ObjCInterfaceDecl *Super =
1790 CurMethod->getClassInterface()->getSuperClass();
1791 if (!Super) {
1792 // The current class does not have a superclass.
1793 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1794 << CurMethod->getClassInterface()->getIdentifier();
1795 return ExprError();
1796 }
1797 QualType T = Context.getObjCInterfaceType(Super);
Chris Lattnera36ec422010-04-11 08:28:14 +00001798 T = Context.getObjCObjectPointerType(T);
Craig Topperc3ec1492014-05-26 06:22:03 +00001799
Chris Lattnera36ec422010-04-11 08:28:14 +00001800 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001801 /*BaseExpr*/nullptr,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001802 SourceLocation()/*OpLoc*/,
1803 &propertyName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001804 propertyNameLoc,
1805 receiverNameLoc, T, true);
Chris Lattnera36ec422010-04-11 08:28:14 +00001806 }
Mike Stump11289f42009-09-09 15:08:12 +00001807
Chris Lattnera36ec422010-04-11 08:28:14 +00001808 // Otherwise, if this is a class method, try dispatching to our
1809 // superclass.
1810 IFace = CurMethod->getClassInterface()->getSuperClass();
1811 }
John McCall5f2d5562011-02-03 09:00:02 +00001812 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001813
1814 if (!IFace) {
Alp Tokerec543272013-12-24 09:48:30 +00001815 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1816 << tok::l_paren;
Chris Lattnera36ec422010-04-11 08:28:14 +00001817 return ExprError();
1818 }
1819 }
1820
1821 // Search for a declared property first.
Steve Naroff9527bbf2009-03-09 21:12:44 +00001822 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001823 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001824
1825 // If this reference is in an @implementation, check for 'private' methods.
1826 if (!Getter)
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001827 Getter = IFace->lookupPrivateClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001828
1829 if (Getter) {
1830 // FIXME: refactor/share with ActOnMemberReference().
1831 // Check if we can reference this property.
1832 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1833 return ExprError();
1834 }
Mike Stump11289f42009-09-09 15:08:12 +00001835
Steve Naroff9527bbf2009-03-09 21:12:44 +00001836 // Look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00001837 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001838 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1839 PP.getSelectorTable(),
1840 &propertyName);
Mike Stump11289f42009-09-09 15:08:12 +00001841
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001842 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001843 if (!Setter) {
1844 // If this reference is in an @implementation, also check for 'private'
1845 // methods.
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001846 Setter = IFace->lookupPrivateClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001847 }
1848 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00001849 if (!Setter)
1850 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001851
1852 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1853 return ExprError();
1854
1855 if (Getter || Setter) {
Douglas Gregor33823722011-06-11 01:09:30 +00001856 if (IsSuper)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001857 return new (Context)
1858 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1859 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
1860 Context.getObjCInterfaceType(IFace));
Douglas Gregor33823722011-06-11 01:09:30 +00001861
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001862 return new (Context) ObjCPropertyRefExpr(
1863 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
1864 propertyNameLoc, receiverNameLoc, IFace);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001865 }
1866 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1867 << &propertyName << Context.getObjCInterfaceType(IFace));
1868}
1869
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001870namespace {
1871
1872class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1873 public:
1874 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1875 // Determine whether "super" is acceptable in the current context.
1876 if (Method && Method->getClassInterface())
1877 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1878 }
1879
Craig Toppere14c0f82014-03-12 04:55:44 +00001880 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001881 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1882 candidate.isKeyword("super");
1883 }
1884};
1885
1886}
1887
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001888Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001889 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001890 SourceLocation NameLoc,
1891 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001892 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00001893 ParsedType &ReceiverType) {
1894 ReceiverType = ParsedType();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001895
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001896 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00001897 // messaging super. If the identifier is "super" and there is a
1898 // trailing dot, it's an instance message.
1899 if (IsSuper && S->isInObjcMethodScope())
1900 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001901
1902 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1903 LookupName(Result, S);
1904
1905 switch (Result.getResultKind()) {
1906 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00001907 // Normal name lookup didn't find anything. If we're in an
1908 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00001909 // FIXME: This is a hack. Ivar lookup should be part of normal
1910 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00001911 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00001912 if (!Method->getClassInterface()) {
1913 // Fall back: let the parser try to parse it as an instance message.
1914 return ObjCInstanceMessage;
1915 }
1916
Douglas Gregorca7136b2010-04-19 20:09:36 +00001917 ObjCInterfaceDecl *ClassDeclared;
1918 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1919 ClassDeclared))
1920 return ObjCInstanceMessage;
1921 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00001922
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001923 // Break out; we'll perform typo correction below.
1924 break;
1925
1926 case LookupResult::NotFoundInCurrentInstantiation:
1927 case LookupResult::FoundOverloaded:
1928 case LookupResult::FoundUnresolvedValue:
1929 case LookupResult::Ambiguous:
1930 Result.suppressDiagnostics();
1931 return ObjCInstanceMessage;
1932
1933 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00001934 // If the identifier is a class or not, and there is a trailing dot,
1935 // it's an instance message.
1936 if (HasTrailingDot)
1937 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001938 // We found something. If it's a type, then we have a class
1939 // message. Otherwise, it's an instance message.
1940 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001941 QualType T;
1942 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1943 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001944 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00001945 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001946 DiagnoseUseOfDecl(Type, NameLoc);
1947 }
1948 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00001949 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001950
Douglas Gregore5798dc2010-04-21 20:38:13 +00001951 // We have a class message, and T is the type we're
1952 // messaging. Build source-location information for it.
1953 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00001954 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00001955 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001956 }
1957 }
1958
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001959 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00001960 if (TypoCorrection Corrected =
1961 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
Craig Topperc3ec1492014-05-26 06:22:03 +00001962 nullptr, Validator, CTK_ErrorRecovery, nullptr, false,
1963 nullptr, false)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001964 if (Corrected.isKeyword()) {
1965 // If we've found the keyword "super" (the only keyword that would be
1966 // returned by CorrectTypo), this is a send to super.
Richard Smithf9b15102013-08-17 00:46:16 +00001967 diagnoseTypo(Corrected,
1968 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001969 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001970 } else if (ObjCInterfaceDecl *Class =
Richard Smithf9b15102013-08-17 00:46:16 +00001971 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001972 // If we found a declaration, correct when it refers to an Objective-C
1973 // class.
Richard Smithf9b15102013-08-17 00:46:16 +00001974 diagnoseTypo(Corrected,
1975 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001976 QualType T = Context.getObjCInterfaceType(Class);
1977 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1978 ReceiverType = CreateParsedType(T, TSInfo);
1979 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001980 }
1981 }
Richard Smithf9b15102013-08-17 00:46:16 +00001982
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001983 // Fall back: let the parser try to parse it as an instance message.
1984 return ObjCInstanceMessage;
1985}
Steve Naroff9527bbf2009-03-09 21:12:44 +00001986
John McCalldadc5752010-08-24 06:29:42 +00001987ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001988 SourceLocation SuperLoc,
1989 Selector Sel,
1990 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00001991 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001992 SourceLocation RBracLoc,
1993 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001994 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00001995 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00001996 if (!Method) {
1997 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1998 return ExprError();
1999 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002000
Douglas Gregor4fdba132010-04-21 20:01:04 +00002001 ObjCInterfaceDecl *Class = Method->getClassInterface();
2002 if (!Class) {
2003 Diag(SuperLoc, diag::error_no_super_class_message)
2004 << Method->getDeclName();
2005 return ExprError();
2006 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002007
Douglas Gregor4fdba132010-04-21 20:01:04 +00002008 ObjCInterfaceDecl *Super = Class->getSuperClass();
2009 if (!Super) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002010 // The current class does not have a superclass.
Ted Kremenek499897b2011-01-23 17:21:34 +00002011 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
2012 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002013 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002014 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002015
Douglas Gregor4fdba132010-04-21 20:01:04 +00002016 // We are in a method whose class has a superclass, so 'super'
2017 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00002018 if (Method->getSelector() == Sel)
2019 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00002020
Jordan Rose2afd6612012-10-19 16:05:26 +00002021 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00002022 // Since we are in an instance method, this is an instance
2023 // message to the superclass instance.
2024 QualType SuperTy = Context.getObjCInterfaceType(Super);
2025 SuperTy = Context.getObjCObjectPointerType(SuperTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00002026 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2027 Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002028 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002029 }
Douglas Gregor4fdba132010-04-21 20:01:04 +00002030
2031 // Since we are in a class method, this is a class message to
2032 // the superclass.
Craig Topperc3ec1492014-05-26 06:22:03 +00002033 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
Douglas Gregor4fdba132010-04-21 20:01:04 +00002034 Context.getObjCInterfaceType(Super),
Craig Topperc3ec1492014-05-26 06:22:03 +00002035 SuperLoc, Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002036 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002037}
2038
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002039
2040ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2041 bool isSuperReceiver,
2042 SourceLocation Loc,
2043 Selector Sel,
2044 ObjCMethodDecl *Method,
2045 MultiExprArg Args) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002046 TypeSourceInfo *receiverTypeInfo = nullptr;
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002047 if (!ReceiverType.isNull())
2048 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2049
2050 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2051 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2052 Sel, Method, Loc, Loc, Loc, Args,
2053 /*isImplicit=*/true);
2054
2055}
2056
Ted Kremeneke65b0862012-03-06 20:05:56 +00002057static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2058 unsigned DiagID,
2059 bool (*refactor)(const ObjCMessageExpr *,
2060 const NSAPI &, edit::Commit &)) {
2061 SourceLocation MsgLoc = Msg->getExprLoc();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002062 if (S.Diags.isIgnored(DiagID, MsgLoc))
Ted Kremeneke65b0862012-03-06 20:05:56 +00002063 return;
2064
2065 SourceManager &SM = S.SourceMgr;
2066 edit::Commit ECommit(SM, S.LangOpts);
2067 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2068 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2069 << Msg->getSelector() << Msg->getSourceRange();
2070 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2071 if (!ECommit.isCommitable())
2072 return;
2073 for (edit::Commit::edit_iterator
2074 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2075 const edit::Commit::Edit &Edit = *I;
2076 switch (Edit.Kind) {
2077 case edit::Commit::Act_Insert:
2078 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2079 Edit.Text,
2080 Edit.BeforePrev));
2081 break;
2082 case edit::Commit::Act_InsertFromRange:
2083 Builder.AddFixItHint(
2084 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2085 Edit.getInsertFromRange(SM),
2086 Edit.BeforePrev));
2087 break;
2088 case edit::Commit::Act_Remove:
2089 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2090 break;
2091 }
2092 }
2093 }
2094}
2095
2096static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2097 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2098 edit::rewriteObjCRedundantCallWithLiteral);
2099}
2100
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002101/// \brief Build an Objective-C class message expression.
2102///
2103/// This routine takes care of both normal class messages and
2104/// class messages to the superclass.
2105///
2106/// \param ReceiverTypeInfo Type source information that describes the
2107/// receiver of this message. This may be NULL, in which case we are
2108/// sending to the superclass and \p SuperLoc must be a valid source
2109/// location.
2110
2111/// \param ReceiverType The type of the object receiving the
2112/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2113/// type as that refers to. For a superclass send, this is the type of
2114/// the superclass.
2115///
2116/// \param SuperLoc The location of the "super" keyword in a
2117/// superclass message.
2118///
2119/// \param Sel The selector to which the message is being sent.
2120///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002121/// \param Method The method that this class message is invoking, if
2122/// already known.
2123///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002124/// \param LBracLoc The location of the opening square bracket ']'.
2125///
James Dennettffad8b72012-06-22 08:10:18 +00002126/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002127///
James Dennettffad8b72012-06-22 08:10:18 +00002128/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002129ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002130 QualType ReceiverType,
2131 SourceLocation SuperLoc,
2132 Selector Sel,
2133 ObjCMethodDecl *Method,
2134 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002135 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002136 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002137 MultiExprArg ArgsIn,
2138 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002139 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002140 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002141 if (LBracLoc.isInvalid()) {
2142 Diag(Loc, diag::err_missing_open_square_message_send)
2143 << FixItHint::CreateInsertion(Loc, "[");
2144 LBracLoc = Loc;
2145 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002146 SourceLocation SelLoc;
2147 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2148 SelLoc = SelectorLocs.front();
2149 else
2150 SelLoc = Loc;
2151
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002152 if (ReceiverType->isDependentType()) {
2153 // If the receiver type is dependent, we can't type-check anything
2154 // at this point. Build a dependent expression.
2155 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002156 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002157 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002158 return ObjCMessageExpr::Create(
2159 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2160 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2161 isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002162 }
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002163
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002164 // Find the class to which we are sending this message.
Craig Topperc3ec1492014-05-26 06:22:03 +00002165 ObjCInterfaceDecl *Class = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00002166 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2167 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002168 Diag(Loc, diag::err_invalid_receiver_class_message)
2169 << ReceiverType;
2170 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002171 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002172 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002173 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002174 if (!getLangOpts().CPlusPlus)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002175 (void)DiagnoseUseOfDecl(Class, SelLoc);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002176 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002177 if (!Method) {
Douglas Gregor4123a862011-11-14 22:10:01 +00002178 SourceRange TypeRange
2179 = SuperLoc.isValid()? SourceRange(SuperLoc)
2180 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002181 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002182 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002183 ? diag::err_arc_receiver_forward_class
2184 : diag::warn_receiver_forward_class),
2185 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002186 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorb5186b12010-04-22 17:01:48 +00002187 Method = LookupFactoryMethodInGlobalPool(Sel,
2188 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002189 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002190 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2191 << Method->getDeclName();
2192 }
2193 if (!Method)
2194 Method = Class->lookupClassMethod(Sel);
2195
2196 // If we have an implementation in scope, check "private" methods.
2197 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002198 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002199
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002200 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002201 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002202 }
Mike Stump11289f42009-09-09 15:08:12 +00002203
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002204 // Check the argument types and determine the result type.
2205 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002206 ExprValueKind VK = VK_RValue;
2207
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002208 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002209 Expr **Args = ArgsIn.data();
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002210 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2211 Sel, SelectorLocs,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00002212 Method, true,
Douglas Gregor33823722011-06-11 01:09:30 +00002213 SuperLoc.isValid(), LBracLoc, RBracLoc,
2214 ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002215 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002216
Alp Toker314cc812014-01-25 16:55:45 +00002217 if (Method && !Method->getReturnType()->isVoidType() &&
2218 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002219 diag::err_illegal_message_expr_incomplete_type))
2220 return ExprError();
2221
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002222 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002223 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002224 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002225 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002226 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002227 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002228 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002229 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002230 else {
John McCall7decc9e2010-11-18 06:31:45 +00002231 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002232 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002233 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002234 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002235 if (!isImplicit)
2236 checkCocoaAPI(*this, Result);
2237 }
Douglas Gregoraae38d62010-05-22 05:17:18 +00002238 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002239}
2240
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002241// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002242// ArgExprs is optional - if it is present, the number of expressions
2243// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002244ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002245 ParsedType Receiver,
2246 Selector Sel,
2247 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002248 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002249 SourceLocation RBracLoc,
2250 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002251 TypeSourceInfo *ReceiverTypeInfo;
2252 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2253 if (ReceiverType.isNull())
2254 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002255
Mike Stump11289f42009-09-09 15:08:12 +00002256
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002257 if (!ReceiverTypeInfo)
2258 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2259
2260 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002261 /*SuperLoc=*/SourceLocation(), Sel,
2262 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2263 Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002264}
2265
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002266ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2267 QualType ReceiverType,
2268 SourceLocation Loc,
2269 Selector Sel,
2270 ObjCMethodDecl *Method,
2271 MultiExprArg Args) {
2272 return BuildInstanceMessage(Receiver, ReceiverType,
2273 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2274 Sel, Method, Loc, Loc, Loc, Args,
2275 /*isImplicit=*/true);
2276}
2277
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002278/// \brief Build an Objective-C instance message expression.
2279///
2280/// This routine takes care of both normal instance messages and
2281/// instance messages to the superclass instance.
2282///
2283/// \param Receiver The expression that computes the object that will
2284/// receive this message. This may be empty, in which case we are
2285/// sending to the superclass instance and \p SuperLoc must be a valid
2286/// source location.
2287///
2288/// \param ReceiverType The (static) type of the object receiving the
2289/// message. When a \p Receiver expression is provided, this is the
2290/// same type as that expression. For a superclass instance send, this
2291/// is a pointer to the type of the superclass.
2292///
2293/// \param SuperLoc The location of the "super" keyword in a
2294/// superclass instance message.
2295///
2296/// \param Sel The selector to which the message is being sent.
2297///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002298/// \param Method The method that this instance message is invoking, if
2299/// already known.
2300///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002301/// \param LBracLoc The location of the opening square bracket ']'.
2302///
James Dennettffad8b72012-06-22 08:10:18 +00002303/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002304///
James Dennettffad8b72012-06-22 08:10:18 +00002305/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002306ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002307 QualType ReceiverType,
2308 SourceLocation SuperLoc,
2309 Selector Sel,
2310 ObjCMethodDecl *Method,
2311 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002312 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002313 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002314 MultiExprArg ArgsIn,
2315 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002316 // The location of the receiver.
2317 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002318 SourceRange RecRange =
2319 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2320 SourceLocation SelLoc;
2321 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2322 SelLoc = SelectorLocs.front();
2323 else
2324 SelLoc = Loc;
2325
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002326 if (LBracLoc.isInvalid()) {
2327 Diag(Loc, diag::err_missing_open_square_message_send)
2328 << FixItHint::CreateInsertion(Loc, "[");
2329 LBracLoc = Loc;
2330 }
2331
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002332 // If we have a receiver expression, perform appropriate promotions
2333 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002334 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002335 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002336 ExprResult Result;
2337 if (Receiver->getType() == Context.UnknownAnyTy)
2338 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2339 else
2340 Result = CheckPlaceholderExpr(Receiver);
2341 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002342 Receiver = Result.get();
John McCall4124c492011-10-17 18:40:02 +00002343 }
2344
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002345 if (Receiver->isTypeDependent()) {
2346 // If the receiver is type-dependent, we can't type-check anything
2347 // at this point. Build a dependent expression.
2348 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002349 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002350 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002351 return ObjCMessageExpr::Create(
2352 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2353 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2354 RBracLoc, isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002355 }
2356
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002357 // If necessary, apply function/array conversion to the receiver.
2358 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002359 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2360 if (Result.isInvalid())
2361 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002362 Receiver = Result.get();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002363 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002364
2365 // If the receiver is an ObjC pointer, a block pointer, or an
2366 // __attribute__((NSObject)) pointer, we don't need to do any
2367 // special conversion in order to look up a receiver.
2368 if (ReceiverType->isObjCRetainableType()) {
2369 // do nothing
2370 } else if (!getLangOpts().ObjCAutoRefCount &&
2371 !Context.getObjCIdType().isNull() &&
2372 (ReceiverType->isPointerType() ||
2373 ReceiverType->isIntegerType())) {
2374 // Implicitly convert integers and pointers to 'id' but emit a warning.
2375 // But not in ARC.
2376 Diag(Loc, diag::warn_bad_receiver_type)
2377 << ReceiverType
2378 << Receiver->getSourceRange();
2379 if (ReceiverType->isPointerType()) {
2380 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002381 CK_CPointerToObjCPointerCast).get();
John McCall80c93a02013-03-01 09:20:14 +00002382 } else {
2383 // TODO: specialized warning on null receivers?
2384 bool IsNull = Receiver->isNullPointerConstant(Context,
2385 Expr::NPC_ValueDependentIsNull);
2386 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2387 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002388 Kind).get();
John McCall80c93a02013-03-01 09:20:14 +00002389 }
2390 ReceiverType = Receiver->getType();
2391 } else if (getLangOpts().CPlusPlus) {
Douglas Gregor4b60a152013-11-07 22:34:54 +00002392 // The receiver must be a complete type.
2393 if (RequireCompleteType(Loc, Receiver->getType(),
2394 diag::err_incomplete_receiver_type))
2395 return ExprError();
2396
John McCall80c93a02013-03-01 09:20:14 +00002397 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2398 if (result.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002399 Receiver = result.get();
John McCall80c93a02013-03-01 09:20:14 +00002400 ReceiverType = Receiver->getType();
2401 }
2402 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002403 }
2404
John McCall80c93a02013-03-01 09:20:14 +00002405 // There's a somewhat weird interaction here where we assume that we
2406 // won't actually have a method unless we also don't need to do some
2407 // of the more detailed type-checking on the receiver.
2408
Douglas Gregorb5186b12010-04-22 17:01:48 +00002409 if (!Method) {
2410 // Handle messages to id.
Fariborz Jahanian32e59ba2010-08-10 18:10:50 +00002411 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002412 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002413 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2414 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002415 SourceRange(LBracLoc, RBracLoc),
2416 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002417 if (!Method)
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002418 Method = LookupFactoryMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002419 SourceRange(LBracLoc,RBracLoc),
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002420 receiverIsId);
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00002421 if (Method) {
2422 SmallVector<ObjCMethodDecl*, 4> Methods;
2423 if (CollectMultipleMethodsInGlobalPool(Sel, Methods,
2424 Method->isInstanceMethod()))
2425 if (ObjCMethodDecl *BestMethod = SelectBestMethod(Sel, ArgsIn, Methods))
2426 Method = BestMethod;
2427 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002428 } else if (ReceiverType->isObjCClassType() ||
2429 ReceiverType->isObjCQualifiedClassType()) {
2430 // Handle messages to Class.
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002431 // We allow sending a message to a qualified Class ("Class<foo>"), which
2432 // is ok as long as one of the protocols implements the selector (if not, warn).
2433 if (const ObjCObjectPointerType *QClassTy
2434 = ReceiverType->getAsObjCQualifiedClassType()) {
2435 // Search protocols for class methods.
2436 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2437 if (!Method) {
2438 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2439 // warn if instance method found for a Class message.
2440 if (Method) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002441 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002442 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002443 Diag(Method->getLocation(), diag::note_method_declared_at)
2444 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002445 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002446 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002447 } else {
2448 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2449 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2450 // First check the public methods in the class interface.
2451 Method = ClassDecl->lookupClassMethod(Sel);
2452
2453 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002454 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002455 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002456 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002457 return ExprError();
2458 }
2459 if (!Method) {
2460 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002461 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002462 Method = LookupFactoryMethodInGlobalPool(Sel,
2463 SourceRange(LBracLoc, RBracLoc),
2464 true);
2465 if (!Method) {
2466 // If no class (factory) method was found, check if an _instance_
2467 // method of the same name exists in the root class only.
2468 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002469 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002470 true);
2471 if (Method)
2472 if (const ObjCInterfaceDecl *ID =
2473 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2474 if (ID->getSuperClass())
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002475 Diag(SelLoc, diag::warn_root_inst_method_not_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002476 << Sel << SourceRange(LBracLoc, RBracLoc);
2477 }
2478 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002479 }
2480 }
2481 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002482 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002483 ObjCInterfaceDecl *ClassDecl = nullptr;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002484
2485 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2486 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002487 // And as long as message is not deprecated/unavailable (warn if it is).
Douglas Gregorb5186b12010-04-22 17:01:48 +00002488 if (const ObjCObjectPointerType *QIdTy
2489 = ReceiverType->getAsObjCQualifiedIdType()) {
2490 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002491 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2492 if (!Method)
2493 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002494 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002495 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002496 } else if (const ObjCObjectPointerType *OCIType
2497 = ReceiverType->getAsObjCInterfacePointerType()) {
2498 // We allow sending a message to a pointer to an interface (an object).
2499 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002500
Douglas Gregor4123a862011-11-14 22:10:01 +00002501 // Try to complete the type. Under ARC, this is a hard error from which
2502 // we don't try to recover.
Craig Topperc3ec1492014-05-26 06:22:03 +00002503 const ObjCInterfaceDecl *forwardClass = nullptr;
Douglas Gregor4123a862011-11-14 22:10:01 +00002504 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002505 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002506 ? diag::err_arc_receiver_forward_instance
2507 : diag::warn_receiver_forward_instance,
2508 Receiver? Receiver->getSourceRange()
2509 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002510 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002511 return ExprError();
2512
2513 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanianc934de62012-02-03 01:02:44 +00002514 Diag(Receiver ? Receiver->getLocStart()
2515 : SuperLoc, diag::note_receiver_is_id);
Craig Topperc3ec1492014-05-26 06:22:03 +00002516 Method = nullptr;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002517 } else {
2518 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002519 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002520
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002521 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002522 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002523 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2524
Douglas Gregorb5186b12010-04-22 17:01:48 +00002525 if (!Method) {
2526 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002527 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002528
David Blaikiebbafb8a2012-03-11 07:00:24 +00002529 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002530 Diag(SelLoc, diag::err_arc_may_not_respond)
2531 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002532 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002533 return ExprError();
2534 }
2535
Douglas Gregor486b74e2011-09-27 16:10:05 +00002536 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002537 // If we still haven't found a method, look in the global pool. This
2538 // behavior isn't very desirable, however we need it for GCC
2539 // compatibility. FIXME: should we deviate??
2540 if (OCIType->qual_empty()) {
2541 Method = LookupInstanceMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002542 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002543 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002544 Diag(SelLoc, diag::warn_maynot_respond)
2545 << OCIType->getInterfaceDecl()->getIdentifier()
2546 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002547 }
2548 }
2549 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002550 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002551 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002552 } else {
John McCall80c93a02013-03-01 09:20:14 +00002553 // Reject other random receiver types (e.g. structs).
2554 Diag(Loc, diag::err_bad_receiver_type)
2555 << ReceiverType << Receiver->getSourceRange();
2556 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002557 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002558 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002559 }
Mike Stump11289f42009-09-09 15:08:12 +00002560
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002561 FunctionScopeInfo *DIFunctionScopeInfo =
2562 (Method && Method->getMethodFamily() == OMF_init)
Craig Topperc3ec1492014-05-26 06:22:03 +00002563 ? getEnclosingFunction() : nullptr;
2564
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002565 if (DIFunctionScopeInfo &&
2566 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002567 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2568 bool isDesignatedInitChain = false;
2569 if (SuperLoc.isValid()) {
2570 if (const ObjCObjectPointerType *
2571 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2572 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
Argyrios Kyrtzidisd664a342013-12-13 03:48:17 +00002573 // Either we know this is a designated initializer or we
2574 // conservatively assume it because we don't know for sure.
2575 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2576 ID->isDesignatedInitializer(Sel)) {
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002577 isDesignatedInitChain = true;
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002578 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002579 }
2580 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002581 }
2582 }
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002583 if (!isDesignatedInitChain) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002584 const ObjCMethodDecl *InitMethod = nullptr;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002585 bool isDesignated =
2586 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2587 assert(isDesignated && InitMethod);
2588 (void)isDesignated;
2589 Diag(SelLoc, SuperLoc.isValid() ?
2590 diag::warn_objc_designated_init_non_designated_init_call :
2591 diag::warn_objc_designated_init_non_super_designated_init_call);
2592 Diag(InitMethod->getLocation(),
2593 diag::note_objc_designated_init_marked_here);
2594 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002595 }
2596
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002597 if (DIFunctionScopeInfo &&
2598 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002599 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2600 if (SuperLoc.isValid()) {
2601 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2602 } else {
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002603 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002604 }
2605 }
2606
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002607 // Check the message arguments.
2608 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002609 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002610 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002611 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00002612 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2613 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002614 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2615 Sel, SelectorLocs, Method,
Douglas Gregor33823722011-06-11 01:09:30 +00002616 ClassMessage, SuperLoc.isValid(),
John McCall7decc9e2010-11-18 06:31:45 +00002617 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002618 return ExprError();
Alp Toker314cc812014-01-25 16:55:45 +00002619
2620 if (Method && !Method->getReturnType()->isVoidType() &&
2621 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002622 diag::err_illegal_message_expr_incomplete_type))
2623 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00002624
John McCall31168b02011-06-15 23:02:42 +00002625 // In ARC, forbid the user from sending messages to
2626 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002627 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002628 ObjCMethodFamily family =
2629 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2630 switch (family) {
2631 case OMF_init:
2632 if (Method)
2633 checkInitMethod(Method, ReceiverType);
2634
2635 case OMF_None:
2636 case OMF_alloc:
2637 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00002638 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002639 case OMF_mutableCopy:
2640 case OMF_new:
2641 case OMF_self:
2642 break;
2643
2644 case OMF_dealloc:
2645 case OMF_retain:
2646 case OMF_release:
2647 case OMF_autorelease:
2648 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002649 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2650 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00002651 break;
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002652
2653 case OMF_performSelector:
2654 if (Method && NumArgs >= 1) {
2655 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2656 Selector ArgSel = SelExp->getSelector();
2657 ObjCMethodDecl *SelMethod =
2658 LookupInstanceMethodInGlobalPool(ArgSel,
2659 SelExp->getSourceRange());
2660 if (!SelMethod)
2661 SelMethod =
2662 LookupFactoryMethodInGlobalPool(ArgSel,
2663 SelExp->getSourceRange());
2664 if (SelMethod) {
2665 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2666 switch (SelFamily) {
2667 case OMF_alloc:
2668 case OMF_copy:
2669 case OMF_mutableCopy:
2670 case OMF_new:
2671 case OMF_self:
2672 case OMF_init:
2673 // Issue error, unless ns_returns_not_retained.
2674 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2675 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002676 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002677 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002678 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2679 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002680 }
2681 break;
2682 default:
2683 // +0 call. OK. unless ns_returns_retained.
2684 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2685 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002686 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002687 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002688 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2689 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002690 }
2691 break;
2692 }
2693 }
2694 } else {
2695 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002696 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002697 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2698 }
2699 }
2700 break;
John McCall31168b02011-06-15 23:02:42 +00002701 }
2702 }
2703
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002704 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00002705 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002706 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002707 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002708 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002709 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002710 makeArrayRef(Args, NumArgs), RBracLoc,
2711 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002712 else {
John McCall7decc9e2010-11-18 06:31:45 +00002713 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002714 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002715 makeArrayRef(Args, NumArgs), RBracLoc,
2716 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002717 if (!isImplicit)
2718 checkCocoaAPI(*this, Result);
2719 }
John McCall31168b02011-06-15 23:02:42 +00002720
David Blaikiebbafb8a2012-03-11 07:00:24 +00002721 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahanian9277ff42014-06-17 23:35:13 +00002722 // Do not warn about IBOutlet weak property receivers being set to null
2723 // as this cannot asynchronously happen.
2724 bool WarnWeakReceiver = true;
2725 if (isImplicit && Method)
2726 if (const ObjCPropertyDecl *PropertyDecl = Method->findPropertyDecl())
2727 WarnWeakReceiver = !PropertyDecl->hasAttr<IBOutletAttr>();
2728 if (WarnWeakReceiver)
2729 DiagnoseARCUseOfWeakReceiver(*this, Receiver);
Fariborz Jahanian6bd22262012-04-04 20:05:25 +00002730
John McCall31168b02011-06-15 23:02:42 +00002731 // In ARC, annotate delegate init calls.
2732 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00002733 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00002734 // Only consider init calls *directly* in init implementations,
2735 // not within blocks.
2736 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2737 if (method && method->getMethodFamily() == OMF_init) {
2738 // The implicit assignment to self means we also don't want to
2739 // consume the result.
2740 Result->setDelegateInitCall(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002741 return Result;
John McCall31168b02011-06-15 23:02:42 +00002742 }
2743 }
2744
2745 // In ARC, check for message sends which are likely to introduce
2746 // retain cycles.
2747 checkRetainCycles(Result);
Jordan Rose22487652012-10-11 16:06:21 +00002748
2749 if (!isImplicit && Method) {
2750 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2751 bool IsWeak =
2752 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2753 if (!IsWeak && Sel.isUnarySelector())
2754 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002755 if (IsWeak &&
2756 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
2757 getCurFunction()->recordUseOfWeak(Result, Prop);
Jordan Rose22487652012-10-11 16:06:21 +00002758 }
2759 }
John McCall31168b02011-06-15 23:02:42 +00002760 }
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00002761
Douglas Gregoraae38d62010-05-22 05:17:18 +00002762 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002763}
2764
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002765static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2766 if (ObjCSelectorExpr *OSE =
2767 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2768 Selector Sel = OSE->getSelector();
2769 SourceLocation Loc = OSE->getAtLoc();
2770 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
2771 = S.ReferencedSelectors.find(Sel);
2772 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
2773 S.ReferencedSelectors.erase(Pos);
2774 }
2775}
2776
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002777// ActOnInstanceMessage - used for both unary and keyword messages.
2778// ArgExprs is optional - if it is present, the number of expressions
2779// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002780ExprResult Sema::ActOnInstanceMessage(Scope *S,
2781 Expr *Receiver,
2782 Selector Sel,
2783 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002784 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00002785 SourceLocation RBracLoc,
2786 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002787 if (!Receiver)
2788 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002789
2790 // A ParenListExpr can show up while doing error recovery with invalid code.
2791 if (isa<ParenListExpr>(Receiver)) {
2792 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
2793 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002794 Receiver = Result.get();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002795 }
Fariborz Jahanian17748062013-01-22 19:05:17 +00002796
2797 if (RespondsToSelectorSel.isNull()) {
2798 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
2799 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
2800 }
2801 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002802 RemoveSelectorFromWarningCache(*this, Args[0]);
Craig Topperc3ec1492014-05-26 06:22:03 +00002803
John McCallb268a282010-08-23 23:25:46 +00002804 return BuildInstanceMessage(Receiver, Receiver->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002805 /*SuperLoc=*/SourceLocation(), Sel,
2806 /*Method=*/nullptr, LBracLoc, SelectorLocs,
2807 RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002808}
Chris Lattner2a3569b2008-04-07 05:30:13 +00002809
John McCall31168b02011-06-15 23:02:42 +00002810enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00002811 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00002812 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00002813
2814 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00002815 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00002816
2817 /// id*, id***, void (^*)(),
2818 ACTC_indirectRetainable,
2819
2820 /// void* might be a normal C type, or it might a CF type.
2821 ACTC_voidPtr,
2822
2823 /// struct A*
2824 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00002825};
John McCalle4fe2452011-10-01 01:01:08 +00002826static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2827 return (ACTC == ACTC_retainable ||
2828 ACTC == ACTC_coreFoundation ||
2829 ACTC == ACTC_voidPtr);
2830}
2831static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2832 return ACTC == ACTC_none ||
2833 ACTC == ACTC_voidPtr ||
2834 ACTC == ACTC_coreFoundation;
2835}
2836
John McCall31168b02011-06-15 23:02:42 +00002837static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00002838 bool isIndirect = false;
John McCall31168b02011-06-15 23:02:42 +00002839
2840 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00002841 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00002842 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002843 isIndirect = true;
2844 }
John McCall31168b02011-06-15 23:02:42 +00002845
2846 // Drill through pointers and arrays recursively.
2847 while (true) {
2848 if (const PointerType *ptr = type->getAs<PointerType>()) {
2849 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002850
2851 // The first level of pointer may be the innermost pointer on a CF type.
2852 if (!isIndirect) {
2853 if (type->isVoidType()) return ACTC_voidPtr;
2854 if (type->isRecordType()) return ACTC_coreFoundation;
2855 }
John McCall31168b02011-06-15 23:02:42 +00002856 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2857 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2858 } else {
2859 break;
2860 }
John McCalle4fe2452011-10-01 01:01:08 +00002861 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00002862 }
2863
John McCalle4fe2452011-10-01 01:01:08 +00002864 if (isIndirect) {
2865 if (type->isObjCARCBridgableType())
2866 return ACTC_indirectRetainable;
2867 return ACTC_none;
2868 }
2869
2870 if (type->isObjCARCBridgableType())
2871 return ACTC_retainable;
2872
2873 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00002874}
2875
2876namespace {
John McCalle4fe2452011-10-01 01:01:08 +00002877 /// A result from the cast checker.
2878 enum ACCResult {
2879 /// Cannot be casted.
2880 ACC_invalid,
2881
2882 /// Can be safely retained or not retained.
2883 ACC_bottom,
2884
2885 /// Can be casted at +0.
2886 ACC_plusZero,
2887
2888 /// Can be casted at +1.
2889 ACC_plusOne
2890 };
2891 ACCResult merge(ACCResult left, ACCResult right) {
2892 if (left == right) return left;
2893 if (left == ACC_bottom) return right;
2894 if (right == ACC_bottom) return left;
2895 return ACC_invalid;
2896 }
2897
2898 /// A checker which white-lists certain expressions whose conversion
2899 /// to or from retainable type would otherwise be forbidden in ARC.
2900 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2901 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2902
John McCall31168b02011-06-15 23:02:42 +00002903 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00002904 ARCConversionTypeClass SourceClass;
2905 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002906 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00002907
2908 static bool isCFType(QualType type) {
2909 // Someday this can use ns_bridged. For now, it has to do this.
2910 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00002911 }
John McCalle4fe2452011-10-01 01:01:08 +00002912
2913 public:
2914 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002915 ARCConversionTypeClass target, bool diagnose)
2916 : Context(Context), SourceClass(source), TargetClass(target),
2917 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00002918
2919 using super::Visit;
2920 ACCResult Visit(Expr *e) {
2921 return super::Visit(e->IgnoreParens());
2922 }
2923
2924 ACCResult VisitStmt(Stmt *s) {
2925 return ACC_invalid;
2926 }
2927
2928 /// Null pointer constants can be casted however you please.
2929 ACCResult VisitExpr(Expr *e) {
2930 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2931 return ACC_bottom;
2932 return ACC_invalid;
2933 }
2934
2935 /// Objective-C string literals can be safely casted.
2936 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2937 // If we're casting to any retainable type, go ahead. Global
2938 // strings are immune to retains, so this is bottom.
2939 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2940
2941 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002942 }
2943
John McCalle4fe2452011-10-01 01:01:08 +00002944 /// Look through certain implicit and explicit casts.
2945 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002946 switch (e->getCastKind()) {
2947 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00002948 return ACC_bottom;
2949
John McCall31168b02011-06-15 23:02:42 +00002950 case CK_NoOp:
2951 case CK_LValueToRValue:
2952 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002953 case CK_CPointerToObjCPointerCast:
2954 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002955 case CK_AnyPointerToBlockPointerCast:
2956 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00002957
John McCall31168b02011-06-15 23:02:42 +00002958 default:
John McCalle4fe2452011-10-01 01:01:08 +00002959 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002960 }
2961 }
John McCalle4fe2452011-10-01 01:01:08 +00002962
2963 /// Look through unary extension.
2964 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002965 return Visit(e->getSubExpr());
2966 }
John McCalle4fe2452011-10-01 01:01:08 +00002967
2968 /// Ignore the LHS of a comma operator.
2969 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002970 return Visit(e->getRHS());
2971 }
John McCalle4fe2452011-10-01 01:01:08 +00002972
2973 /// Conditional operators are okay if both sides are okay.
2974 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2975 ACCResult left = Visit(e->getTrueExpr());
2976 if (left == ACC_invalid) return ACC_invalid;
2977 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00002978 }
John McCalle4fe2452011-10-01 01:01:08 +00002979
John McCallfe96e0b2011-11-06 09:01:30 +00002980 /// Look through pseudo-objects.
2981 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2982 // If we're getting here, we should always have a result.
2983 return Visit(e->getResultExpr());
2984 }
2985
John McCalle4fe2452011-10-01 01:01:08 +00002986 /// Statement expressions are okay if their result expression is okay.
2987 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002988 return Visit(e->getSubStmt()->body_back());
2989 }
John McCall31168b02011-06-15 23:02:42 +00002990
John McCalle4fe2452011-10-01 01:01:08 +00002991 /// Some declaration references are okay.
2992 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2993 // References to global constants from system headers are okay.
2994 // These are things like 'kCFStringTransformToLatin'. They are
2995 // can also be assumed to be immune to retains.
2996 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2997 if (isAnyRetainable(TargetClass) &&
2998 isAnyRetainable(SourceClass) &&
2999 var &&
3000 var->getStorageClass() == SC_Extern &&
3001 var->getType().isConstQualified() &&
3002 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
3003 return ACC_bottom;
3004 }
3005
3006 // Nothing else.
3007 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00003008 }
John McCalle4fe2452011-10-01 01:01:08 +00003009
3010 /// Some calls are okay.
3011 ACCResult VisitCallExpr(CallExpr *e) {
3012 if (FunctionDecl *fn = e->getDirectCallee())
3013 if (ACCResult result = checkCallToFunction(fn))
3014 return result;
3015
3016 return super::VisitCallExpr(e);
3017 }
3018
3019 ACCResult checkCallToFunction(FunctionDecl *fn) {
3020 // Require a CF*Ref return type.
Alp Toker314cc812014-01-25 16:55:45 +00003021 if (!isCFType(fn->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003022 return ACC_invalid;
3023
3024 if (!isAnyRetainable(TargetClass))
3025 return ACC_invalid;
3026
3027 // Honor an explicit 'not retained' attribute.
3028 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3029 return ACC_plusZero;
3030
3031 // Honor an explicit 'retained' attribute, except that for
3032 // now we're not going to permit implicit handling of +1 results,
3033 // because it's a bit frightening.
3034 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003035 return Diagnose ? ACC_plusOne
3036 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003037
3038 // Recognize this specific builtin function, which is used by CFSTR.
3039 unsigned builtinID = fn->getBuiltinID();
3040 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3041 return ACC_bottom;
3042
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003043 // Otherwise, don't do anything implicit with an unaudited function.
3044 if (!fn->hasAttr<CFAuditedTransferAttr>())
3045 return ACC_invalid;
3046
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003047 // Otherwise, it's +0 unless it follows the create convention.
3048 if (ento::coreFoundation::followsCreateRule(fn))
3049 return Diagnose ? ACC_plusOne
3050 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003051
John McCalle4fe2452011-10-01 01:01:08 +00003052 return ACC_plusZero;
3053 }
3054
3055 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3056 return checkCallToMethod(e->getMethodDecl());
3057 }
3058
3059 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3060 ObjCMethodDecl *method;
3061 if (e->isExplicitProperty())
3062 method = e->getExplicitProperty()->getGetterMethodDecl();
3063 else
3064 method = e->getImplicitPropertyGetter();
3065 return checkCallToMethod(method);
3066 }
3067
3068 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3069 if (!method) return ACC_invalid;
3070
3071 // Check for message sends to functions returning CF types. We
3072 // just obey the Cocoa conventions with these, even though the
3073 // return type is CF.
Alp Toker314cc812014-01-25 16:55:45 +00003074 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003075 return ACC_invalid;
3076
3077 // If the method is explicitly marked not-retained, it's +0.
3078 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3079 return ACC_plusZero;
3080
3081 // If the method is explicitly marked as returning retained, or its
3082 // selector follows a +1 Cocoa convention, treat it as +1.
3083 if (method->hasAttr<CFReturnsRetainedAttr>())
3084 return ACC_plusOne;
3085
3086 switch (method->getSelector().getMethodFamily()) {
3087 case OMF_alloc:
3088 case OMF_copy:
3089 case OMF_mutableCopy:
3090 case OMF_new:
3091 return ACC_plusOne;
3092
3093 default:
3094 // Otherwise, treat it as +0.
3095 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00003096 }
3097 }
John McCalle4fe2452011-10-01 01:01:08 +00003098 };
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00003099}
3100
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003101bool Sema::isKnownName(StringRef name) {
3102 if (name.empty())
3103 return false;
3104 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003105 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003106 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003107}
3108
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003109static void addFixitForObjCARCConversion(Sema &S,
3110 DiagnosticBuilder &DiagB,
3111 Sema::CheckedConversionKind CCK,
3112 SourceLocation afterLParen,
3113 QualType castType,
3114 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003115 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003116 const char *bridgeKeyword,
3117 const char *CFBridgeName) {
3118 // We handle C-style and implicit casts here.
3119 switch (CCK) {
3120 case Sema::CCK_ImplicitConversion:
3121 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003122 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003123 break;
3124 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003125 return;
3126 }
3127
3128 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003129 if (CCK == Sema::CCK_OtherCast) {
3130 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3131 SourceRange range(NCE->getOperatorLoc(),
3132 NCE->getAngleBrackets().getEnd());
3133 SmallString<32> BridgeCall;
3134
3135 SourceManager &SM = S.getSourceManager();
3136 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3137 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3138 BridgeCall += ' ';
3139
3140 BridgeCall += CFBridgeName;
3141 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3142 }
3143 return;
3144 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003145 Expr *castedE = castExpr;
3146 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3147 castedE = CCE->getSubExpr();
3148 castedE = castedE->IgnoreImpCasts();
3149 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00003150
3151 SmallString<32> BridgeCall;
3152
3153 SourceManager &SM = S.getSourceManager();
3154 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3155 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3156 BridgeCall += ' ';
3157
3158 BridgeCall += CFBridgeName;
3159
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003160 if (isa<ParenExpr>(castedE)) {
3161 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003162 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003163 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00003164 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003165 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003166 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003167 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3168 S.PP.getLocForEndOfToken(range.getEnd()),
3169 ")"));
3170 }
3171 return;
3172 }
3173
3174 if (CCK == Sema::CCK_CStyleCast) {
3175 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003176 } else if (CCK == Sema::CCK_OtherCast) {
3177 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3178 std::string castCode = "(";
3179 castCode += bridgeKeyword;
3180 castCode += castType.getAsString();
3181 castCode += ")";
3182 SourceRange Range(NCE->getOperatorLoc(),
3183 NCE->getAngleBrackets().getEnd());
3184 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3185 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003186 } else {
3187 std::string castCode = "(";
3188 castCode += bridgeKeyword;
3189 castCode += castType.getAsString();
3190 castCode += ")";
3191 Expr *castedE = castExpr->IgnoreImpCasts();
3192 SourceRange range = castedE->getSourceRange();
3193 if (isa<ParenExpr>(castedE)) {
3194 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3195 castCode));
3196 } else {
3197 castCode += "(";
3198 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3199 castCode));
3200 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3201 S.PP.getLocForEndOfToken(range.getEnd()),
3202 ")"));
3203 }
3204 }
3205}
3206
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003207template <typename T>
3208static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3209 TypedefNameDecl *TDNDecl = TD->getDecl();
3210 QualType QT = TDNDecl->getUnderlyingType();
3211 if (QT->isPointerType()) {
3212 QT = QT->getPointeeType();
3213 if (const RecordType *RT = QT->getAs<RecordType>())
Fariborz Jahanian9af6a782014-06-11 19:10:46 +00003214 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
Aaron Ballman2084f8f2013-12-19 13:20:36 +00003215 return RD->getAttr<T>();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003216 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003217 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003218}
3219
3220static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3221 TypedefNameDecl *&TDNDecl) {
3222 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3223 TDNDecl = TD->getDecl();
3224 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3225 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3226 return ObjCBAttr;
3227 T = TDNDecl->getUnderlyingType();
3228 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003229 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003230}
3231
John McCall4124c492011-10-17 18:40:02 +00003232static void
3233diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3234 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003235 Expr *castExpr, Expr *realCast,
3236 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003237 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003238 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003239 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00003240
John McCall4124c492011-10-17 18:40:02 +00003241 if (S.makeUnavailableInSystemHeader(loc,
John McCalle4fe2452011-10-01 01:01:08 +00003242 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCall31168b02011-06-15 23:02:42 +00003243 return;
John McCall4124c492011-10-17 18:40:02 +00003244
3245 QualType castExprType = castExpr->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003246 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003247 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3248 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3249 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
Fariborz Jahanian1ad83a32014-06-18 23:22:38 +00003250 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003251 return;
John McCall31168b02011-06-15 23:02:42 +00003252
John McCall640767f2011-06-17 06:50:50 +00003253 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003254 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003255 case ACTC_none:
3256 case ACTC_coreFoundation:
3257 case ACTC_voidPtr:
3258 srcKind = (castExprType->isPointerType() ? 1 : 0);
3259 break;
3260 case ACTC_retainable:
3261 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3262 break;
3263 case ACTC_indirectRetainable:
3264 srcKind = 4;
3265 break;
John McCall31168b02011-06-15 23:02:42 +00003266 }
3267
John McCall4124c492011-10-17 18:40:02 +00003268 // Check whether this could be fixed with a bridge cast.
3269 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3270 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003271
John McCall4124c492011-10-17 18:40:02 +00003272 // Bridge from an ARC type to a CF type.
3273 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003274
John McCall4124c492011-10-17 18:40:02 +00003275 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3276 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3277 << 2 // of C pointer type
3278 << castExprType
3279 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3280 << castType
3281 << castRange
3282 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003283 bool br = S.isKnownName("CFBridgingRelease");
Jordan Rose4502b532012-07-31 01:07:43 +00003284 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003285 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003286 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003287 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003288 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003289 DiagnosticBuilder DiagB =
3290 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3291 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Craig Topperc3ec1492014-05-26 06:22:03 +00003292
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003293 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003294 castType, castExpr, realCast, "__bridge ",
3295 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003296 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003297 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003298 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003299 DiagnosticBuilder DiagB =
3300 (CCK == Sema::CCK_OtherCast && !br) ?
3301 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3302 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3303 diag::note_arc_bridge_transfer)
3304 << castExprType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003305
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003306 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003307 castType, castExpr, realCast, "__bridge_transfer ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003308 br ? "CFBridgingRelease" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003309 }
John McCall4124c492011-10-17 18:40:02 +00003310
3311 return;
3312 }
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003313
John McCall4124c492011-10-17 18:40:02 +00003314 // Bridge from a CF type to an ARC type.
3315 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003316 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003317 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3318 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3319 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3320 << castExprType
3321 << 2 // to C pointer type
3322 << castType
3323 << castRange
3324 << castExpr->getSourceRange();
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003325 ACCResult CreateRule =
3326 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003327 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003328 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003329 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003330 DiagnosticBuilder DiagB =
3331 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3332 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003333 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003334 castType, castExpr, realCast, "__bridge ",
3335 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003336 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003337 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003338 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003339 DiagnosticBuilder DiagB =
3340 (CCK == Sema::CCK_OtherCast && !br) ?
3341 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3342 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3343 diag::note_arc_bridge_retained)
3344 << castType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003345
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003346 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003347 castType, castExpr, realCast, "__bridge_retained ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003348 br ? "CFBridgingRetain" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003349 }
John McCall4124c492011-10-17 18:40:02 +00003350
3351 return;
John McCall31168b02011-06-15 23:02:42 +00003352 }
3353
John McCall4124c492011-10-17 18:40:02 +00003354 S.Diag(loc, diag::err_arc_mismatched_cast)
3355 << (CCK != Sema::CCK_ImplicitConversion)
3356 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003357 << castRange << castExpr->getSourceRange();
3358}
3359
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003360template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003361static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3362 bool &HadTheAttribute, bool warn) {
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003363 QualType T = castExpr->getType();
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003364 HadTheAttribute = false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003365 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3366 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003367 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003368 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003369 HadTheAttribute = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003370 NamedDecl *Target = nullptr;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003371 // Check for an existing type with this name.
3372 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3373 Sema::LookupOrdinaryName);
3374 if (S.LookupName(R, S.TUScope)) {
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003375 Target = R.getFoundDecl();
3376 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3377 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3378 if (const ObjCObjectPointerType *InterfacePointerType =
3379 castType->getAsObjCInterfacePointerType()) {
3380 ObjCInterfaceDecl *CastClass
3381 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003382 if ((CastClass == ExprClass) ||
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003383 (CastClass && ExprClass->isSuperClassOf(CastClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003384 return true;
3385 if (warn)
3386 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3387 << T << Target->getName() << castType->getPointeeType();
3388 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003389 } else if (castType->isObjCIdType() ||
3390 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3391 castType, ExprClass)))
3392 // ok to cast to 'id'.
3393 // casting to id<p-list> is ok if bridge type adopts all of
3394 // p-list protocols.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003395 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003396 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003397 if (warn) {
3398 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3399 << T << Target->getName() << castType;
3400 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3401 S.Diag(Target->getLocStart(), diag::note_declared_at);
3402 }
3403 return false;
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003404 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003405 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003406 }
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003407 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
Aaron Ballmanc0550742014-01-03 02:07:43 +00003408 << castExpr->getType() << Parm;
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003409 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3410 if (Target)
3411 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003412 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003413 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003414 return false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003415 }
3416 T = TDNDecl->getUnderlyingType();
3417 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003418 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003419}
3420
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003421template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003422static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3423 bool &HadTheAttribute, bool warn) {
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003424 QualType T = castType;
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003425 HadTheAttribute = false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003426 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3427 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003428 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003429 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003430 HadTheAttribute = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003431 NamedDecl *Target = nullptr;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003432 // Check for an existing type with this name.
3433 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3434 Sema::LookupOrdinaryName);
3435 if (S.LookupName(R, S.TUScope)) {
3436 Target = R.getFoundDecl();
3437 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3438 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3439 if (const ObjCObjectPointerType *InterfacePointerType =
3440 castExpr->getType()->getAsObjCInterfacePointerType()) {
3441 ObjCInterfaceDecl *ExprClass
3442 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003443 if ((CastClass == ExprClass) ||
3444 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003445 return true;
3446 if (warn) {
3447 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3448 << castExpr->getType()->getPointeeType() << T;
3449 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3450 }
3451 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003452 } else if (castExpr->getType()->isObjCIdType() ||
3453 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3454 castExpr->getType(), CastClass)))
3455 // ok to cast an 'id' expression to a CFtype.
3456 // ok to cast an 'id<plist>' expression to CFtype provided plist
3457 // adopts all of CFtype's ObjetiveC's class plist.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003458 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003459 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003460 if (warn) {
3461 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3462 << castExpr->getType() << castType;
3463 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3464 S.Diag(Target->getLocStart(), diag::note_declared_at);
3465 }
3466 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003467 }
3468 }
3469 }
3470 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3471 << castExpr->getType() << castType;
3472 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3473 if (Target)
3474 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003475 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003476 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003477 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003478 }
3479 T = TDNDecl->getUnderlyingType();
3480 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003481 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003482}
3483
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003484void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003485 if (!getLangOpts().ObjC1)
3486 return;
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003487 // warn in presence of __bridge casting to or from a toll free bridge cast.
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003488 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3489 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003490 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003491 bool HasObjCBridgeAttr;
3492 bool ObjCBridgeAttrWillNotWarn =
3493 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3494 false);
3495 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3496 return;
3497 bool HasObjCBridgeMutableAttr;
3498 bool ObjCBridgeMutableAttrWillNotWarn =
3499 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3500 HasObjCBridgeMutableAttr, false);
3501 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3502 return;
3503
3504 if (HasObjCBridgeAttr)
3505 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3506 true);
3507 else if (HasObjCBridgeMutableAttr)
3508 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3509 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003510 }
3511 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003512 bool HasObjCBridgeAttr;
3513 bool ObjCBridgeAttrWillNotWarn =
3514 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3515 false);
3516 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3517 return;
3518 bool HasObjCBridgeMutableAttr;
3519 bool ObjCBridgeMutableAttrWillNotWarn =
3520 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3521 HasObjCBridgeMutableAttr, false);
3522 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3523 return;
3524
3525 if (HasObjCBridgeAttr)
3526 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3527 true);
3528 else if (HasObjCBridgeMutableAttr)
3529 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3530 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003531 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003532}
3533
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003534void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3535 QualType SrcType = castExpr->getType();
3536 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3537 if (PRE->isExplicitProperty()) {
3538 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3539 SrcType = PDecl->getType();
3540 }
3541 else if (PRE->isImplicitProperty()) {
3542 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3543 SrcType = Getter->getReturnType();
3544
3545 }
3546 }
3547
3548 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3549 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3550 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3551 return;
3552 CheckObjCBridgeRelatedConversions(castExpr->getLocStart(),
3553 castType, SrcType, castExpr);
3554 return;
3555}
3556
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00003557bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3558 CastKind &Kind) {
3559 if (!getLangOpts().ObjC1)
3560 return false;
3561 ARCConversionTypeClass exprACTC =
3562 classifyTypeForARCConversion(castExpr->getType());
3563 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3564 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3565 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3566 CheckTollFreeBridgeCast(castType, castExpr);
3567 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3568 : CK_CPointerToObjCPointerCast;
3569 return true;
3570 }
3571 return false;
3572}
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003573
3574bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3575 QualType DestType, QualType SrcType,
3576 ObjCInterfaceDecl *&RelatedClass,
3577 ObjCMethodDecl *&ClassMethod,
3578 ObjCMethodDecl *&InstanceMethod,
3579 TypedefNameDecl *&TDNDecl,
3580 bool CfToNs) {
3581 QualType T = CfToNs ? SrcType : DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003582 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3583 if (!ObjCBAttr)
3584 return false;
3585
3586 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3587 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3588 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3589 if (!RCId)
3590 return false;
Craig Topperc3ec1492014-05-26 06:22:03 +00003591 NamedDecl *Target = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003592 // Check for an existing type with this name.
3593 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3594 Sema::LookupOrdinaryName);
3595 if (!LookupName(R, TUScope)) {
3596 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003597 << SrcType << DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003598 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3599 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003600 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003601 Target = R.getFoundDecl();
3602 if (Target && isa<ObjCInterfaceDecl>(Target))
3603 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3604 else {
3605 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3606 << SrcType << DestType;
3607 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3608 if (Target)
3609 Diag(Target->getLocStart(), diag::note_declared_at);
3610 return false;
3611 }
3612
3613 // Check for an existing class method with the given selector name.
3614 if (CfToNs && CMId) {
3615 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3616 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3617 if (!ClassMethod) {
3618 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003619 << SrcType << DestType << Sel << false;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003620 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3621 return false;
3622 }
3623 }
3624
3625 // Check for an existing instance method with the given selector name.
3626 if (!CfToNs && IMId) {
3627 Selector Sel = Context.Selectors.getNullarySelector(IMId);
3628 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3629 if (!InstanceMethod) {
3630 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003631 << SrcType << DestType << Sel << true;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003632 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3633 return false;
3634 }
3635 }
3636 return true;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003637}
3638
3639bool
3640Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003641 QualType DestType, QualType SrcType,
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003642 Expr *&SrcExpr) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003643 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3644 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3645 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3646 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3647 if (!CfToNs && !NsToCf)
3648 return false;
3649
3650 ObjCInterfaceDecl *RelatedClass;
Craig Topperc3ec1492014-05-26 06:22:03 +00003651 ObjCMethodDecl *ClassMethod = nullptr;
3652 ObjCMethodDecl *InstanceMethod = nullptr;
3653 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003654 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
3655 ClassMethod, InstanceMethod, TDNDecl, CfToNs))
3656 return false;
3657
3658 if (CfToNs) {
3659 // Implicit conversion from CF to ObjC object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003660 if (ClassMethod) {
3661 std::string ExpressionString = "[";
3662 ExpressionString += RelatedClass->getNameAsString();
3663 ExpressionString += " ";
3664 ExpressionString += ClassMethod->getSelector().getAsString();
3665 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3666 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003667 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003668 << SrcType << DestType << ClassMethod->getSelector() << false
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003669 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3670 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003671 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3672 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3673
3674 QualType receiverType =
3675 Context.getObjCInterfaceType(RelatedClass);
3676 // Argument.
3677 Expr *args[] = { SrcExpr };
3678 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
3679 ClassMethod->getLocation(),
3680 ClassMethod->getSelector(), ClassMethod,
3681 MultiExprArg(args, 1));
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003682 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003683 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003684 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003685 }
3686 else {
3687 // Implicit conversion from ObjC type to CF object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003688 if (InstanceMethod) {
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003689 std::string ExpressionString;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003690 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003691 if (InstanceMethod->isPropertyAccessor())
3692 if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
3693 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
3694 ExpressionString = ".";
3695 ExpressionString += PDecl->getNameAsString();
3696 Diag(Loc, diag::err_objc_bridged_related_known_method)
3697 << SrcType << DestType << InstanceMethod->getSelector() << true
3698 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3699 }
3700 if (ExpressionString.empty()) {
3701 // Provide a fixit: [ObjectExpr InstanceMethod]
3702 ExpressionString = " ";
3703 ExpressionString += InstanceMethod->getSelector().getAsString();
3704 ExpressionString += "]";
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003705
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003706 Diag(Loc, diag::err_objc_bridged_related_known_method)
3707 << SrcType << DestType << InstanceMethod->getSelector() << true
3708 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3709 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3710 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003711 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3712 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3713
3714 ExprResult msg =
3715 BuildInstanceMessageImplicit(SrcExpr, SrcType,
3716 InstanceMethod->getLocation(),
3717 InstanceMethod->getSelector(),
3718 InstanceMethod, None);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003719 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003720 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003721 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003722 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003723 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003724}
3725
John McCall4124c492011-10-17 18:40:02 +00003726Sema::ARCConversionResult
3727Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003728 Expr *&castExpr, CheckedConversionKind CCK,
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00003729 bool DiagnoseCFAudited,
3730 BinaryOperatorKind Opc) {
John McCall4124c492011-10-17 18:40:02 +00003731 QualType castExprType = castExpr->getType();
3732
3733 // For the purposes of the classification, we assume reference types
3734 // will bind to temporaries.
3735 QualType effCastType = castType;
3736 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3737 effCastType = ref->getPointeeType();
3738
3739 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3740 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003741 if (exprACTC == castACTC) {
3742 // check for viablity and report error if casting an rvalue to a
3743 // life-time qualifier.
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003744 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003745 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003746 (castType != castExprType)) {
3747 const Type *DT = castType.getTypePtr();
3748 QualType QDT = castType;
3749 // We desugar some types but not others. We ignore those
3750 // that cannot happen in a cast; i.e. auto, and those which
3751 // should not be de-sugared; i.e typedef.
3752 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3753 QDT = PT->desugar();
3754 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3755 QDT = TP->desugar();
3756 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3757 QDT = AT->desugar();
3758 if (QDT != castType &&
3759 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3760 SourceLocation loc =
3761 (castRange.isValid() ? castRange.getBegin()
3762 : castExpr->getExprLoc());
3763 Diag(loc, diag::err_arc_nolifetime_behavior);
3764 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003765 }
3766 return ACR_okay;
3767 }
3768
John McCall4124c492011-10-17 18:40:02 +00003769 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
3770
3771 // Allow all of these types to be cast to integer types (but not
3772 // vice-versa).
3773 if (castACTC == ACTC_none && castType->isIntegralType(Context))
3774 return ACR_okay;
3775
3776 // Allow casts between pointers to lifetime types (e.g., __strong id*)
3777 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
3778 // must be explicit.
3779 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
3780 return ACR_okay;
3781 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
3782 CCK != CCK_ImplicitConversion)
3783 return ACR_okay;
3784
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003785 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00003786 // For invalid casts, fall through.
3787 case ACC_invalid:
3788 break;
3789
3790 // Do nothing for both bottom and +0.
3791 case ACC_bottom:
3792 case ACC_plusZero:
3793 return ACR_okay;
3794
3795 // If the result is +1, consume it here.
3796 case ACC_plusOne:
3797 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3798 CK_ARCConsumeObject, castExpr,
Craig Topperc3ec1492014-05-26 06:22:03 +00003799 nullptr, VK_RValue);
John McCall4124c492011-10-17 18:40:02 +00003800 ExprNeedsCleanups = true;
3801 return ACR_okay;
3802 }
3803
3804 // If this is a non-implicit cast from id or block type to a
3805 // CoreFoundation type, delay complaining in case the cast is used
3806 // in an acceptable context.
3807 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3808 CCK != CCK_ImplicitConversion)
3809 return ACR_unbridged;
3810
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003811 // Do not issue bridge cast" diagnostic when implicit casting a cstring
3812 // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
3813 // suitable fix-it.
Fariborz Jahanian283bf892013-12-18 21:04:43 +00003814 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
3815 ConversionToObjCStringLiteralCheck(castType, castExpr))
3816 return ACR_okay;
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003817
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003818 // Do not issue "bridge cast" diagnostic when implicit casting
3819 // a retainable object to a CF type parameter belonging to an audited
3820 // CF API function. Let caller issue a normal type mismatched diagnostic
3821 // instead.
3822 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
3823 castACTC != ACTC_coreFoundation)
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00003824 if (!(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
3825 (Opc == BO_NE || Opc == BO_EQ)))
3826 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3827 castExpr, castExpr, exprACTC, CCK);
John McCall4124c492011-10-17 18:40:02 +00003828 return ACR_okay;
3829}
3830
3831/// Given that we saw an expression with the ARCUnbridgedCastTy
3832/// placeholder type, complain bitterly.
3833void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3834 // We expect the spurious ImplicitCastExpr to already have been stripped.
3835 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3836 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3837
3838 SourceRange castRange;
3839 QualType castType;
3840 CheckedConversionKind CCK;
3841
3842 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3843 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3844 castType = cast->getTypeAsWritten();
3845 CCK = CCK_CStyleCast;
3846 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3847 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3848 castType = cast->getTypeAsWritten();
3849 CCK = CCK_OtherCast;
3850 } else {
3851 castType = cast->getType();
3852 CCK = CCK_ImplicitConversion;
3853 }
3854
3855 ARCConversionTypeClass castACTC =
3856 classifyTypeForARCConversion(castType.getNonReferenceType());
3857
3858 Expr *castExpr = realCast->getSubExpr();
3859 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3860
3861 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003862 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00003863}
3864
3865/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3866/// type, remove the placeholder cast.
3867Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3868 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3869
3870 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3871 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3872 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3873 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3874 assert(uo->getOpcode() == UO_Extension);
3875 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3876 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3877 sub->getValueKind(), sub->getObjectKind(),
3878 uo->getOperatorLoc());
3879 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3880 assert(!gse->isResultDependent());
3881
3882 unsigned n = gse->getNumAssocs();
3883 SmallVector<Expr*, 4> subExprs(n);
3884 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3885 for (unsigned i = 0; i != n; ++i) {
3886 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3887 Expr *sub = gse->getAssocExpr(i);
3888 if (i == gse->getResultIndex())
3889 sub = stripARCUnbridgedCast(sub);
3890 subExprs[i] = sub;
3891 }
3892
3893 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3894 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003895 subTypes, subExprs,
3896 gse->getDefaultLoc(),
John McCall4124c492011-10-17 18:40:02 +00003897 gse->getRParenLoc(),
3898 gse->containsUnexpandedParameterPack(),
3899 gse->getResultIndex());
3900 } else {
3901 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3902 return cast<ImplicitCastExpr>(e)->getSubExpr();
3903 }
3904}
3905
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003906bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3907 QualType exprType) {
3908 QualType canCastType =
3909 Context.getCanonicalType(castType).getUnqualifiedType();
3910 QualType canExprType =
3911 Context.getCanonicalType(exprType).getUnqualifiedType();
3912 if (isa<ObjCObjectPointerType>(canCastType) &&
3913 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3914 canExprType->isObjCObjectPointerType()) {
3915 if (const ObjCObjectPointerType *ObjT =
3916 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00003917 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
3918 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003919 }
3920 return true;
3921}
3922
John McCall4db5c3c2011-07-07 06:58:02 +00003923/// Look for an ObjCReclaimReturnedObject cast and destroy it.
3924static Expr *maybeUndoReclaimObject(Expr *e) {
3925 // For now, we just undo operands that are *immediately* reclaim
3926 // expressions, which prevents the vast majority of potential
3927 // problems here. To catch them all, we'd need to rebuild arbitrary
3928 // value-propagating subexpressions --- we can't reliably rebuild
3929 // in-place because of expression sharing.
3930 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall2d637d22011-09-10 06:18:15 +00003931 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall4db5c3c2011-07-07 06:58:02 +00003932 return ice->getSubExpr();
3933
3934 return e;
3935}
3936
John McCall31168b02011-06-15 23:02:42 +00003937ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3938 ObjCBridgeCastKind Kind,
3939 SourceLocation BridgeKeywordLoc,
3940 TypeSourceInfo *TSInfo,
3941 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00003942 ExprResult SubResult = UsualUnaryConversions(SubExpr);
3943 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003944 SubExpr = SubResult.get();
John McCalleb075542011-08-26 00:48:42 +00003945
John McCall31168b02011-06-15 23:02:42 +00003946 QualType T = TSInfo->getType();
3947 QualType FromType = SubExpr->getType();
3948
John McCall9320b872011-09-09 05:25:32 +00003949 CastKind CK;
3950
John McCall31168b02011-06-15 23:02:42 +00003951 bool MustConsume = false;
3952 if (T->isDependentType() || SubExpr->isTypeDependent()) {
3953 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00003954 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00003955 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3956 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00003957 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3958 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00003959 switch (Kind) {
3960 case OBC_Bridge:
3961 break;
3962
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003963 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003964 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00003965 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3966 << 2
3967 << FromType
3968 << (T->isBlockPointerType()? 1 : 0)
3969 << T
3970 << SubExpr->getSourceRange()
3971 << Kind;
3972 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3973 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3974 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003975 << FromType << br
John McCall31168b02011-06-15 23:02:42 +00003976 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003977 br ? "CFBridgingRelease "
3978 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00003979
3980 Kind = OBC_Bridge;
3981 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003982 }
John McCall31168b02011-06-15 23:02:42 +00003983
3984 case OBC_BridgeTransfer:
3985 // We must consume the Objective-C object produced by the cast.
3986 MustConsume = true;
3987 break;
3988 }
3989 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3990 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00003991 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00003992 switch (Kind) {
3993 case OBC_Bridge:
John McCall4db5c3c2011-07-07 06:58:02 +00003994 // Reclaiming a value that's going to be __bridge-casted to CF
3995 // is very dangerous, so we don't do it.
3996 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCall31168b02011-06-15 23:02:42 +00003997 break;
3998
3999 case OBC_BridgeRetained:
4000 // Produce the object before casting it.
4001 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00004002 CK_ARCProduceObject,
Craig Topperc3ec1492014-05-26 06:22:03 +00004003 SubExpr, nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004004 break;
4005
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004006 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00004007 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00004008 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4009 << (FromType->isBlockPointerType()? 1 : 0)
4010 << FromType
4011 << 2
4012 << T
4013 << SubExpr->getSourceRange()
4014 << Kind;
4015
4016 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4017 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4018 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004019 << T << br
4020 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4021 br ? "CFBridgingRetain " : "__bridge_retained");
John McCall31168b02011-06-15 23:02:42 +00004022
4023 Kind = OBC_Bridge;
4024 break;
4025 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004026 }
John McCall31168b02011-06-15 23:02:42 +00004027 } else {
4028 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4029 << FromType << T << Kind
4030 << SubExpr->getSourceRange()
4031 << TSInfo->getTypeLoc().getSourceRange();
4032 return ExprError();
4033 }
4034
John McCall9320b872011-09-09 05:25:32 +00004035 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00004036 BridgeKeywordLoc,
4037 TSInfo, SubExpr);
4038
4039 if (MustConsume) {
4040 ExprNeedsCleanups = true;
John McCall2d637d22011-09-10 06:18:15 +00004041 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
Craig Topperc3ec1492014-05-26 06:22:03 +00004042 nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004043 }
4044
4045 return Result;
4046}
4047
4048ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4049 SourceLocation LParenLoc,
4050 ObjCBridgeCastKind Kind,
4051 SourceLocation BridgeKeywordLoc,
4052 ParsedType Type,
4053 SourceLocation RParenLoc,
4054 Expr *SubExpr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004055 TypeSourceInfo *TSInfo = nullptr;
John McCall31168b02011-06-15 23:02:42 +00004056 QualType T = GetTypeFromParser(Type, &TSInfo);
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00004057 if (Kind == OBC_Bridge)
4058 CheckTollFreeBridgeCast(T, SubExpr);
John McCall31168b02011-06-15 23:02:42 +00004059 if (!TSInfo)
4060 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4061 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
4062 SubExpr);
4063}