blob: 84167fef3f7e54325c293bf3168fe190928877d3 [file] [log] [blame]
Chris Lattner85a932e2008-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 McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
John McCall5f1e0942010-08-24 08:50:51 +000016#include "clang/Sema/Scope.h"
John McCall26743b22011-02-03 09:00:02 +000017#include "clang/Sema/ScopeInfo.h"
Douglas Gregore737f502010-08-12 20:07:10 +000018#include "clang/Sema/Initialization.h"
John McCall2cf031d2011-10-01 01:01:08 +000019#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Chris Lattner85a932e2008-01-04 22:32:30 +000020#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclObjC.h"
Steve Narofff494b572008-05-29 21:12:08 +000022#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000023#include "clang/AST/StmtVisitor.h"
Douglas Gregor2725ca82010-04-21 19:57:20 +000024#include "clang/AST/TypeLoc.h"
Chris Lattner39c28bb2009-02-18 06:48:40 +000025#include "llvm/ADT/SmallString.h"
Steve Naroff61f72cb2009-03-09 21:12:44 +000026#include "clang/Lex/Preprocessor.h"
27
Chris Lattner85a932e2008-01-04 22:32:30 +000028using namespace clang;
John McCall26743b22011-02-03 09:00:02 +000029using namespace sema;
Chris Lattner85a932e2008-01-04 22:32:30 +000030
John McCallf312b1e2010-08-26 23:41:50 +000031ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
32 Expr **strings,
33 unsigned NumStrings) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000034 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
35
Chris Lattnerf4b136f2009-02-18 06:13:04 +000036 // Most ObjC strings are formed out of a single piece. However, we *can*
37 // have strings formed out of multiple @ strings with multiple pptokens in
38 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
39 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner39c28bb2009-02-18 06:48:40 +000040 StringLiteral *S = Strings[0];
Mike Stump1eb44332009-09-09 15:08:12 +000041
Chris Lattnerf4b136f2009-02-18 06:13:04 +000042 // If we have a multi-part string, merge it all together.
43 if (NumStrings != 1) {
Chris Lattner85a932e2008-01-04 22:32:30 +000044 // Concatenate objc strings.
Chris Lattner39c28bb2009-02-18 06:48:40 +000045 llvm::SmallString<128> StrBuf;
Chris Lattner5f9e2722011-07-23 10:55:15 +000046 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump1eb44332009-09-09 15:08:12 +000047
Chris Lattner726e1682009-02-18 05:49:11 +000048 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000049 S = Strings[i];
Mike Stump1eb44332009-09-09 15:08:12 +000050
Douglas Gregor5cee1192011-07-27 05:40:30 +000051 // ObjC strings can't be wide or UTF.
52 if (!S->isAscii()) {
Chris Lattnerf4b136f2009-02-18 06:13:04 +000053 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
54 << S->getSourceRange();
55 return true;
56 }
Mike Stump1eb44332009-09-09 15:08:12 +000057
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +000058 // Append the string.
59 StrBuf += S->getString();
Mike Stump1eb44332009-09-09 15:08:12 +000060
Chris Lattner39c28bb2009-02-18 06:48:40 +000061 // Get the locations of the string tokens.
62 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattner85a932e2008-01-04 22:32:30 +000063 }
Mike Stump1eb44332009-09-09 15:08:12 +000064
Chris Lattner39c28bb2009-02-18 06:48:40 +000065 // Create the aggregate string with the appropriate content and location
66 // information.
Jay Foad65aa6882011-06-21 15:13:30 +000067 S = StringLiteral::Create(Context, StrBuf,
Douglas Gregor5cee1192011-07-27 05:40:30 +000068 StringLiteral::Ascii, /*Pascal=*/false,
Chris Lattner2085fd62009-02-18 06:40:38 +000069 Context.getPointerType(Context.CharTy),
Chris Lattner39c28bb2009-02-18 06:48:40 +000070 &StrLocs[0], StrLocs.size());
Chris Lattner85a932e2008-01-04 22:32:30 +000071 }
Mike Stump1eb44332009-09-09 15:08:12 +000072
Chris Lattner69039812009-02-18 06:01:06 +000073 // Verify that this composite string is acceptable for ObjC strings.
74 if (CheckObjCString(S))
Chris Lattner85a932e2008-01-04 22:32:30 +000075 return true;
Chris Lattnera0af1fe2009-02-18 06:06:56 +000076
77 // Initialize the constant string interface lazily. This assumes
Steve Naroffd9fd7642009-04-07 14:18:33 +000078 // the NSString interface is seen in this translation unit. Note: We
79 // don't use NSConstantString, since the runtime team considers this
80 // interface private (even though it appears in the header files).
Chris Lattnera0af1fe2009-02-18 06:06:56 +000081 QualType Ty = Context.getObjCConstantStringInterface();
82 if (!Ty.isNull()) {
Steve Naroff14108da2009-07-10 23:34:53 +000083 Ty = Context.getObjCObjectPointerType(Ty);
Fariborz Jahanian8a437762010-04-23 23:19:04 +000084 } else if (getLangOptions().NoConstantCFStrings) {
Fariborz Jahanian4c733072010-10-19 17:19:29 +000085 IdentifierInfo *NSIdent=0;
86 std::string StringClass(getLangOptions().ObjCConstantStringClass);
87
88 if (StringClass.empty())
89 NSIdent = &Context.Idents.get("NSConstantString");
90 else
91 NSIdent = &Context.Idents.get(StringClass);
92
Fariborz Jahanian8a437762010-04-23 23:19:04 +000093 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
94 LookupOrdinaryName);
95 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
96 Context.setObjCConstantStringInterface(StrIF);
97 Ty = Context.getObjCConstantStringInterface();
98 Ty = Context.getObjCObjectPointerType(Ty);
99 } else {
100 // If there is no NSConstantString interface defined then treat this
101 // as error and recover from it.
102 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
103 << S->getSourceRange();
104 Ty = Context.getObjCIdType();
105 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000106 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000107 IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
Douglas Gregorc83c6872010-04-15 22:33:43 +0000108 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
109 LookupOrdinaryName);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000110 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
111 Context.setObjCConstantStringInterface(StrIF);
112 Ty = Context.getObjCConstantStringInterface();
Steve Naroff14108da2009-07-10 23:34:53 +0000113 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000114 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000115 // If there is no NSString interface defined then treat constant
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000116 // strings as untyped objects and let the runtime figure it out later.
117 Ty = Context.getObjCIdType();
118 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000119 }
Mike Stump1eb44332009-09-09 15:08:12 +0000120
Chris Lattnerf4b136f2009-02-18 06:13:04 +0000121 return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
Chris Lattner85a932e2008-01-04 22:32:30 +0000122}
123
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000124ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregor81d34662010-04-20 15:39:42 +0000125 TypeSourceInfo *EncodedTypeInfo,
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000126 SourceLocation RParenLoc) {
Douglas Gregor81d34662010-04-20 15:39:42 +0000127 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000128 QualType StrTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000129 if (EncodedType->isDependentType())
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000130 StrTy = Context.DependentTy;
131 else {
Fariborz Jahanian6c916152011-06-16 22:34:44 +0000132 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
133 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000134 if (RequireCompleteType(AtLoc, EncodedType,
135 PDiag(diag::err_incomplete_type_objc_at_encode)
136 << EncodedTypeInfo->getTypeLoc().getSourceRange()))
137 return ExprError();
138
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000139 std::string Str;
140 Context.getObjCEncodingForType(EncodedType, Str);
141
142 // The type of @encode is the same as the type of the corresponding string,
143 // which is an array type.
144 StrTy = Context.CharTy;
145 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
John McCall4b7a8342010-03-15 10:54:44 +0000146 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000147 StrTy.addConst();
148 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
149 ArrayType::Normal, 0);
150 }
Mike Stump1eb44332009-09-09 15:08:12 +0000151
Douglas Gregor81d34662010-04-20 15:39:42 +0000152 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000153}
154
John McCallf312b1e2010-08-26 23:41:50 +0000155ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
156 SourceLocation EncodeLoc,
157 SourceLocation LParenLoc,
158 ParsedType ty,
159 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000160 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000161 TypeSourceInfo *TInfo;
162 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
163 if (!TInfo)
164 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
165 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000166
Douglas Gregor81d34662010-04-20 15:39:42 +0000167 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000168}
169
John McCallf312b1e2010-08-26 23:41:50 +0000170ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
171 SourceLocation AtLoc,
172 SourceLocation SelLoc,
173 SourceLocation LParenLoc,
174 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000175 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000176 SourceRange(LParenLoc, RParenLoc), false, false);
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +0000177 if (!Method)
178 Method = LookupFactoryMethodInGlobalPool(Sel,
179 SourceRange(LParenLoc, RParenLoc));
180 if (!Method)
181 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian4c91d892011-07-13 19:05:43 +0000182
183 if (!Method ||
184 Method->getImplementationControl() != ObjCMethodDecl::Optional) {
185 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
186 = ReferencedSelectors.find(Sel);
187 if (Pos == ReferencedSelectors.end())
188 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
189 }
Fariborz Jahanian3fe10412010-07-22 18:24:20 +0000190
John McCallf85e1932011-06-15 23:02:42 +0000191 // In ARC, forbid the user from using @selector for
192 // retain/release/autorelease/dealloc/retainCount.
193 if (getLangOptions().ObjCAutoRefCount) {
194 switch (Sel.getMethodFamily()) {
195 case OMF_retain:
196 case OMF_release:
197 case OMF_autorelease:
198 case OMF_retainCount:
199 case OMF_dealloc:
200 Diag(AtLoc, diag::err_arc_illegal_selector) <<
201 Sel << SourceRange(LParenLoc, RParenLoc);
202 break;
203
204 case OMF_None:
205 case OMF_alloc:
206 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +0000207 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +0000208 case OMF_init:
209 case OMF_mutableCopy:
210 case OMF_new:
211 case OMF_self:
Fariborz Jahanian9670e172011-07-05 22:38:59 +0000212 case OMF_performSelector:
John McCallf85e1932011-06-15 23:02:42 +0000213 break;
214 }
215 }
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000216 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000217 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000218}
219
John McCallf312b1e2010-08-26 23:41:50 +0000220ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
221 SourceLocation AtLoc,
222 SourceLocation ProtoLoc,
223 SourceLocation LParenLoc,
224 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000225 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000226 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000227 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000228 return true;
229 }
Mike Stump1eb44332009-09-09 15:08:12 +0000230
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000231 QualType Ty = Context.getObjCProtoType();
232 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000233 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000234 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000235 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000236}
237
John McCall26743b22011-02-03 09:00:02 +0000238/// Try to capture an implicit reference to 'self'.
239ObjCMethodDecl *Sema::tryCaptureObjCSelf() {
240 // Ignore block scopes: we can capture through them.
241 DeclContext *DC = CurContext;
242 while (true) {
243 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
244 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
245 else break;
246 }
247
248 // If we're not in an ObjC method, error out. Note that, unlike the
249 // C++ case, we don't require an instance method --- class methods
250 // still have a 'self', and we really do still need to capture it!
251 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
252 if (!method)
253 return 0;
254
255 ImplicitParamDecl *self = method->getSelfDecl();
256 assert(self && "capturing 'self' in non-definition?");
257
258 // Mark that we're closing on 'this' in all the block scopes, if applicable.
259 for (unsigned idx = FunctionScopes.size() - 1;
260 isa<BlockScopeInfo>(FunctionScopes[idx]);
John McCall6b5a61b2011-02-07 10:33:21 +0000261 --idx) {
262 BlockScopeInfo *blockScope = cast<BlockScopeInfo>(FunctionScopes[idx]);
263 unsigned &captureIndex = blockScope->CaptureMap[self];
264 if (captureIndex) break;
265
266 bool nested = isa<BlockScopeInfo>(FunctionScopes[idx-1]);
267 blockScope->Captures.push_back(
268 BlockDecl::Capture(self, /*byref*/ false, nested, /*copy*/ 0));
269 captureIndex = blockScope->Captures.size(); // +1
270 }
John McCall26743b22011-02-03 09:00:02 +0000271
272 return method;
273}
274
Douglas Gregor5c16d632011-09-09 20:05:21 +0000275static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
276 if (T == Context.getObjCInstanceType())
277 return Context.getObjCIdType();
278
279 return T;
280}
281
Douglas Gregor926df6c2011-06-11 01:09:30 +0000282QualType Sema::getMessageSendResultType(QualType ReceiverType,
283 ObjCMethodDecl *Method,
284 bool isClassMessage, bool isSuperMessage) {
285 assert(Method && "Must have a method");
286 if (!Method->hasRelatedResultType())
287 return Method->getSendResultType();
288
289 // If a method has a related return type:
290 // - if the method found is an instance method, but the message send
291 // was a class message send, T is the declared return type of the method
292 // found
293 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor5c16d632011-09-09 20:05:21 +0000294 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000295
296 // - if the receiver is super, T is a pointer to the class of the
297 // enclosing method definition
298 if (isSuperMessage) {
299 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
300 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
301 return Context.getObjCObjectPointerType(
302 Context.getObjCInterfaceType(Class));
303 }
304
305 // - if the receiver is the name of a class U, T is a pointer to U
306 if (ReceiverType->getAs<ObjCInterfaceType>() ||
307 ReceiverType->isObjCQualifiedInterfaceType())
308 return Context.getObjCObjectPointerType(ReceiverType);
309 // - if the receiver is of type Class or qualified Class type,
310 // T is the declared return type of the method.
311 if (ReceiverType->isObjCClassType() ||
312 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor5c16d632011-09-09 20:05:21 +0000313 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000314
315 // - if the receiver is id, qualified id, Class, or qualified Class, T
316 // is the receiver type, otherwise
317 // - T is the type of the receiver expression.
318 return ReceiverType;
319}
John McCall26743b22011-02-03 09:00:02 +0000320
Douglas Gregor926df6c2011-06-11 01:09:30 +0000321void Sema::EmitRelatedResultTypeNote(const Expr *E) {
322 E = E->IgnoreParenImpCasts();
323 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
324 if (!MsgSend)
325 return;
326
327 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
328 if (!Method)
329 return;
330
331 if (!Method->hasRelatedResultType())
332 return;
333
334 if (Context.hasSameUnqualifiedType(Method->getResultType()
335 .getNonReferenceType(),
336 MsgSend->getType()))
337 return;
338
Douglas Gregore97179c2011-09-08 01:46:34 +0000339 if (!Context.hasSameUnqualifiedType(Method->getResultType(),
340 Context.getObjCInstanceType()))
341 return;
342
Douglas Gregor926df6c2011-06-11 01:09:30 +0000343 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
344 << Method->isInstanceMethod() << Method->getSelector()
345 << MsgSend->getType();
346}
347
348bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
349 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000350 Selector Sel, ObjCMethodDecl *Method,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000351 bool isClassMessage, bool isSuperMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000352 SourceLocation lbrac, SourceLocation rbrac,
John McCallf89e55a2010-11-18 06:31:45 +0000353 QualType &ReturnType, ExprValueKind &VK) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000354 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000355 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000356 for (unsigned i = 0; i != NumArgs; i++) {
357 if (Args[i]->isTypeDependent())
358 continue;
359
John Wiegley429bb272011-04-08 18:41:53 +0000360 ExprResult Result = DefaultArgumentPromotion(Args[i]);
361 if (Result.isInvalid())
362 return true;
363 Args[i] = Result.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000364 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000365
John McCallf85e1932011-06-15 23:02:42 +0000366 unsigned DiagID;
367 if (getLangOptions().ObjCAutoRefCount)
368 DiagID = diag::err_arc_method_not_found;
369 else
370 DiagID = isClassMessage ? diag::warn_class_method_not_found
371 : diag::warn_inst_method_not_found;
John McCall819e7452011-08-31 20:57:36 +0000372 if (!getLangOptions().DebuggerSupport)
373 Diag(lbrac, DiagID)
374 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
John McCall48218c62011-07-13 17:56:40 +0000375
376 // In debuggers, we want to use __unknown_anytype for these
377 // results so that clients can cast them.
378 if (getLangOptions().DebuggerSupport) {
379 ReturnType = Context.UnknownAnyTy;
380 } else {
381 ReturnType = Context.getObjCIdType();
382 }
John McCallf89e55a2010-11-18 06:31:45 +0000383 VK = VK_RValue;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000384 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000385 }
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Douglas Gregor926df6c2011-06-11 01:09:30 +0000387 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
388 isSuperMessage);
John McCallf89e55a2010-11-18 06:31:45 +0000389 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000391 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000392 // Method might have more arguments than selector indicates. This is due
393 // to addition of c-style arguments in method.
394 if (Method->param_size() > Sel.getNumArgs())
395 NumNamedArgs = Method->param_size();
396 // FIXME. This need be cleaned up.
397 if (NumArgs < NumNamedArgs) {
John McCallf89e55a2010-11-18 06:31:45 +0000398 Diag(lbrac, diag::err_typecheck_call_too_few_args)
399 << 2 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000400 return false;
401 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000402
Chris Lattner312531a2009-04-12 08:11:20 +0000403 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000404 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000405 // We can't do any type-checking on a type-dependent argument.
406 if (Args[i]->isTypeDependent())
407 continue;
408
Chris Lattner85a932e2008-01-04 22:32:30 +0000409 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000410
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000411 ParmVarDecl *Param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000412 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000414 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
415 Param->getType(),
416 PDiag(diag::err_call_incomplete_argument)
417 << argExpr->getSourceRange()))
418 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000419
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000420 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
421 Param);
John McCall3fa5cae2010-10-26 07:05:15 +0000422 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000423 if (ArgE.isInvalid())
424 IsError = true;
425 else
426 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000427 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000428
429 // Promote additional arguments to variadic methods.
430 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000431 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
432 if (Args[i]->isTypeDependent())
433 continue;
434
John Wiegley429bb272011-04-08 18:41:53 +0000435 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
436 IsError |= Arg.isInvalid();
437 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000438 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000439 } else {
440 // Check for extra arguments to non-variadic methods.
441 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000442 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000443 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000444 << 2 /*method*/ << NumNamedArgs << NumArgs
445 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000446 << SourceRange(Args[NumNamedArgs]->getLocStart(),
447 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000448 }
449 }
Fariborz Jahanian5272adf2011-04-15 22:06:22 +0000450 // diagnose nonnull arguments.
451 for (specific_attr_iterator<NonNullAttr>
452 i = Method->specific_attr_begin<NonNullAttr>(),
453 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
454 CheckNonNullArguments(*i, Args, lbrac);
455 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000456
Douglas Gregor2725ca82010-04-21 19:57:20 +0000457 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000458 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000459}
460
Douglas Gregorc737acb2011-09-27 16:10:05 +0000461bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000462 // 'self' is objc 'self' in an objc method only.
Fariborz Jahanianb4602102011-03-28 16:23:34 +0000463 DeclContext *DC = CurContext;
464 while (isa<BlockDecl>(DC))
465 DC = DC->getParent();
466 if (DC && !isa<ObjCMethodDecl>(DC))
Douglas Gregorc737acb2011-09-27 16:10:05 +0000467 return false;
John McCallf85e1932011-06-15 23:02:42 +0000468 receiver = receiver->IgnoreParenLValueCasts();
469 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000470 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
Douglas Gregorc737acb2011-09-27 16:10:05 +0000471 return true;
472 return false;
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000473}
474
Steve Narofff1afaf62009-02-26 15:55:06 +0000475// Helper method for ActOnClassMethod/ActOnInstanceMethod.
476// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000477// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000478// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000479ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000480 ObjCInterfaceDecl *ClassDecl) {
481 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000482 // lookup in class and all superclasses
483 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000484 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000485 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Steve Naroff5609ec02009-03-08 18:56:13 +0000487 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000488 if (!Method)
489 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Steve Naroff5609ec02009-03-08 18:56:13 +0000491 // Before we give up, check if the selector is an instance method.
492 // But only in the root. This matches gcc's behaviour and what the
493 // runtime expects.
494 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000495 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000496 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000497 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000498 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000499 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
500 }
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Steve Naroff5609ec02009-03-08 18:56:13 +0000502 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000503 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000504 return Method;
505}
506
507ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
508 ObjCInterfaceDecl *ClassDecl) {
509 ObjCMethodDecl *Method = 0;
510 while (ClassDecl && !Method) {
511 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000512 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000513 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Steve Naroff5609ec02009-03-08 18:56:13 +0000515 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000516 if (!Method)
517 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000518 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000519 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000520 return Method;
521}
522
Fariborz Jahanian61478062011-03-09 20:18:06 +0000523/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
524/// list of a qualified objective pointer type.
525ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
526 const ObjCObjectPointerType *OPT,
527 bool Instance)
528{
529 ObjCMethodDecl *MD = 0;
530 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
531 E = OPT->qual_end(); I != E; ++I) {
532 ObjCProtocolDecl *PROTO = (*I);
533 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
534 return MD;
535 }
536 }
537 return 0;
538}
539
Chris Lattner7f816522010-04-11 07:45:24 +0000540/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
541/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +0000542ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +0000543HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000544 Expr *BaseExpr, SourceLocation OpLoc,
545 DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000546 SourceLocation MemberLoc,
547 SourceLocation SuperLoc, QualType SuperType,
548 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +0000549 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
550 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +0000551
552 if (MemberName.getNameKind() != DeclarationName::Identifier) {
553 Diag(MemberLoc, diag::err_invalid_property_name)
554 << MemberName << QualType(OPT, 0);
555 return ExprError();
556 }
557
Chris Lattner7f816522010-04-11 07:45:24 +0000558 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
559
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +0000560 if (IFace->isForwardDecl()) {
561 Diag(MemberLoc, diag::err_property_not_found_forward_class)
562 << MemberName << QualType(OPT, 0);
563 Diag(IFace->getLocation(), diag::note_forward_class);
564 return ExprError();
565 }
Chris Lattner7f816522010-04-11 07:45:24 +0000566 // Search for a declared property first.
567 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
568 // Check whether we can reference this property.
569 if (DiagnoseUseOfDecl(PD, MemberLoc))
570 return ExprError();
571 QualType ResTy = PD->getType();
Fariborz Jahanian14086762011-03-28 23:47:18 +0000572 ResTy = ResTy.getNonLValueExprType(Context);
Chris Lattner7f816522010-04-11 07:45:24 +0000573 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
574 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000575 if (Getter &&
576 (Getter->hasRelatedResultType()
577 || DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc)))
578 ResTy = getMessageSendResultType(QualType(OPT, 0), Getter, false,
579 Super);
580
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000581 if (Super)
582 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000583 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000584 MemberLoc,
585 SuperLoc, SuperType));
586 else
587 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000588 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000589 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000590 }
591 // Check protocols on qualified interfaces.
592 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
593 E = OPT->qual_end(); I != E; ++I)
594 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
595 // Check whether we can reference this property.
596 if (DiagnoseUseOfDecl(PD, MemberLoc))
597 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000598
599 QualType T = PD->getType();
600 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
601 T = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000602 if (Super)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000603 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000604 VK_LValue,
605 OK_ObjCProperty,
606 MemberLoc,
607 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000608 else
Douglas Gregor926df6c2011-06-11 01:09:30 +0000609 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000610 VK_LValue,
611 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000612 MemberLoc,
613 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000614 }
615 // If that failed, look for an "implicit" property by seeing if the nullary
616 // selector is implemented.
617
618 // FIXME: The logic for looking up nullary and unary selectors should be
619 // shared with the code in ActOnInstanceMessage.
620
621 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
622 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000623
624 // May be founf in property's qualified list.
625 if (!Getter)
626 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +0000627
628 // If this reference is in an @implementation, check for 'private' methods.
629 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000630 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +0000631
632 // Look through local category implementations associated with the class.
633 if (!Getter)
634 Getter = IFace->getCategoryInstanceMethod(Sel);
635 if (Getter) {
636 // Check if we can reference this property.
637 if (DiagnoseUseOfDecl(Getter, MemberLoc))
638 return ExprError();
639 }
640 // If we found a getter then this may be a valid dot-reference, we
641 // will look for the matching setter, in case it is needed.
642 Selector SetterSel =
643 SelectorTable::constructSetterName(PP.getIdentifierTable(),
644 PP.getSelectorTable(), Member);
645 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000646
647 // May be founf in property's qualified list.
648 if (!Setter)
649 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
650
Chris Lattner7f816522010-04-11 07:45:24 +0000651 if (!Setter) {
652 // If this reference is in an @implementation, also check for 'private'
653 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000654 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +0000655 }
656 // Look through local category implementations associated with the class.
657 if (!Setter)
658 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000659
Chris Lattner7f816522010-04-11 07:45:24 +0000660 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
661 return ExprError();
662
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000663 if (Getter || Setter) {
664 QualType PType;
665 if (Getter)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000666 PType = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000667 else {
668 ParmVarDecl *ArgDecl = *Setter->param_begin();
669 PType = ArgDecl->getType();
670 }
671
John McCall09431682010-11-18 19:01:18 +0000672 ExprValueKind VK = VK_LValue;
673 ExprObjectKind OK = OK_ObjCProperty;
674 if (!getLangOptions().CPlusPlus && !PType.hasQualifiers() &&
675 PType->isVoidType())
676 VK = VK_RValue, OK = OK_Ordinary;
677
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000678 if (Super)
John McCall12f78a62010-12-02 01:19:52 +0000679 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
680 PType, VK, OK,
681 MemberLoc,
682 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000683 else
John McCall12f78a62010-12-02 01:19:52 +0000684 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
685 PType, VK, OK,
686 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000687
Chris Lattner7f816522010-04-11 07:45:24 +0000688 }
689
690 // Attempt to correct for typos in property names.
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000691 TypoCorrection Corrected = CorrectTypo(
692 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
693 NULL, IFace, false, CTC_NoKeywords, OPT);
694 if (ObjCPropertyDecl *Property =
695 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>()) {
696 DeclarationName TypoResult = Corrected.getCorrection();
Chris Lattner7f816522010-04-11 07:45:24 +0000697 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000698 << MemberName << QualType(OPT, 0) << TypoResult
699 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000700 Diag(Property->getLocation(), diag::note_previous_decl)
701 << Property->getDeclName();
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000702 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
703 TypoResult, MemberLoc,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000704 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +0000705 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000706 ObjCInterfaceDecl *ClassDeclared;
707 if (ObjCIvarDecl *Ivar =
708 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
709 QualType T = Ivar->getType();
710 if (const ObjCObjectPointerType * OBJPT =
711 T->getAsObjCInterfacePointerType()) {
712 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
713 if (ObjCInterfaceDecl *IFace = IFaceT->getDecl())
714 if (IFace->isForwardDecl()) {
715 Diag(MemberLoc, diag::err_property_not_as_forward_class)
Fariborz Jahanian2a96bf52011-02-17 17:30:05 +0000716 << MemberName << IFace;
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000717 Diag(IFace->getLocation(), diag::note_forward_class);
718 return ExprError();
719 }
720 }
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000721 Diag(MemberLoc,
722 diag::err_ivar_access_using_property_syntax_suggest)
723 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
724 << FixItHint::CreateReplacement(OpLoc, "->");
725 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000726 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000727
Chris Lattner7f816522010-04-11 07:45:24 +0000728 Diag(MemberLoc, diag::err_property_not_found)
729 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000730 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +0000731 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000732 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +0000733 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000734}
735
736
737
John McCall60d7b3a2010-08-24 06:29:42 +0000738ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +0000739ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
740 IdentifierInfo &propertyName,
741 SourceLocation receiverNameLoc,
742 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000744 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000745 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
746 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000747
748 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +0000749 if (IFace == 0) {
750 // If the "receiver" is 'super' in a method, handle it as an expression-like
751 // property reference.
John McCall26743b22011-02-03 09:00:02 +0000752 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000753 IsSuper = true;
754
John McCall26743b22011-02-03 09:00:02 +0000755 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf()) {
Chris Lattnereb483eb2010-04-11 08:28:14 +0000756 if (CurMethod->isInstanceMethod()) {
757 QualType T =
758 Context.getObjCInterfaceType(CurMethod->getClassInterface());
759 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000760
761 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000762 /*BaseExpr*/0,
763 SourceLocation()/*OpLoc*/,
764 &propertyName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000765 propertyNameLoc,
766 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000767 }
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Chris Lattnereb483eb2010-04-11 08:28:14 +0000769 // Otherwise, if this is a class method, try dispatching to our
770 // superclass.
771 IFace = CurMethod->getClassInterface()->getSuperClass();
772 }
John McCall26743b22011-02-03 09:00:02 +0000773 }
Chris Lattnereb483eb2010-04-11 08:28:14 +0000774
775 if (IFace == 0) {
776 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
777 return ExprError();
778 }
779 }
780
781 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000782 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000783 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000784
785 // If this reference is in an @implementation, check for 'private' methods.
786 if (!Getter)
787 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
788 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000789 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000790 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000791
792 if (Getter) {
793 // FIXME: refactor/share with ActOnMemberReference().
794 // Check if we can reference this property.
795 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
796 return ExprError();
797 }
Mike Stump1eb44332009-09-09 15:08:12 +0000798
Steve Naroff61f72cb2009-03-09 21:12:44 +0000799 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000800 Selector SetterSel =
801 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000802 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000803
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000804 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000805 if (!Setter) {
806 // If this reference is in an @implementation, also check for 'private'
807 // methods.
808 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
809 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000810 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000811 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000812 }
813 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000814 if (!Setter)
815 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000816
817 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
818 return ExprError();
819
820 if (Getter || Setter) {
821 QualType PType;
822
John McCall09431682010-11-18 19:01:18 +0000823 ExprValueKind VK = VK_LValue;
824 if (Getter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000825 PType = getMessageSendResultType(Context.getObjCInterfaceType(IFace),
826 Getter, true,
827 receiverNamePtr->isStr("super"));
John McCall09431682010-11-18 19:01:18 +0000828 if (!getLangOptions().CPlusPlus &&
829 !PType.hasQualifiers() && PType->isVoidType())
830 VK = VK_RValue;
831 } else {
Steve Naroff61f72cb2009-03-09 21:12:44 +0000832 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
833 E = Setter->param_end(); PI != E; ++PI)
834 PType = (*PI)->getType();
John McCall09431682010-11-18 19:01:18 +0000835 VK = VK_LValue;
Steve Naroff61f72cb2009-03-09 21:12:44 +0000836 }
John McCall09431682010-11-18 19:01:18 +0000837
838 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
839
Douglas Gregor926df6c2011-06-11 01:09:30 +0000840 if (IsSuper)
841 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
842 PType, VK, OK,
843 propertyNameLoc,
844 receiverNameLoc,
845 Context.getObjCInterfaceType(IFace)));
846
John McCall12f78a62010-12-02 01:19:52 +0000847 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
848 PType, VK, OK,
849 propertyNameLoc,
850 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +0000851 }
852 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
853 << &propertyName << Context.getObjCInterfaceType(IFace));
854}
855
Douglas Gregor47bd5432010-04-14 02:46:37 +0000856Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000857 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000858 SourceLocation NameLoc,
859 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000860 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +0000861 ParsedType &ReceiverType) {
862 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +0000863
Douglas Gregor47bd5432010-04-14 02:46:37 +0000864 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +0000865 // messaging super. If the identifier is "super" and there is a
866 // trailing dot, it's an instance message.
867 if (IsSuper && S->isInObjcMethodScope())
868 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000869
870 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
871 LookupName(Result, S);
872
873 switch (Result.getResultKind()) {
874 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000875 // Normal name lookup didn't find anything. If we're in an
876 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +0000877 // FIXME: This is a hack. Ivar lookup should be part of normal
878 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +0000879 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
880 ObjCInterfaceDecl *ClassDeclared;
881 if (Method->getClassInterface()->lookupInstanceVariable(Name,
882 ClassDeclared))
883 return ObjCInstanceMessage;
884 }
Douglas Gregor95f42922010-10-14 22:11:03 +0000885
Douglas Gregor47bd5432010-04-14 02:46:37 +0000886 // Break out; we'll perform typo correction below.
887 break;
888
889 case LookupResult::NotFoundInCurrentInstantiation:
890 case LookupResult::FoundOverloaded:
891 case LookupResult::FoundUnresolvedValue:
892 case LookupResult::Ambiguous:
893 Result.suppressDiagnostics();
894 return ObjCInstanceMessage;
895
896 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +0000897 // If the identifier is a class or not, and there is a trailing dot,
898 // it's an instance message.
899 if (HasTrailingDot)
900 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000901 // We found something. If it's a type, then we have a class
902 // message. Otherwise, it's an instance message.
903 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000904 QualType T;
905 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
906 T = Context.getObjCInterfaceType(Class);
907 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
908 T = Context.getTypeDeclType(Type);
909 else
910 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000911
Douglas Gregor1569f952010-04-21 20:38:13 +0000912 // We have a class message, and T is the type we're
913 // messaging. Build source-location information for it.
914 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000915 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +0000916 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000917 }
918 }
919
Douglas Gregoraaf87162010-04-14 20:04:41 +0000920 // Determine our typo-correction context.
921 CorrectTypoContext CTC = CTC_Expression;
922 if (ObjCMethodDecl *Method = getCurMethodDecl())
923 if (Method->getClassInterface() &&
924 Method->getClassInterface()->getSuperClass())
925 CTC = CTC_ObjCMessageReceiver;
926
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000927 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
928 Result.getLookupKind(), S, NULL,
929 NULL, false, CTC)) {
930 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000931 // If we found a declaration, correct when it refers to an Objective-C
932 // class.
Douglas Gregor1569f952010-04-21 20:38:13 +0000933 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000934 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000935 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000936 << FixItHint::CreateReplacement(SourceRange(NameLoc),
937 ND->getNameAsString());
938 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000939 << Corrected.getCorrection();
Douglas Gregor47bd5432010-04-14 02:46:37 +0000940
Douglas Gregor1569f952010-04-21 20:38:13 +0000941 QualType T = Context.getObjCInterfaceType(Class);
942 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000943 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000944 return ObjCClassMessage;
945 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000946 } else if (Corrected.isKeyword() &&
947 Corrected.getCorrectionAsIdentifierInfo()->isStr("super")) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000948 // If we've found the keyword "super", this is a send to super.
949 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000950 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000951 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +0000952 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000953 }
954 }
955
956 // Fall back: let the parser try to parse it as an instance message.
957 return ObjCInstanceMessage;
958}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000959
John McCall60d7b3a2010-08-24 06:29:42 +0000960ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000961 SourceLocation SuperLoc,
962 Selector Sel,
963 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +0000964 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000965 SourceLocation RBracLoc,
966 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000967 // Determine whether we are inside a method or not.
John McCall26743b22011-02-03 09:00:02 +0000968 ObjCMethodDecl *Method = tryCaptureObjCSelf();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000969 if (!Method) {
970 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
971 return ExprError();
972 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000973
Douglas Gregorf95861a2010-04-21 20:01:04 +0000974 ObjCInterfaceDecl *Class = Method->getClassInterface();
975 if (!Class) {
976 Diag(SuperLoc, diag::error_no_super_class_message)
977 << Method->getDeclName();
978 return ExprError();
979 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000980
Douglas Gregorf95861a2010-04-21 20:01:04 +0000981 ObjCInterfaceDecl *Super = Class->getSuperClass();
982 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000983 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +0000984 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
985 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +0000986 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000987 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000988
Douglas Gregorf95861a2010-04-21 20:01:04 +0000989 // We are in a method whose class has a superclass, so 'super'
990 // is acting as a keyword.
991 if (Method->isInstanceMethod()) {
Nico Weber9a1ecf02011-08-22 17:25:57 +0000992 if (Sel.getMethodFamily() == OMF_dealloc)
993 ObjCShouldCallSuperDealloc = false;
Nico Weber80cb6e62011-08-28 22:35:17 +0000994 if (Sel.getMethodFamily() == OMF_finalize)
995 ObjCShouldCallSuperFinalize = false;
Nico Weber9a1ecf02011-08-22 17:25:57 +0000996
Douglas Gregorf95861a2010-04-21 20:01:04 +0000997 // Since we are in an instance method, this is an instance
998 // message to the superclass instance.
999 QualType SuperTy = Context.getObjCInterfaceType(Super);
1000 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +00001001 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001002 Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001003 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001004 }
Douglas Gregorf95861a2010-04-21 20:01:04 +00001005
1006 // Since we are in a class method, this is a class message to
1007 // the superclass.
1008 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1009 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001010 SuperLoc, Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001011 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001012}
1013
1014/// \brief Build an Objective-C class message expression.
1015///
1016/// This routine takes care of both normal class messages and
1017/// class messages to the superclass.
1018///
1019/// \param ReceiverTypeInfo Type source information that describes the
1020/// receiver of this message. This may be NULL, in which case we are
1021/// sending to the superclass and \p SuperLoc must be a valid source
1022/// location.
1023
1024/// \param ReceiverType The type of the object receiving the
1025/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1026/// type as that refers to. For a superclass send, this is the type of
1027/// the superclass.
1028///
1029/// \param SuperLoc The location of the "super" keyword in a
1030/// superclass message.
1031///
1032/// \param Sel The selector to which the message is being sent.
1033///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001034/// \param Method The method that this class message is invoking, if
1035/// already known.
1036///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001037/// \param LBracLoc The location of the opening square bracket ']'.
1038///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001039/// \param RBrac The location of the closing square bracket ']'.
1040///
1041/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001042ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001043 QualType ReceiverType,
1044 SourceLocation SuperLoc,
1045 Selector Sel,
1046 ObjCMethodDecl *Method,
1047 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001048 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001049 SourceLocation RBracLoc,
1050 MultiExprArg ArgsIn) {
1051 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001052 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001053 if (LBracLoc.isInvalid()) {
1054 Diag(Loc, diag::err_missing_open_square_message_send)
1055 << FixItHint::CreateInsertion(Loc, "[");
1056 LBracLoc = Loc;
1057 }
1058
Douglas Gregor92e986e2010-04-22 16:44:27 +00001059 if (ReceiverType->isDependentType()) {
1060 // If the receiver type is dependent, we can't type-check anything
1061 // at this point. Build a dependent expression.
1062 unsigned NumArgs = ArgsIn.size();
1063 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1064 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001065 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1066 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001067 Sel, SelectorLocs, /*Method=*/0,
Douglas Gregor92e986e2010-04-22 16:44:27 +00001068 Args, NumArgs, RBracLoc));
1069 }
Chris Lattner15faee12010-04-12 05:38:43 +00001070
Douglas Gregor2725ca82010-04-21 19:57:20 +00001071 // Find the class to which we are sending this message.
1072 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001073 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1074 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001075 Diag(Loc, diag::err_invalid_receiver_class_message)
1076 << ReceiverType;
1077 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001078 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001079 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian02b0d652011-03-08 19:12:46 +00001080 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001081 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001082 if (!Method) {
1083 if (Class->isForwardDecl()) {
John McCallf85e1932011-06-15 23:02:42 +00001084 if (getLangOptions().ObjCAutoRefCount) {
1085 Diag(Loc, diag::err_arc_receiver_forward_class) << ReceiverType;
1086 } else {
1087 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
1088 }
1089
Douglas Gregorf49bb082010-04-22 17:01:48 +00001090 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001091 Method = LookupFactoryMethodInGlobalPool(Sel,
1092 SourceRange(LBracLoc, RBracLoc));
John McCallf85e1932011-06-15 23:02:42 +00001093 if (Method && !getLangOptions().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001094 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1095 << Method->getDeclName();
1096 }
1097 if (!Method)
1098 Method = Class->lookupClassMethod(Sel);
1099
1100 // If we have an implementation in scope, check "private" methods.
1101 if (!Method)
1102 Method = LookupPrivateClassMethod(Sel, Class);
1103
1104 if (Method && DiagnoseUseOfDecl(Method, Loc))
1105 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001106 }
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Douglas Gregor2725ca82010-04-21 19:57:20 +00001108 // Check the argument types and determine the result type.
1109 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001110 ExprValueKind VK = VK_RValue;
1111
Douglas Gregor2725ca82010-04-21 19:57:20 +00001112 unsigned NumArgs = ArgsIn.size();
1113 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001114 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1115 SuperLoc.isValid(), LBracLoc, RBracLoc,
1116 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001117 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001118
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001119 if (Method && !Method->getResultType()->isVoidType() &&
1120 RequireCompleteType(LBracLoc, Method->getResultType(),
1121 diag::err_illegal_message_expr_incomplete_type))
1122 return ExprError();
1123
Douglas Gregor2725ca82010-04-21 19:57:20 +00001124 // Construct the appropriate ObjCMessageExpr.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001125 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001126 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001127 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001128 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001129 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001130 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001131 else
John McCallf89e55a2010-11-18 06:31:45 +00001132 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001133 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001134 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001135 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00001136}
1137
Douglas Gregor2725ca82010-04-21 19:57:20 +00001138// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00001139// ArgExprs is optional - if it is present, the number of expressions
1140// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001141ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00001142 ParsedType Receiver,
1143 Selector Sel,
1144 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001145 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor77328d12010-09-15 23:19:31 +00001146 SourceLocation RBracLoc,
1147 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001148 TypeSourceInfo *ReceiverTypeInfo;
1149 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1150 if (ReceiverType.isNull())
1151 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Douglas Gregor2725ca82010-04-21 19:57:20 +00001154 if (!ReceiverTypeInfo)
1155 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1156
1157 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00001158 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001159 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001160}
1161
1162/// \brief Build an Objective-C instance message expression.
1163///
1164/// This routine takes care of both normal instance messages and
1165/// instance messages to the superclass instance.
1166///
1167/// \param Receiver The expression that computes the object that will
1168/// receive this message. This may be empty, in which case we are
1169/// sending to the superclass instance and \p SuperLoc must be a valid
1170/// source location.
1171///
1172/// \param ReceiverType The (static) type of the object receiving the
1173/// message. When a \p Receiver expression is provided, this is the
1174/// same type as that expression. For a superclass instance send, this
1175/// is a pointer to the type of the superclass.
1176///
1177/// \param SuperLoc The location of the "super" keyword in a
1178/// superclass instance message.
1179///
1180/// \param Sel The selector to which the message is being sent.
1181///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001182/// \param Method The method that this instance message is invoking, if
1183/// already known.
1184///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001185/// \param LBracLoc The location of the opening square bracket ']'.
1186///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001187/// \param RBrac The location of the closing square bracket ']'.
1188///
1189/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001190ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001191 QualType ReceiverType,
1192 SourceLocation SuperLoc,
1193 Selector Sel,
1194 ObjCMethodDecl *Method,
1195 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001196 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001197 SourceLocation RBracLoc,
1198 MultiExprArg ArgsIn) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001199 // The location of the receiver.
1200 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1201
1202 if (LBracLoc.isInvalid()) {
1203 Diag(Loc, diag::err_missing_open_square_message_send)
1204 << FixItHint::CreateInsertion(Loc, "[");
1205 LBracLoc = Loc;
1206 }
1207
Douglas Gregor2725ca82010-04-21 19:57:20 +00001208 // If we have a receiver expression, perform appropriate promotions
1209 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00001210 if (Receiver) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001211 if (Receiver->isTypeDependent()) {
1212 // If the receiver is type-dependent, we can't type-check anything
1213 // at this point. Build a dependent expression.
1214 unsigned NumArgs = ArgsIn.size();
1215 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1216 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1217 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00001218 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001219 SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001220 Args, NumArgs, RBracLoc));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001221 }
1222
Douglas Gregor2725ca82010-04-21 19:57:20 +00001223 // If necessary, apply function/array conversion to the receiver.
1224 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00001225 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1226 if (Result.isInvalid())
1227 return ExprError();
1228 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001229 ReceiverType = Receiver->getType();
1230 }
1231
Douglas Gregorf49bb082010-04-22 17:01:48 +00001232 if (!Method) {
1233 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00001234 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001235 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00001236 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1237 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001238 SourceRange(LBracLoc, RBracLoc),
1239 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001240 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00001241 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001242 SourceRange(LBracLoc, RBracLoc),
1243 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001244 } else if (ReceiverType->isObjCClassType() ||
1245 ReceiverType->isObjCQualifiedClassType()) {
1246 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001247 // We allow sending a message to a qualified Class ("Class<foo>"), which
1248 // is ok as long as one of the protocols implements the selector (if not, warn).
1249 if (const ObjCObjectPointerType *QClassTy
1250 = ReceiverType->getAsObjCQualifiedClassType()) {
1251 // Search protocols for class methods.
1252 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1253 if (!Method) {
1254 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1255 // warn if instance method found for a Class message.
1256 if (Method) {
1257 Diag(Loc, diag::warn_instance_method_on_class_found)
1258 << Method->getSelector() << Sel;
1259 Diag(Method->getLocation(), diag::note_method_declared_at);
1260 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001261 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001262 } else {
1263 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1264 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1265 // First check the public methods in the class interface.
1266 Method = ClassDecl->lookupClassMethod(Sel);
1267
1268 if (!Method)
1269 Method = LookupPrivateClassMethod(Sel, ClassDecl);
1270 }
1271 if (Method && DiagnoseUseOfDecl(Method, Loc))
1272 return ExprError();
1273 }
1274 if (!Method) {
1275 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregorc737acb2011-09-27 16:10:05 +00001276 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001277 Method = LookupFactoryMethodInGlobalPool(Sel,
1278 SourceRange(LBracLoc, RBracLoc),
1279 true);
1280 if (!Method) {
1281 // If no class (factory) method was found, check if an _instance_
1282 // method of the same name exists in the root class only.
1283 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001284 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001285 true);
1286 if (Method)
1287 if (const ObjCInterfaceDecl *ID =
1288 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1289 if (ID->getSuperClass())
1290 Diag(Loc, diag::warn_root_inst_method_not_found)
1291 << Sel << SourceRange(LBracLoc, RBracLoc);
1292 }
1293 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001294 }
1295 }
1296 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001297 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001298 ObjCInterfaceDecl* ClassDecl = 0;
1299
1300 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1301 // long as one of the protocols implements the selector (if not, warn).
1302 if (const ObjCObjectPointerType *QIdTy
1303 = ReceiverType->getAsObjCQualifiedIdType()) {
1304 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001305 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
1306 if (!Method)
1307 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001308 } else if (const ObjCObjectPointerType *OCIType
1309 = ReceiverType->getAsObjCInterfacePointerType()) {
1310 // We allow sending a message to a pointer to an interface (an object).
1311 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00001312
1313 if (ClassDecl->isForwardDecl() && getLangOptions().ObjCAutoRefCount) {
1314 Diag(Loc, diag::err_arc_receiver_forward_instance)
1315 << OCIType->getPointeeType()
1316 << (Receiver ? Receiver->getSourceRange() : SourceRange(SuperLoc));
1317 return ExprError();
1318 }
1319
Douglas Gregorf49bb082010-04-22 17:01:48 +00001320 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
1321 // faster than the following method (which can do *many* linear searches).
Sebastian Redldb9d2142010-08-02 23:18:59 +00001322 // The idea is to add class info to MethodPool.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001323 Method = ClassDecl->lookupInstanceMethod(Sel);
1324
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001325 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001326 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001327 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
1328
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001329 const ObjCInterfaceDecl *forwardClass = 0;
Douglas Gregorf49bb082010-04-22 17:01:48 +00001330 if (!Method) {
1331 // If we have implementations in scope, check "private" methods.
1332 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1333
John McCallf85e1932011-06-15 23:02:42 +00001334 if (!Method && getLangOptions().ObjCAutoRefCount) {
1335 Diag(Loc, diag::err_arc_may_not_respond)
1336 << OCIType->getPointeeType() << Sel;
1337 return ExprError();
1338 }
1339
Douglas Gregorc737acb2011-09-27 16:10:05 +00001340 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001341 // If we still haven't found a method, look in the global pool. This
1342 // behavior isn't very desirable, however we need it for GCC
1343 // compatibility. FIXME: should we deviate??
1344 if (OCIType->qual_empty()) {
1345 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001346 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001347 if (OCIType->getInterfaceDecl()->isForwardDecl())
1348 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001349 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001350 Diag(Loc, diag::warn_maynot_respond)
1351 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1352 }
1353 }
1354 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001355 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00001356 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00001357 } else if (!getLangOptions().ObjCAutoRefCount &&
1358 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00001359 (ReceiverType->isPointerType() ||
1360 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001361 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00001362 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001363 Diag(Loc, diag::warn_bad_receiver_type)
1364 << ReceiverType
1365 << Receiver->getSourceRange();
1366 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00001367 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00001368 CK_CPointerToObjCPointerCast).take();
John McCall404cd162010-11-13 01:35:44 +00001369 else {
1370 // TODO: specialized warning on null receivers?
1371 bool IsNull = Receiver->isNullPointerConstant(Context,
1372 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00001373 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1374 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00001375 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001376 ReceiverType = Receiver->getType();
John McCall0bcc9bc2011-09-09 06:11:02 +00001377 } else {
John Wiegley429bb272011-04-08 18:41:53 +00001378 ExprResult ReceiverRes;
1379 if (getLangOptions().CPlusPlus)
John McCall0bcc9bc2011-09-09 06:11:02 +00001380 ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
John Wiegley429bb272011-04-08 18:41:53 +00001381 if (ReceiverRes.isUsable()) {
1382 Receiver = ReceiverRes.take();
John Wiegley429bb272011-04-08 18:41:53 +00001383 return BuildInstanceMessage(Receiver,
1384 ReceiverType,
1385 SuperLoc,
1386 Sel,
1387 Method,
1388 LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001389 SelectorLocs,
John Wiegley429bb272011-04-08 18:41:53 +00001390 RBracLoc,
1391 move(ArgsIn));
1392 } else {
1393 // Reject other random receiver types (e.g. structs).
1394 Diag(Loc, diag::err_bad_receiver_type)
1395 << ReceiverType << Receiver->getSourceRange();
1396 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00001397 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001398 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001399 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00001400 }
Mike Stump1eb44332009-09-09 15:08:12 +00001401
Douglas Gregor2725ca82010-04-21 19:57:20 +00001402 // Check the message arguments.
1403 unsigned NumArgs = ArgsIn.size();
1404 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1405 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001406 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00001407 bool ClassMessage = (ReceiverType->isObjCClassType() ||
1408 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001409 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
1410 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00001411 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001412 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00001413
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001414 if (Method && !Method->getResultType()->isVoidType() &&
1415 RequireCompleteType(LBracLoc, Method->getResultType(),
1416 diag::err_illegal_message_expr_incomplete_type))
1417 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001418
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001419 SourceLocation SelLoc = SelectorLocs.front();
1420
John McCallf85e1932011-06-15 23:02:42 +00001421 // In ARC, forbid the user from sending messages to
1422 // retain/release/autorelease/dealloc/retainCount explicitly.
1423 if (getLangOptions().ObjCAutoRefCount) {
1424 ObjCMethodFamily family =
1425 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
1426 switch (family) {
1427 case OMF_init:
1428 if (Method)
1429 checkInitMethod(Method, ReceiverType);
1430
1431 case OMF_None:
1432 case OMF_alloc:
1433 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +00001434 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +00001435 case OMF_mutableCopy:
1436 case OMF_new:
1437 case OMF_self:
1438 break;
1439
1440 case OMF_dealloc:
1441 case OMF_retain:
1442 case OMF_release:
1443 case OMF_autorelease:
1444 case OMF_retainCount:
1445 Diag(Loc, diag::err_arc_illegal_explicit_message)
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001446 << Sel << SelLoc;
John McCallf85e1932011-06-15 23:02:42 +00001447 break;
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001448
1449 case OMF_performSelector:
1450 if (Method && NumArgs >= 1) {
1451 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
1452 Selector ArgSel = SelExp->getSelector();
1453 ObjCMethodDecl *SelMethod =
1454 LookupInstanceMethodInGlobalPool(ArgSel,
1455 SelExp->getSourceRange());
1456 if (!SelMethod)
1457 SelMethod =
1458 LookupFactoryMethodInGlobalPool(ArgSel,
1459 SelExp->getSourceRange());
1460 if (SelMethod) {
1461 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
1462 switch (SelFamily) {
1463 case OMF_alloc:
1464 case OMF_copy:
1465 case OMF_mutableCopy:
1466 case OMF_new:
1467 case OMF_self:
1468 case OMF_init:
1469 // Issue error, unless ns_returns_not_retained.
1470 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
1471 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001472 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001473 diag::err_arc_perform_selector_retains);
1474 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1475 }
1476 break;
1477 default:
1478 // +0 call. OK. unless ns_returns_retained.
1479 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
1480 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001481 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001482 diag::err_arc_perform_selector_retains);
1483 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1484 }
1485 break;
1486 }
1487 }
1488 } else {
1489 // error (may leak).
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001490 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001491 Diag(Args[0]->getExprLoc(), diag::note_used_here);
1492 }
1493 }
1494 break;
John McCallf85e1932011-06-15 23:02:42 +00001495 }
1496 }
1497
Douglas Gregor2725ca82010-04-21 19:57:20 +00001498 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00001499 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001500 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001501 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001502 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001503 ReceiverType, Sel, SelectorLocs, Method,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001504 Args, NumArgs, RBracLoc);
1505 else
John McCallf89e55a2010-11-18 06:31:45 +00001506 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001507 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001508 Args, NumArgs, RBracLoc);
John McCallf85e1932011-06-15 23:02:42 +00001509
1510 if (getLangOptions().ObjCAutoRefCount) {
1511 // In ARC, annotate delegate init calls.
1512 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregorc737acb2011-09-27 16:10:05 +00001513 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCallf85e1932011-06-15 23:02:42 +00001514 // Only consider init calls *directly* in init implementations,
1515 // not within blocks.
1516 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
1517 if (method && method->getMethodFamily() == OMF_init) {
1518 // The implicit assignment to self means we also don't want to
1519 // consume the result.
1520 Result->setDelegateInitCall(true);
1521 return Owned(Result);
1522 }
1523 }
1524
1525 // In ARC, check for message sends which are likely to introduce
1526 // retain cycles.
1527 checkRetainCycles(Result);
1528 }
1529
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001530 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001531}
1532
1533// ActOnInstanceMessage - used for both unary and keyword messages.
1534// ArgExprs is optional - if it is present, the number of expressions
1535// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001536ExprResult Sema::ActOnInstanceMessage(Scope *S,
1537 Expr *Receiver,
1538 Selector Sel,
1539 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001540 ArrayRef<SourceLocation> SelectorLocs,
John McCall60d7b3a2010-08-24 06:29:42 +00001541 SourceLocation RBracLoc,
1542 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001543 if (!Receiver)
1544 return ExprError();
1545
John McCall9ae2f072010-08-23 23:25:46 +00001546 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001547 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001548 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001549}
Chris Lattnereca7be62008-04-07 05:30:13 +00001550
John McCallf85e1932011-06-15 23:02:42 +00001551enum ARCConversionTypeClass {
John McCall2cf031d2011-10-01 01:01:08 +00001552 /// int, void, struct A
John McCallf85e1932011-06-15 23:02:42 +00001553 ACTC_none,
John McCall2cf031d2011-10-01 01:01:08 +00001554
1555 /// id, void (^)()
John McCallf85e1932011-06-15 23:02:42 +00001556 ACTC_retainable,
John McCall2cf031d2011-10-01 01:01:08 +00001557
1558 /// id*, id***, void (^*)(),
1559 ACTC_indirectRetainable,
1560
1561 /// void* might be a normal C type, or it might a CF type.
1562 ACTC_voidPtr,
1563
1564 /// struct A*
1565 ACTC_coreFoundation
John McCallf85e1932011-06-15 23:02:42 +00001566};
John McCall2cf031d2011-10-01 01:01:08 +00001567static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
1568 return (ACTC == ACTC_retainable ||
1569 ACTC == ACTC_coreFoundation ||
1570 ACTC == ACTC_voidPtr);
1571}
1572static bool isAnyCLike(ARCConversionTypeClass ACTC) {
1573 return ACTC == ACTC_none ||
1574 ACTC == ACTC_voidPtr ||
1575 ACTC == ACTC_coreFoundation;
1576}
1577
John McCallf85e1932011-06-15 23:02:42 +00001578static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCall2cf031d2011-10-01 01:01:08 +00001579 bool isIndirect = false;
John McCallf85e1932011-06-15 23:02:42 +00001580
1581 // Ignore an outermost reference type.
John McCall2cf031d2011-10-01 01:01:08 +00001582 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCallf85e1932011-06-15 23:02:42 +00001583 type = ref->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00001584 isIndirect = true;
1585 }
John McCallf85e1932011-06-15 23:02:42 +00001586
1587 // Drill through pointers and arrays recursively.
1588 while (true) {
1589 if (const PointerType *ptr = type->getAs<PointerType>()) {
1590 type = ptr->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00001591
1592 // The first level of pointer may be the innermost pointer on a CF type.
1593 if (!isIndirect) {
1594 if (type->isVoidType()) return ACTC_voidPtr;
1595 if (type->isRecordType()) return ACTC_coreFoundation;
1596 }
John McCallf85e1932011-06-15 23:02:42 +00001597 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
1598 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
1599 } else {
1600 break;
1601 }
John McCall2cf031d2011-10-01 01:01:08 +00001602 isIndirect = true;
John McCallf85e1932011-06-15 23:02:42 +00001603 }
1604
John McCall2cf031d2011-10-01 01:01:08 +00001605 if (isIndirect) {
1606 if (type->isObjCARCBridgableType())
1607 return ACTC_indirectRetainable;
1608 return ACTC_none;
1609 }
1610
1611 if (type->isObjCARCBridgableType())
1612 return ACTC_retainable;
1613
1614 return ACTC_none;
John McCallf85e1932011-06-15 23:02:42 +00001615}
1616
1617namespace {
John McCall2cf031d2011-10-01 01:01:08 +00001618 /// A result from the cast checker.
1619 enum ACCResult {
1620 /// Cannot be casted.
1621 ACC_invalid,
1622
1623 /// Can be safely retained or not retained.
1624 ACC_bottom,
1625
1626 /// Can be casted at +0.
1627 ACC_plusZero,
1628
1629 /// Can be casted at +1.
1630 ACC_plusOne
1631 };
1632 ACCResult merge(ACCResult left, ACCResult right) {
1633 if (left == right) return left;
1634 if (left == ACC_bottom) return right;
1635 if (right == ACC_bottom) return left;
1636 return ACC_invalid;
1637 }
1638
1639 /// A checker which white-lists certain expressions whose conversion
1640 /// to or from retainable type would otherwise be forbidden in ARC.
1641 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
1642 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
1643
John McCallf85e1932011-06-15 23:02:42 +00001644 ASTContext &Context;
John McCall2cf031d2011-10-01 01:01:08 +00001645 ARCConversionTypeClass SourceClass;
1646 ARCConversionTypeClass TargetClass;
1647
1648 static bool isCFType(QualType type) {
1649 // Someday this can use ns_bridged. For now, it has to do this.
1650 return type->isCARCBridgableType();
John McCallf85e1932011-06-15 23:02:42 +00001651 }
John McCall2cf031d2011-10-01 01:01:08 +00001652
1653 public:
1654 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
1655 ARCConversionTypeClass target)
1656 : Context(Context), SourceClass(source), TargetClass(target) {}
1657
1658 using super::Visit;
1659 ACCResult Visit(Expr *e) {
1660 return super::Visit(e->IgnoreParens());
1661 }
1662
1663 ACCResult VisitStmt(Stmt *s) {
1664 return ACC_invalid;
1665 }
1666
1667 /// Null pointer constants can be casted however you please.
1668 ACCResult VisitExpr(Expr *e) {
1669 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1670 return ACC_bottom;
1671 return ACC_invalid;
1672 }
1673
1674 /// Objective-C string literals can be safely casted.
1675 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
1676 // If we're casting to any retainable type, go ahead. Global
1677 // strings are immune to retains, so this is bottom.
1678 if (isAnyRetainable(TargetClass)) return ACC_bottom;
1679
1680 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00001681 }
1682
John McCall2cf031d2011-10-01 01:01:08 +00001683 /// Look through certain implicit and explicit casts.
1684 ACCResult VisitCastExpr(CastExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00001685 switch (e->getCastKind()) {
1686 case CK_NullToPointer:
John McCall2cf031d2011-10-01 01:01:08 +00001687 return ACC_bottom;
1688
John McCallf85e1932011-06-15 23:02:42 +00001689 case CK_NoOp:
1690 case CK_LValueToRValue:
1691 case CK_BitCast:
John McCall2cf031d2011-10-01 01:01:08 +00001692 case CK_GetObjCProperty:
John McCall1d9b3b22011-09-09 05:25:32 +00001693 case CK_CPointerToObjCPointerCast:
1694 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00001695 case CK_AnyPointerToBlockPointerCast:
1696 return Visit(e->getSubExpr());
John McCall2cf031d2011-10-01 01:01:08 +00001697
John McCallf85e1932011-06-15 23:02:42 +00001698 default:
John McCall2cf031d2011-10-01 01:01:08 +00001699 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00001700 }
1701 }
John McCall2cf031d2011-10-01 01:01:08 +00001702
1703 /// Look through unary extension.
1704 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00001705 return Visit(e->getSubExpr());
1706 }
John McCall2cf031d2011-10-01 01:01:08 +00001707
1708 /// Ignore the LHS of a comma operator.
1709 ACCResult VisitBinComma(BinaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00001710 return Visit(e->getRHS());
1711 }
John McCall2cf031d2011-10-01 01:01:08 +00001712
1713 /// Conditional operators are okay if both sides are okay.
1714 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
1715 ACCResult left = Visit(e->getTrueExpr());
1716 if (left == ACC_invalid) return ACC_invalid;
1717 return merge(left, Visit(e->getFalseExpr()));
John McCallf85e1932011-06-15 23:02:42 +00001718 }
John McCall2cf031d2011-10-01 01:01:08 +00001719
1720 /// Statement expressions are okay if their result expression is okay.
1721 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00001722 return Visit(e->getSubStmt()->body_back());
1723 }
John McCallf85e1932011-06-15 23:02:42 +00001724
John McCall2cf031d2011-10-01 01:01:08 +00001725 /// Some declaration references are okay.
1726 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
1727 // References to global constants from system headers are okay.
1728 // These are things like 'kCFStringTransformToLatin'. They are
1729 // can also be assumed to be immune to retains.
1730 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
1731 if (isAnyRetainable(TargetClass) &&
1732 isAnyRetainable(SourceClass) &&
1733 var &&
1734 var->getStorageClass() == SC_Extern &&
1735 var->getType().isConstQualified() &&
1736 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
1737 return ACC_bottom;
1738 }
1739
1740 // Nothing else.
1741 return ACC_invalid;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001742 }
John McCall2cf031d2011-10-01 01:01:08 +00001743
1744 /// Some calls are okay.
1745 ACCResult VisitCallExpr(CallExpr *e) {
1746 if (FunctionDecl *fn = e->getDirectCallee())
1747 if (ACCResult result = checkCallToFunction(fn))
1748 return result;
1749
1750 return super::VisitCallExpr(e);
1751 }
1752
1753 ACCResult checkCallToFunction(FunctionDecl *fn) {
1754 // Require a CF*Ref return type.
1755 if (!isCFType(fn->getResultType()))
1756 return ACC_invalid;
1757
1758 if (!isAnyRetainable(TargetClass))
1759 return ACC_invalid;
1760
1761 // Honor an explicit 'not retained' attribute.
1762 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
1763 return ACC_plusZero;
1764
1765 // Honor an explicit 'retained' attribute, except that for
1766 // now we're not going to permit implicit handling of +1 results,
1767 // because it's a bit frightening.
1768 if (fn->hasAttr<CFReturnsRetainedAttr>())
1769 return ACC_invalid; // ACC_plusOne if we start accepting this
1770
1771 // Recognize this specific builtin function, which is used by CFSTR.
1772 unsigned builtinID = fn->getBuiltinID();
1773 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
1774 return ACC_bottom;
1775
1776 // Otherwise, don't do anything implicit with an unaudited function.
1777 if (!fn->hasAttr<CFAuditedTransferAttr>())
1778 return ACC_invalid;
1779
1780 // Otherwise, it's +0 unless it follows the create convention.
1781 if (ento::coreFoundation::followsCreateRule(fn))
1782 return ACC_invalid; // ACC_plusOne if we start accepting this
1783
1784 return ACC_plusZero;
1785 }
1786
1787 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
1788 return checkCallToMethod(e->getMethodDecl());
1789 }
1790
1791 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
1792 ObjCMethodDecl *method;
1793 if (e->isExplicitProperty())
1794 method = e->getExplicitProperty()->getGetterMethodDecl();
1795 else
1796 method = e->getImplicitPropertyGetter();
1797 return checkCallToMethod(method);
1798 }
1799
1800 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
1801 if (!method) return ACC_invalid;
1802
1803 // Check for message sends to functions returning CF types. We
1804 // just obey the Cocoa conventions with these, even though the
1805 // return type is CF.
1806 if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
1807 return ACC_invalid;
1808
1809 // If the method is explicitly marked not-retained, it's +0.
1810 if (method->hasAttr<CFReturnsNotRetainedAttr>())
1811 return ACC_plusZero;
1812
1813 // If the method is explicitly marked as returning retained, or its
1814 // selector follows a +1 Cocoa convention, treat it as +1.
1815 if (method->hasAttr<CFReturnsRetainedAttr>())
1816 return ACC_plusOne;
1817
1818 switch (method->getSelector().getMethodFamily()) {
1819 case OMF_alloc:
1820 case OMF_copy:
1821 case OMF_mutableCopy:
1822 case OMF_new:
1823 return ACC_plusOne;
1824
1825 default:
1826 // Otherwise, treat it as +0.
1827 return ACC_plusZero;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001828 }
1829 }
John McCall2cf031d2011-10-01 01:01:08 +00001830 };
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001831}
1832
John McCallf85e1932011-06-15 23:02:42 +00001833void
1834Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001835 Expr *&castExpr, CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00001836 QualType castExprType = castExpr->getType();
John McCall2cf031d2011-10-01 01:01:08 +00001837
1838 // For the purposes of the classification, we assume reference types
1839 // will bind to temporaries.
1840 QualType effCastType = castType;
1841 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
1842 effCastType = ref->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001843
1844 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
John McCall2cf031d2011-10-01 01:01:08 +00001845 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
John McCallf85e1932011-06-15 23:02:42 +00001846 if (exprACTC == castACTC) return;
John McCall2cf031d2011-10-01 01:01:08 +00001847 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return;
1848
1849 // Allow all of these types to be cast to integer types (but not
1850 // vice-versa).
1851 if (castACTC == ACTC_none && castType->isIntegralType(Context))
1852 return;
John McCallf85e1932011-06-15 23:02:42 +00001853
1854 // Allow casts between pointers to lifetime types (e.g., __strong id*)
1855 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
1856 // must be explicit.
John McCall2cf031d2011-10-01 01:01:08 +00001857 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
1858 return;
1859 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
1860 CCK != CCK_ImplicitConversion)
1861 return;
1862
1863 switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
1864 // For invalid casts, fall through.
1865 case ACC_invalid:
1866 break;
1867
1868 // Do nothing for both bottom and +0.
1869 case ACC_bottom:
1870 case ACC_plusZero:
1871 return;
1872
1873 // If the result is +1, consume it here.
1874 case ACC_plusOne:
1875 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
1876 CK_ARCConsumeObject, castExpr,
1877 0, VK_RValue);
1878 ExprNeedsCleanups = true;
1879 return;
John McCallf85e1932011-06-15 23:02:42 +00001880 }
1881
John McCallf85e1932011-06-15 23:02:42 +00001882 SourceLocation loc =
John McCall2cf031d2011-10-01 01:01:08 +00001883 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCallf85e1932011-06-15 23:02:42 +00001884
1885 if (makeUnavailableInSystemHeader(loc,
John McCall2cf031d2011-10-01 01:01:08 +00001886 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCallf85e1932011-06-15 23:02:42 +00001887 return;
1888
John McCall71c482c2011-06-17 06:50:50 +00001889 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00001890 switch (exprACTC) {
John McCall2cf031d2011-10-01 01:01:08 +00001891 case ACTC_none:
1892 case ACTC_coreFoundation:
1893 case ACTC_voidPtr:
1894 srcKind = (castExprType->isPointerType() ? 1 : 0);
1895 break;
1896 case ACTC_retainable:
1897 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
1898 break;
1899 case ACTC_indirectRetainable:
1900 srcKind = 4;
1901 break;
John McCallf85e1932011-06-15 23:02:42 +00001902 }
1903
1904 if (CCK == CCK_CStyleCast) {
1905 // Check whether this could be fixed with a bridge cast.
1906 SourceLocation AfterLParen = PP.getLocForEndOfToken(castRange.getBegin());
1907 SourceLocation NoteLoc = AfterLParen.isValid()? AfterLParen : loc;
1908
John McCall2cf031d2011-10-01 01:01:08 +00001909 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
John McCallf85e1932011-06-15 23:02:42 +00001910 Diag(loc, diag::err_arc_cast_requires_bridge)
1911 << 2
1912 << castExprType
1913 << (castType->isBlockPointerType()? 1 : 0)
1914 << castType
1915 << castRange
1916 << castExpr->getSourceRange();
1917 Diag(NoteLoc, diag::note_arc_bridge)
1918 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1919 Diag(NoteLoc, diag::note_arc_bridge_transfer)
1920 << castExprType
1921 << FixItHint::CreateInsertion(AfterLParen, "__bridge_transfer ");
1922
1923 return;
1924 }
1925
John McCall2cf031d2011-10-01 01:01:08 +00001926 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
John McCallf85e1932011-06-15 23:02:42 +00001927 Diag(loc, diag::err_arc_cast_requires_bridge)
1928 << (castExprType->isBlockPointerType()? 1 : 0)
1929 << castExprType
1930 << 2
1931 << castType
1932 << castRange
1933 << castExpr->getSourceRange();
1934
1935 Diag(NoteLoc, diag::note_arc_bridge)
1936 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1937 Diag(NoteLoc, diag::note_arc_bridge_retained)
1938 << castType
1939 << FixItHint::CreateInsertion(AfterLParen, "__bridge_retained ");
1940 return;
1941 }
1942 }
1943
1944 Diag(loc, diag::err_arc_mismatched_cast)
1945 << (CCK != CCK_ImplicitConversion) << srcKind << castExprType << castType
1946 << castRange << castExpr->getSourceRange();
1947}
1948
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00001949bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
1950 QualType exprType) {
1951 QualType canCastType =
1952 Context.getCanonicalType(castType).getUnqualifiedType();
1953 QualType canExprType =
1954 Context.getCanonicalType(exprType).getUnqualifiedType();
1955 if (isa<ObjCObjectPointerType>(canCastType) &&
1956 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
1957 canExprType->isObjCObjectPointerType()) {
1958 if (const ObjCObjectPointerType *ObjT =
1959 canExprType->getAs<ObjCObjectPointerType>())
1960 if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
1961 return false;
1962 }
1963 return true;
1964}
1965
John McCall7e5e5f42011-07-07 06:58:02 +00001966/// Look for an ObjCReclaimReturnedObject cast and destroy it.
1967static Expr *maybeUndoReclaimObject(Expr *e) {
1968 // For now, we just undo operands that are *immediately* reclaim
1969 // expressions, which prevents the vast majority of potential
1970 // problems here. To catch them all, we'd need to rebuild arbitrary
1971 // value-propagating subexpressions --- we can't reliably rebuild
1972 // in-place because of expression sharing.
1973 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall33e56f32011-09-10 06:18:15 +00001974 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall7e5e5f42011-07-07 06:58:02 +00001975 return ice->getSubExpr();
1976
1977 return e;
1978}
1979
John McCallf85e1932011-06-15 23:02:42 +00001980ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
1981 ObjCBridgeCastKind Kind,
1982 SourceLocation BridgeKeywordLoc,
1983 TypeSourceInfo *TSInfo,
1984 Expr *SubExpr) {
John McCall4906cf92011-08-26 00:48:42 +00001985 ExprResult SubResult = UsualUnaryConversions(SubExpr);
1986 if (SubResult.isInvalid()) return ExprError();
1987 SubExpr = SubResult.take();
1988
John McCallf85e1932011-06-15 23:02:42 +00001989 QualType T = TSInfo->getType();
1990 QualType FromType = SubExpr->getType();
1991
John McCall1d9b3b22011-09-09 05:25:32 +00001992 CastKind CK;
1993
John McCallf85e1932011-06-15 23:02:42 +00001994 bool MustConsume = false;
1995 if (T->isDependentType() || SubExpr->isTypeDependent()) {
1996 // Okay: we'll build a dependent expression type.
John McCall1d9b3b22011-09-09 05:25:32 +00001997 CK = CK_Dependent;
John McCallf85e1932011-06-15 23:02:42 +00001998 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
1999 // Casting CF -> id
John McCall1d9b3b22011-09-09 05:25:32 +00002000 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
2001 : CK_CPointerToObjCPointerCast);
John McCallf85e1932011-06-15 23:02:42 +00002002 switch (Kind) {
2003 case OBC_Bridge:
2004 break;
2005
2006 case OBC_BridgeRetained:
2007 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2008 << 2
2009 << FromType
2010 << (T->isBlockPointerType()? 1 : 0)
2011 << T
2012 << SubExpr->getSourceRange()
2013 << Kind;
2014 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2015 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
2016 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
2017 << FromType
2018 << FixItHint::CreateReplacement(BridgeKeywordLoc,
2019 "__bridge_transfer ");
2020
2021 Kind = OBC_Bridge;
2022 break;
2023
2024 case OBC_BridgeTransfer:
2025 // We must consume the Objective-C object produced by the cast.
2026 MustConsume = true;
2027 break;
2028 }
2029 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
2030 // Okay: id -> CF
John McCall1d9b3b22011-09-09 05:25:32 +00002031 CK = CK_BitCast;
John McCallf85e1932011-06-15 23:02:42 +00002032 switch (Kind) {
2033 case OBC_Bridge:
John McCall7e5e5f42011-07-07 06:58:02 +00002034 // Reclaiming a value that's going to be __bridge-casted to CF
2035 // is very dangerous, so we don't do it.
2036 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCallf85e1932011-06-15 23:02:42 +00002037 break;
2038
2039 case OBC_BridgeRetained:
2040 // Produce the object before casting it.
2041 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall33e56f32011-09-10 06:18:15 +00002042 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00002043 SubExpr, 0, VK_RValue);
2044 break;
2045
2046 case OBC_BridgeTransfer:
2047 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2048 << (FromType->isBlockPointerType()? 1 : 0)
2049 << FromType
2050 << 2
2051 << T
2052 << SubExpr->getSourceRange()
2053 << Kind;
2054
2055 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2056 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
2057 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
2058 << T
2059 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge_retained ");
2060
2061 Kind = OBC_Bridge;
2062 break;
2063 }
2064 } else {
2065 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
2066 << FromType << T << Kind
2067 << SubExpr->getSourceRange()
2068 << TSInfo->getTypeLoc().getSourceRange();
2069 return ExprError();
2070 }
2071
John McCall1d9b3b22011-09-09 05:25:32 +00002072 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCallf85e1932011-06-15 23:02:42 +00002073 BridgeKeywordLoc,
2074 TSInfo, SubExpr);
2075
2076 if (MustConsume) {
2077 ExprNeedsCleanups = true;
John McCall33e56f32011-09-10 06:18:15 +00002078 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
John McCallf85e1932011-06-15 23:02:42 +00002079 0, VK_RValue);
2080 }
2081
2082 return Result;
2083}
2084
2085ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
2086 SourceLocation LParenLoc,
2087 ObjCBridgeCastKind Kind,
2088 SourceLocation BridgeKeywordLoc,
2089 ParsedType Type,
2090 SourceLocation RParenLoc,
2091 Expr *SubExpr) {
2092 TypeSourceInfo *TSInfo = 0;
2093 QualType T = GetTypeFromParser(Type, &TSInfo);
2094 if (!TSInfo)
2095 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
2096 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
2097 SubExpr);
2098}