blob: 448f145964788ca7e6f5ec0f628574c5068daef1 [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"
Ted Kremenekebcb57a2012-03-06 20:05:56 +000020#include "clang/Edit/Rewriters.h"
21#include "clang/Edit/Commit.h"
Chris Lattner85a932e2008-01-04 22:32:30 +000022#include "clang/AST/ASTContext.h"
23#include "clang/AST/DeclObjC.h"
Steve Narofff494b572008-05-29 21:12:08 +000024#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor2725ca82010-04-21 19:57:20 +000026#include "clang/AST/TypeLoc.h"
Chris Lattner39c28bb2009-02-18 06:48:40 +000027#include "llvm/ADT/SmallString.h"
Steve Naroff61f72cb2009-03-09 21:12:44 +000028#include "clang/Lex/Preprocessor.h"
29
Chris Lattner85a932e2008-01-04 22:32:30 +000030using namespace clang;
John McCall26743b22011-02-03 09:00:02 +000031using namespace sema;
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +000032using llvm::makeArrayRef;
Chris Lattner85a932e2008-01-04 22:32:30 +000033
John McCallf312b1e2010-08-26 23:41:50 +000034ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
35 Expr **strings,
36 unsigned NumStrings) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000037 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
38
Chris Lattnerf4b136f2009-02-18 06:13:04 +000039 // Most ObjC strings are formed out of a single piece. However, we *can*
40 // have strings formed out of multiple @ strings with multiple pptokens in
41 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
42 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner39c28bb2009-02-18 06:48:40 +000043 StringLiteral *S = Strings[0];
Mike Stump1eb44332009-09-09 15:08:12 +000044
Chris Lattnerf4b136f2009-02-18 06:13:04 +000045 // If we have a multi-part string, merge it all together.
46 if (NumStrings != 1) {
Chris Lattner85a932e2008-01-04 22:32:30 +000047 // Concatenate objc strings.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +000048 SmallString<128> StrBuf;
Chris Lattner5f9e2722011-07-23 10:55:15 +000049 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump1eb44332009-09-09 15:08:12 +000050
Chris Lattner726e1682009-02-18 05:49:11 +000051 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000052 S = Strings[i];
Mike Stump1eb44332009-09-09 15:08:12 +000053
Douglas Gregor5cee1192011-07-27 05:40:30 +000054 // ObjC strings can't be wide or UTF.
55 if (!S->isAscii()) {
Chris Lattnerf4b136f2009-02-18 06:13:04 +000056 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
57 << S->getSourceRange();
58 return true;
59 }
Mike Stump1eb44332009-09-09 15:08:12 +000060
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +000061 // Append the string.
62 StrBuf += S->getString();
Mike Stump1eb44332009-09-09 15:08:12 +000063
Chris Lattner39c28bb2009-02-18 06:48:40 +000064 // Get the locations of the string tokens.
65 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattner85a932e2008-01-04 22:32:30 +000066 }
Mike Stump1eb44332009-09-09 15:08:12 +000067
Chris Lattner39c28bb2009-02-18 06:48:40 +000068 // Create the aggregate string with the appropriate content and location
69 // information.
Jay Foad65aa6882011-06-21 15:13:30 +000070 S = StringLiteral::Create(Context, StrBuf,
Douglas Gregor5cee1192011-07-27 05:40:30 +000071 StringLiteral::Ascii, /*Pascal=*/false,
Chris Lattner2085fd62009-02-18 06:40:38 +000072 Context.getPointerType(Context.CharTy),
Chris Lattner39c28bb2009-02-18 06:48:40 +000073 &StrLocs[0], StrLocs.size());
Chris Lattner85a932e2008-01-04 22:32:30 +000074 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +000075
76 return BuildObjCStringLiteral(AtLocs[0], S);
77}
Mike Stump1eb44332009-09-09 15:08:12 +000078
Ted Kremenekebcb57a2012-03-06 20:05:56 +000079ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
Chris Lattner69039812009-02-18 06:01:06 +000080 // Verify that this composite string is acceptable for ObjC strings.
81 if (CheckObjCString(S))
Chris Lattner85a932e2008-01-04 22:32:30 +000082 return true;
Chris Lattnera0af1fe2009-02-18 06:06:56 +000083
84 // Initialize the constant string interface lazily. This assumes
Steve Naroffd9fd7642009-04-07 14:18:33 +000085 // the NSString interface is seen in this translation unit. Note: We
86 // don't use NSConstantString, since the runtime team considers this
87 // interface private (even though it appears in the header files).
Chris Lattnera0af1fe2009-02-18 06:06:56 +000088 QualType Ty = Context.getObjCConstantStringInterface();
89 if (!Ty.isNull()) {
Steve Naroff14108da2009-07-10 23:34:53 +000090 Ty = Context.getObjCObjectPointerType(Ty);
David Blaikie4e4d0842012-03-11 07:00:24 +000091 } else if (getLangOpts().NoConstantCFStrings) {
Fariborz Jahanian4c733072010-10-19 17:19:29 +000092 IdentifierInfo *NSIdent=0;
David Blaikie4e4d0842012-03-11 07:00:24 +000093 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Fariborz Jahanian4c733072010-10-19 17:19:29 +000094
95 if (StringClass.empty())
96 NSIdent = &Context.Idents.get("NSConstantString");
97 else
98 NSIdent = &Context.Idents.get(StringClass);
99
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000100 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Fariborz Jahanian8a437762010-04-23 23:19:04 +0000101 LookupOrdinaryName);
102 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
103 Context.setObjCConstantStringInterface(StrIF);
104 Ty = Context.getObjCConstantStringInterface();
105 Ty = Context.getObjCObjectPointerType(Ty);
106 } else {
107 // If there is no NSConstantString interface defined then treat this
108 // as error and recover from it.
109 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
110 << S->getSourceRange();
111 Ty = Context.getObjCIdType();
112 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000113 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000114 IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000115 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Douglas Gregorc83c6872010-04-15 22:33:43 +0000116 LookupOrdinaryName);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000117 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
118 Context.setObjCConstantStringInterface(StrIF);
119 Ty = Context.getObjCConstantStringInterface();
Steve Naroff14108da2009-07-10 23:34:53 +0000120 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000121 } else {
Fariborz Jahanianf64bc202012-02-23 22:51:36 +0000122 // If there is no NSString interface defined, implicitly declare
123 // a @class NSString; and use that instead. This is to make sure
124 // type of an NSString literal is represented correctly, instead of
125 // being an 'id' type.
126 Ty = Context.getObjCNSStringType();
127 if (Ty.isNull()) {
128 ObjCInterfaceDecl *NSStringIDecl =
129 ObjCInterfaceDecl::Create (Context,
130 Context.getTranslationUnitDecl(),
131 SourceLocation(), NSIdent,
132 0, SourceLocation());
133 Ty = Context.getObjCInterfaceType(NSStringIDecl);
134 Context.setObjCNSStringType(Ty);
135 }
136 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000137 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000138 }
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000140 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
141}
142
143/// \brief Retrieve the NSNumber factory method that should be used to create
144/// an Objective-C literal for the given type.
145static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
146 QualType T, QualType ReturnType,
147 SourceRange Range) {
148 llvm::Optional<NSAPI::NSNumberLiteralMethodKind> Kind
149 = S.NSAPIObj->getNSNumberFactoryMethodKind(T);
150
151 if (!Kind) {
152 S.Diag(Loc, diag::err_invalid_nsnumber_type)
153 << T << Range;
154 return 0;
155 }
156
157 // If we already looked up this method, we're done.
158 if (S.NSNumberLiteralMethods[*Kind])
159 return S.NSNumberLiteralMethods[*Kind];
160
161 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
162 /*Instance=*/false);
163
164 // Look for the appropriate method within NSNumber.
165 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);;
David Blaikie4e4d0842012-03-11 07:00:24 +0000166 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000167 TypeSourceInfo *ResultTInfo = 0;
168 Method = ObjCMethodDecl::Create(S.Context, SourceLocation(), SourceLocation(), Sel,
169 ReturnType,
170 ResultTInfo,
171 S.Context.getTranslationUnitDecl(),
172 false /*Instance*/, false/*isVariadic*/,
173 /*isSynthesized=*/false,
174 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
175 ObjCMethodDecl::Required,
176 false);
177 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
178 SourceLocation(), SourceLocation(),
179 &S.Context.Idents.get("value"),
180 T, /*TInfo=*/0, SC_None, SC_None, 0);
181 Method->setMethodParams(S.Context, value, ArrayRef<SourceLocation>());
182 }
183
184 if (!Method) {
185 S.Diag(Loc, diag::err_undeclared_nsnumber_method) << Sel;
186 return 0;
187 }
188
189 // Make sure the return type is reasonable.
190 if (!Method->getResultType()->isObjCObjectPointerType()) {
191 S.Diag(Loc, diag::err_objc_literal_method_sig)
192 << Sel;
193 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
194 << Method->getResultType();
195 return 0;
196 }
197
198 // Note: if the parameter type is out-of-line, we'll catch it later in the
199 // implicit conversion.
200
201 S.NSNumberLiteralMethods[*Kind] = Method;
202 return Method;
203}
204
205/// BuildObjCNumericLiteral - builds an ObjCNumericLiteral AST node for the
206/// numeric literal expression. Type of the expression will be "NSNumber *"
207/// or "id" if NSNumber is unavailable.
208ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
209 // Look up the NSNumber class, if we haven't done so already.
210 if (!NSNumberDecl) {
211 NamedDecl *IF = LookupSingleName(TUScope,
212 NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber),
213 AtLoc, LookupOrdinaryName);
214 NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
215
David Blaikie4e4d0842012-03-11 07:00:24 +0000216 if (!NSNumberDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000217 NSNumberDecl = ObjCInterfaceDecl::Create (Context,
218 Context.getTranslationUnitDecl(),
219 SourceLocation(),
220 NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber),
221 0, SourceLocation());
222 if (!NSNumberDecl) {
223 Diag(AtLoc, diag::err_undeclared_nsnumber);
224 return ExprError();
225 }
226 }
227
228 // Determine the type of the literal.
229 QualType NumberType = Number->getType();
230 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
231 // In C, character literals have type 'int'. That's not the type we want
232 // to use to determine the Objective-c literal kind.
233 switch (Char->getKind()) {
234 case CharacterLiteral::Ascii:
235 NumberType = Context.CharTy;
236 break;
237
238 case CharacterLiteral::Wide:
239 NumberType = Context.getWCharType();
240 break;
241
242 case CharacterLiteral::UTF16:
243 NumberType = Context.Char16Ty;
244 break;
245
246 case CharacterLiteral::UTF32:
247 NumberType = Context.Char32Ty;
248 break;
249 }
250 }
251
252 ObjCMethodDecl *Method = 0;
253 // Look for the appropriate method within NSNumber.
254 // Construct the literal.
255 QualType Ty
256 = Context.getObjCObjectPointerType(
257 Context.getObjCInterfaceType(NSNumberDecl));
258 Method = getNSNumberFactoryMethod(*this, AtLoc,
259 NumberType, Ty,
260 Number->getSourceRange());
261
262 if (!Method)
263 return ExprError();
264
265 // Convert the number to the type that the parameter expects.
266 QualType ElementT = Method->param_begin()[0]->getType();
267 ExprResult ConvertedNumber = PerformImplicitConversion(Number, ElementT,
268 AA_Sending);
269 if (ConvertedNumber.isInvalid())
270 return ExprError();
271 Number = ConvertedNumber.get();
272
273 return MaybeBindToTemporary(
274 new (Context) ObjCNumericLiteral(Number, Ty, Method, AtLoc));
275}
276
277ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
278 SourceLocation ValueLoc,
279 bool Value) {
280 ExprResult Inner;
David Blaikie4e4d0842012-03-11 07:00:24 +0000281 if (getLangOpts().CPlusPlus) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000282 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
283 } else {
284 // C doesn't actually have a way to represent literal values of type
285 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
286 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
287 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
288 CK_IntegralToBoolean);
289 }
290
291 return BuildObjCNumericLiteral(AtLoc, Inner.get());
292}
293
294/// \brief Check that the given expression is a valid element of an Objective-C
295/// collection literal.
296static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
297 QualType T) {
298 // If the expression is type-dependent, there's nothing for us to do.
299 if (Element->isTypeDependent())
300 return Element;
301
302 ExprResult Result = S.CheckPlaceholderExpr(Element);
303 if (Result.isInvalid())
304 return ExprError();
305 Element = Result.get();
306
307 // In C++, check for an implicit conversion to an Objective-C object pointer
308 // type.
David Blaikie4e4d0842012-03-11 07:00:24 +0000309 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000310 InitializedEntity Entity
311 = InitializedEntity::InitializeParameter(S.Context, T, /*Consumed=*/false);
312 InitializationKind Kind
313 = InitializationKind::CreateCopy(Element->getLocStart(), SourceLocation());
314 InitializationSequence Seq(S, Entity, Kind, &Element, 1);
315 if (!Seq.Failed())
316 return Seq.Perform(S, Entity, Kind, MultiExprArg(S, &Element, 1));
317 }
318
319 Expr *OrigElement = Element;
320
321 // Perform lvalue-to-rvalue conversion.
322 Result = S.DefaultLvalueConversion(Element);
323 if (Result.isInvalid())
324 return ExprError();
325 Element = Result.get();
326
327 // Make sure that we have an Objective-C pointer type or block.
328 if (!Element->getType()->isObjCObjectPointerType() &&
329 !Element->getType()->isBlockPointerType()) {
330 bool Recovered = false;
331
332 // If this is potentially an Objective-C numeric literal, add the '@'.
333 if (isa<IntegerLiteral>(OrigElement) ||
334 isa<CharacterLiteral>(OrigElement) ||
335 isa<FloatingLiteral>(OrigElement) ||
336 isa<ObjCBoolLiteralExpr>(OrigElement) ||
337 isa<CXXBoolLiteralExpr>(OrigElement)) {
338 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
339 int Which = isa<CharacterLiteral>(OrigElement) ? 1
340 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
341 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
342 : 3;
343
344 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
345 << Which << OrigElement->getSourceRange()
346 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
347
348 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
349 OrigElement);
350 if (Result.isInvalid())
351 return ExprError();
352
353 Element = Result.get();
354 Recovered = true;
355 }
356 }
357 // If this is potentially an Objective-C string literal, add the '@'.
358 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
359 if (String->isAscii()) {
360 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
361 << 0 << OrigElement->getSourceRange()
362 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
363
364 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
365 if (Result.isInvalid())
366 return ExprError();
367
368 Element = Result.get();
369 Recovered = true;
370 }
371 }
372
373 if (!Recovered) {
374 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
375 << Element->getType();
376 return ExprError();
377 }
378 }
379
380 // Make sure that the element has the type that the container factory
381 // function expects.
382 return S.PerformCopyInitialization(
383 InitializedEntity::InitializeParameter(S.Context, T,
384 /*Consumed=*/false),
385 Element->getLocStart(), Element);
386}
387
388ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
389 Expr *IndexExpr,
390 ObjCMethodDecl *getterMethod,
391 ObjCMethodDecl *setterMethod) {
392 // Feature support is for modern abi.
393 if (!LangOpts.ObjCNonFragileABI)
394 return ExprError();
395 // If the expression is type-dependent, there's nothing for us to do.
396 assert ((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
397 "base or index cannot have dependent type here");
398 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
399 if (Result.isInvalid())
400 return ExprError();
401 IndexExpr = Result.get();
402
403 // Perform lvalue-to-rvalue conversion.
404 Result = DefaultLvalueConversion(BaseExpr);
405 if (Result.isInvalid())
406 return ExprError();
407 BaseExpr = Result.get();
408 return Owned(ObjCSubscriptRefExpr::Create(Context,
409 BaseExpr,
410 IndexExpr,
411 Context.PseudoObjectTy,
412 getterMethod,
413 setterMethod, RB));
414
415}
416
417ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
418 // Look up the NSArray class, if we haven't done so already.
419 if (!NSArrayDecl) {
420 NamedDecl *IF = LookupSingleName(TUScope,
421 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
422 SR.getBegin(),
423 LookupOrdinaryName);
424 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikie4e4d0842012-03-11 07:00:24 +0000425 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000426 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
427 Context.getTranslationUnitDecl(),
428 SourceLocation(),
429 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
430 0, SourceLocation());
431
432 if (!NSArrayDecl) {
433 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
434 return ExprError();
435 }
436 }
437
438 // Find the arrayWithObjects:count: method, if we haven't done so already.
439 QualType IdT = Context.getObjCIdType();
440 if (!ArrayWithObjectsMethod) {
441 Selector
442 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
443 ArrayWithObjectsMethod = NSArrayDecl->lookupClassMethod(Sel);
David Blaikie4e4d0842012-03-11 07:00:24 +0000444 if (!ArrayWithObjectsMethod && getLangOpts().DebuggerObjCLiteral) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000445 TypeSourceInfo *ResultTInfo = 0;
446 ArrayWithObjectsMethod =
447 ObjCMethodDecl::Create(Context,
448 SourceLocation(), SourceLocation(), Sel,
449 IdT,
450 ResultTInfo,
451 Context.getTranslationUnitDecl(),
452 false /*Instance*/, false/*isVariadic*/,
453 /*isSynthesized=*/false,
454 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
455 ObjCMethodDecl::Required,
456 false);
457 SmallVector<ParmVarDecl *, 2> Params;
458 ParmVarDecl *objects = ParmVarDecl::Create(Context, ArrayWithObjectsMethod,
459 SourceLocation(), SourceLocation(),
460 &Context.Idents.get("objects"),
461 Context.getPointerType(IdT),
462 /*TInfo=*/0,
463 SC_None,
464 SC_None,
465 0);
466 Params.push_back(objects);
467 ParmVarDecl *cnt = ParmVarDecl::Create(Context, ArrayWithObjectsMethod,
468 SourceLocation(), SourceLocation(),
469 &Context.Idents.get("cnt"),
470 Context.UnsignedLongTy,
471 /*TInfo=*/0,
472 SC_None,
473 SC_None,
474 0);
475 Params.push_back(cnt);
476 ArrayWithObjectsMethod->setMethodParams(Context, Params,
477 ArrayRef<SourceLocation>());
478
479
480 }
481
482 if (!ArrayWithObjectsMethod) {
483 Diag(SR.getBegin(), diag::err_undeclared_arraywithobjects) << Sel;
484 return ExprError();
485 }
486 }
487
488 // Make sure the return type is reasonable.
489 if (!ArrayWithObjectsMethod->getResultType()->isObjCObjectPointerType()) {
490 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
491 << ArrayWithObjectsMethod->getSelector();
492 Diag(ArrayWithObjectsMethod->getLocation(),
493 diag::note_objc_literal_method_return)
494 << ArrayWithObjectsMethod->getResultType();
495 return ExprError();
496 }
497
498 // Dig out the type that all elements should be converted to.
499 QualType T = ArrayWithObjectsMethod->param_begin()[0]->getType();
500 const PointerType *PtrT = T->getAs<PointerType>();
501 if (!PtrT ||
502 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
503 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
504 << ArrayWithObjectsMethod->getSelector();
505 Diag(ArrayWithObjectsMethod->param_begin()[0]->getLocation(),
506 diag::note_objc_literal_method_param)
507 << 0 << T
508 << Context.getPointerType(IdT.withConst());
509 return ExprError();
510 }
511 T = PtrT->getPointeeType();
512
513 // Check that the 'count' parameter is integral.
514 if (!ArrayWithObjectsMethod->param_begin()[1]->getType()->isIntegerType()) {
515 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
516 << ArrayWithObjectsMethod->getSelector();
517 Diag(ArrayWithObjectsMethod->param_begin()[1]->getLocation(),
518 diag::note_objc_literal_method_param)
519 << 1
520 << ArrayWithObjectsMethod->param_begin()[1]->getType()
521 << "integral";
522 return ExprError();
523 }
524
525 // Check that each of the elements provided is valid in a collection literal,
526 // performing conversions as necessary.
527 Expr **ElementsBuffer = Elements.get();
528 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
529 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
530 ElementsBuffer[I],
531 T);
532 if (Converted.isInvalid())
533 return ExprError();
534
535 ElementsBuffer[I] = Converted.get();
536 }
537
538 QualType Ty
539 = Context.getObjCObjectPointerType(
540 Context.getObjCInterfaceType(NSArrayDecl));
541
542 return MaybeBindToTemporary(
543 ObjCArrayLiteral::Create(Context,
544 llvm::makeArrayRef(Elements.get(),
545 Elements.size()),
546 Ty, ArrayWithObjectsMethod, SR));
547}
548
549ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
550 ObjCDictionaryElement *Elements,
551 unsigned NumElements) {
552 // Look up the NSDictionary class, if we haven't done so already.
553 if (!NSDictionaryDecl) {
554 NamedDecl *IF = LookupSingleName(TUScope,
555 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
556 SR.getBegin(), LookupOrdinaryName);
557 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikie4e4d0842012-03-11 07:00:24 +0000558 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000559 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
560 Context.getTranslationUnitDecl(),
561 SourceLocation(),
562 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
563 0, SourceLocation());
564
565 if (!NSDictionaryDecl) {
566 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
567 return ExprError();
568 }
569 }
570
571 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
572 // so already.
573 QualType IdT = Context.getObjCIdType();
574 if (!DictionaryWithObjectsMethod) {
575 Selector Sel = NSAPIObj->getNSDictionarySelector(
576 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
577 DictionaryWithObjectsMethod = NSDictionaryDecl->lookupClassMethod(Sel);
David Blaikie4e4d0842012-03-11 07:00:24 +0000578 if (!DictionaryWithObjectsMethod && getLangOpts().DebuggerObjCLiteral) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000579 DictionaryWithObjectsMethod =
580 ObjCMethodDecl::Create(Context,
581 SourceLocation(), SourceLocation(), Sel,
582 IdT,
583 0 /*TypeSourceInfo */,
584 Context.getTranslationUnitDecl(),
585 false /*Instance*/, false/*isVariadic*/,
586 /*isSynthesized=*/false,
587 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
588 ObjCMethodDecl::Required,
589 false);
590 SmallVector<ParmVarDecl *, 3> Params;
591 ParmVarDecl *objects = ParmVarDecl::Create(Context, DictionaryWithObjectsMethod,
592 SourceLocation(), SourceLocation(),
593 &Context.Idents.get("objects"),
594 Context.getPointerType(IdT),
595 /*TInfo=*/0,
596 SC_None,
597 SC_None,
598 0);
599 Params.push_back(objects);
600 ParmVarDecl *keys = ParmVarDecl::Create(Context, DictionaryWithObjectsMethod,
601 SourceLocation(), SourceLocation(),
602 &Context.Idents.get("keys"),
603 Context.getPointerType(IdT),
604 /*TInfo=*/0,
605 SC_None,
606 SC_None,
607 0);
608 Params.push_back(keys);
609 ParmVarDecl *cnt = ParmVarDecl::Create(Context, DictionaryWithObjectsMethod,
610 SourceLocation(), SourceLocation(),
611 &Context.Idents.get("cnt"),
612 Context.UnsignedLongTy,
613 /*TInfo=*/0,
614 SC_None,
615 SC_None,
616 0);
617 Params.push_back(cnt);
618 DictionaryWithObjectsMethod->setMethodParams(Context, Params,
619 ArrayRef<SourceLocation>());
620 }
621
622 if (!DictionaryWithObjectsMethod) {
623 Diag(SR.getBegin(), diag::err_undeclared_dictwithobjects) << Sel;
624 return ExprError();
625 }
626 }
627
628 // Make sure the return type is reasonable.
629 if (!DictionaryWithObjectsMethod->getResultType()->isObjCObjectPointerType()){
630 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
631 << DictionaryWithObjectsMethod->getSelector();
632 Diag(DictionaryWithObjectsMethod->getLocation(),
633 diag::note_objc_literal_method_return)
634 << DictionaryWithObjectsMethod->getResultType();
635 return ExprError();
636 }
637
638 // Dig out the type that all values should be converted to.
639 QualType ValueT = DictionaryWithObjectsMethod->param_begin()[0]->getType();
640 const PointerType *PtrValue = ValueT->getAs<PointerType>();
641 if (!PtrValue ||
642 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
643 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
644 << DictionaryWithObjectsMethod->getSelector();
645 Diag(DictionaryWithObjectsMethod->param_begin()[0]->getLocation(),
646 diag::note_objc_literal_method_param)
647 << 0 << ValueT
648 << Context.getPointerType(IdT.withConst());
649 return ExprError();
650 }
651 ValueT = PtrValue->getPointeeType();
652
653 // Dig out the type that all keys should be converted to.
654 QualType KeyT = DictionaryWithObjectsMethod->param_begin()[1]->getType();
655 const PointerType *PtrKey = KeyT->getAs<PointerType>();
656 if (!PtrKey ||
657 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
658 IdT)) {
659 bool err = true;
660 if (PtrKey) {
661 if (QIDNSCopying.isNull()) {
662 // key argument of selector is id<NSCopying>?
663 if (ObjCProtocolDecl *NSCopyingPDecl =
664 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
665 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
666 QIDNSCopying =
667 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
668 (ObjCProtocolDecl**) PQ,1);
669 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
670 }
671 }
672 if (!QIDNSCopying.isNull())
673 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
674 QIDNSCopying);
675 }
676
677 if (err) {
678 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
679 << DictionaryWithObjectsMethod->getSelector();
680 Diag(DictionaryWithObjectsMethod->param_begin()[1]->getLocation(),
681 diag::note_objc_literal_method_param)
682 << 1 << KeyT
683 << Context.getPointerType(IdT.withConst());
684 return ExprError();
685 }
686 }
687 KeyT = PtrKey->getPointeeType();
688
689 // Check that the 'count' parameter is integral.
690 if (!DictionaryWithObjectsMethod->param_begin()[2]->getType()
691 ->isIntegerType()) {
692 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
693 << DictionaryWithObjectsMethod->getSelector();
694 Diag(DictionaryWithObjectsMethod->param_begin()[2]->getLocation(),
695 diag::note_objc_literal_method_param)
696 << 2
697 << DictionaryWithObjectsMethod->param_begin()[2]->getType()
698 << "integral";
699 return ExprError();
700 }
701
702 // Check that each of the keys and values provided is valid in a collection
703 // literal, performing conversions as necessary.
704 bool HasPackExpansions = false;
705 for (unsigned I = 0, N = NumElements; I != N; ++I) {
706 // Check the key.
707 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
708 KeyT);
709 if (Key.isInvalid())
710 return ExprError();
711
712 // Check the value.
713 ExprResult Value
714 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
715 if (Value.isInvalid())
716 return ExprError();
717
718 Elements[I].Key = Key.get();
719 Elements[I].Value = Value.get();
720
721 if (Elements[I].EllipsisLoc.isInvalid())
722 continue;
723
724 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
725 !Elements[I].Value->containsUnexpandedParameterPack()) {
726 Diag(Elements[I].EllipsisLoc,
727 diag::err_pack_expansion_without_parameter_packs)
728 << SourceRange(Elements[I].Key->getLocStart(),
729 Elements[I].Value->getLocEnd());
730 return ExprError();
731 }
732
733 HasPackExpansions = true;
734 }
735
736
737 QualType Ty
738 = Context.getObjCObjectPointerType(
739 Context.getObjCInterfaceType(NSDictionaryDecl));
740 return MaybeBindToTemporary(
741 ObjCDictionaryLiteral::Create(Context,
742 llvm::makeArrayRef(Elements,
743 NumElements),
744 HasPackExpansions,
745 Ty,
746 DictionaryWithObjectsMethod, SR));
Chris Lattner85a932e2008-01-04 22:32:30 +0000747}
748
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000749ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregor81d34662010-04-20 15:39:42 +0000750 TypeSourceInfo *EncodedTypeInfo,
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000751 SourceLocation RParenLoc) {
Douglas Gregor81d34662010-04-20 15:39:42 +0000752 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000753 QualType StrTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000754 if (EncodedType->isDependentType())
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000755 StrTy = Context.DependentTy;
756 else {
Fariborz Jahanian6c916152011-06-16 22:34:44 +0000757 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
758 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000759 if (RequireCompleteType(AtLoc, EncodedType,
760 PDiag(diag::err_incomplete_type_objc_at_encode)
761 << EncodedTypeInfo->getTypeLoc().getSourceRange()))
762 return ExprError();
763
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000764 std::string Str;
765 Context.getObjCEncodingForType(EncodedType, Str);
766
767 // The type of @encode is the same as the type of the corresponding string,
768 // which is an array type.
769 StrTy = Context.CharTy;
770 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikie4e4d0842012-03-11 07:00:24 +0000771 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000772 StrTy.addConst();
773 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
774 ArrayType::Normal, 0);
775 }
Mike Stump1eb44332009-09-09 15:08:12 +0000776
Douglas Gregor81d34662010-04-20 15:39:42 +0000777 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000778}
779
John McCallf312b1e2010-08-26 23:41:50 +0000780ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
781 SourceLocation EncodeLoc,
782 SourceLocation LParenLoc,
783 ParsedType ty,
784 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000785 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000786 TypeSourceInfo *TInfo;
787 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
788 if (!TInfo)
789 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
790 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000791
Douglas Gregor81d34662010-04-20 15:39:42 +0000792 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000793}
794
John McCallf312b1e2010-08-26 23:41:50 +0000795ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
796 SourceLocation AtLoc,
797 SourceLocation SelLoc,
798 SourceLocation LParenLoc,
799 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000800 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000801 SourceRange(LParenLoc, RParenLoc), false, false);
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +0000802 if (!Method)
803 Method = LookupFactoryMethodInGlobalPool(Sel,
804 SourceRange(LParenLoc, RParenLoc));
805 if (!Method)
806 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian4c91d892011-07-13 19:05:43 +0000807
808 if (!Method ||
809 Method->getImplementationControl() != ObjCMethodDecl::Optional) {
810 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
811 = ReferencedSelectors.find(Sel);
812 if (Pos == ReferencedSelectors.end())
813 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
814 }
Fariborz Jahanian3fe10412010-07-22 18:24:20 +0000815
John McCallf85e1932011-06-15 23:02:42 +0000816 // In ARC, forbid the user from using @selector for
817 // retain/release/autorelease/dealloc/retainCount.
David Blaikie4e4d0842012-03-11 07:00:24 +0000818 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +0000819 switch (Sel.getMethodFamily()) {
820 case OMF_retain:
821 case OMF_release:
822 case OMF_autorelease:
823 case OMF_retainCount:
824 case OMF_dealloc:
825 Diag(AtLoc, diag::err_arc_illegal_selector) <<
826 Sel << SourceRange(LParenLoc, RParenLoc);
827 break;
828
829 case OMF_None:
830 case OMF_alloc:
831 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +0000832 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +0000833 case OMF_init:
834 case OMF_mutableCopy:
835 case OMF_new:
836 case OMF_self:
Fariborz Jahanian9670e172011-07-05 22:38:59 +0000837 case OMF_performSelector:
John McCallf85e1932011-06-15 23:02:42 +0000838 break;
839 }
840 }
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000841 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000842 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000843}
844
John McCallf312b1e2010-08-26 23:41:50 +0000845ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
846 SourceLocation AtLoc,
847 SourceLocation ProtoLoc,
848 SourceLocation LParenLoc,
849 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000850 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000851 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000852 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000853 return true;
854 }
Mike Stump1eb44332009-09-09 15:08:12 +0000855
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000856 QualType Ty = Context.getObjCProtoType();
857 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000858 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000859 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000860 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000861}
862
John McCall26743b22011-02-03 09:00:02 +0000863/// Try to capture an implicit reference to 'self'.
Eli Friedmanb942cb22012-02-03 22:47:37 +0000864ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
865 DeclContext *DC = getFunctionLevelDeclContext();
John McCall26743b22011-02-03 09:00:02 +0000866
867 // If we're not in an ObjC method, error out. Note that, unlike the
868 // C++ case, we don't require an instance method --- class methods
869 // still have a 'self', and we really do still need to capture it!
870 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
871 if (!method)
872 return 0;
873
Douglas Gregor999713e2012-02-18 09:37:24 +0000874 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall26743b22011-02-03 09:00:02 +0000875
876 return method;
877}
878
Douglas Gregor5c16d632011-09-09 20:05:21 +0000879static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
880 if (T == Context.getObjCInstanceType())
881 return Context.getObjCIdType();
882
883 return T;
884}
885
Douglas Gregor926df6c2011-06-11 01:09:30 +0000886QualType Sema::getMessageSendResultType(QualType ReceiverType,
887 ObjCMethodDecl *Method,
888 bool isClassMessage, bool isSuperMessage) {
889 assert(Method && "Must have a method");
890 if (!Method->hasRelatedResultType())
891 return Method->getSendResultType();
892
893 // If a method has a related return type:
894 // - if the method found is an instance method, but the message send
895 // was a class message send, T is the declared return type of the method
896 // found
897 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor5c16d632011-09-09 20:05:21 +0000898 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000899
900 // - if the receiver is super, T is a pointer to the class of the
901 // enclosing method definition
902 if (isSuperMessage) {
903 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
904 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
905 return Context.getObjCObjectPointerType(
906 Context.getObjCInterfaceType(Class));
907 }
908
909 // - if the receiver is the name of a class U, T is a pointer to U
910 if (ReceiverType->getAs<ObjCInterfaceType>() ||
911 ReceiverType->isObjCQualifiedInterfaceType())
912 return Context.getObjCObjectPointerType(ReceiverType);
913 // - if the receiver is of type Class or qualified Class type,
914 // T is the declared return type of the method.
915 if (ReceiverType->isObjCClassType() ||
916 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor5c16d632011-09-09 20:05:21 +0000917 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000918
919 // - if the receiver is id, qualified id, Class, or qualified Class, T
920 // is the receiver type, otherwise
921 // - T is the type of the receiver expression.
922 return ReceiverType;
923}
John McCall26743b22011-02-03 09:00:02 +0000924
Douglas Gregor926df6c2011-06-11 01:09:30 +0000925void Sema::EmitRelatedResultTypeNote(const Expr *E) {
926 E = E->IgnoreParenImpCasts();
927 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
928 if (!MsgSend)
929 return;
930
931 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
932 if (!Method)
933 return;
934
935 if (!Method->hasRelatedResultType())
936 return;
937
938 if (Context.hasSameUnqualifiedType(Method->getResultType()
939 .getNonReferenceType(),
940 MsgSend->getType()))
941 return;
942
Douglas Gregore97179c2011-09-08 01:46:34 +0000943 if (!Context.hasSameUnqualifiedType(Method->getResultType(),
944 Context.getObjCInstanceType()))
945 return;
946
Douglas Gregor926df6c2011-06-11 01:09:30 +0000947 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
948 << Method->isInstanceMethod() << Method->getSelector()
949 << MsgSend->getType();
950}
951
952bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
953 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000954 Selector Sel, ObjCMethodDecl *Method,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000955 bool isClassMessage, bool isSuperMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000956 SourceLocation lbrac, SourceLocation rbrac,
John McCallf89e55a2010-11-18 06:31:45 +0000957 QualType &ReturnType, ExprValueKind &VK) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000958 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000959 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000960 for (unsigned i = 0; i != NumArgs; i++) {
961 if (Args[i]->isTypeDependent())
962 continue;
963
John Wiegley429bb272011-04-08 18:41:53 +0000964 ExprResult Result = DefaultArgumentPromotion(Args[i]);
965 if (Result.isInvalid())
966 return true;
967 Args[i] = Result.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000968 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000969
John McCallf85e1932011-06-15 23:02:42 +0000970 unsigned DiagID;
David Blaikie4e4d0842012-03-11 07:00:24 +0000971 if (getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +0000972 DiagID = diag::err_arc_method_not_found;
973 else
974 DiagID = isClassMessage ? diag::warn_class_method_not_found
975 : diag::warn_inst_method_not_found;
David Blaikie4e4d0842012-03-11 07:00:24 +0000976 if (!getLangOpts().DebuggerSupport)
John McCall819e7452011-08-31 20:57:36 +0000977 Diag(lbrac, DiagID)
978 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
John McCall48218c62011-07-13 17:56:40 +0000979
980 // In debuggers, we want to use __unknown_anytype for these
981 // results so that clients can cast them.
David Blaikie4e4d0842012-03-11 07:00:24 +0000982 if (getLangOpts().DebuggerSupport) {
John McCall48218c62011-07-13 17:56:40 +0000983 ReturnType = Context.UnknownAnyTy;
984 } else {
985 ReturnType = Context.getObjCIdType();
986 }
John McCallf89e55a2010-11-18 06:31:45 +0000987 VK = VK_RValue;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000988 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000989 }
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Douglas Gregor926df6c2011-06-11 01:09:30 +0000991 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
992 isSuperMessage);
John McCallf89e55a2010-11-18 06:31:45 +0000993 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump1eb44332009-09-09 15:08:12 +0000994
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000995 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000996 // Method might have more arguments than selector indicates. This is due
997 // to addition of c-style arguments in method.
998 if (Method->param_size() > Sel.getNumArgs())
999 NumNamedArgs = Method->param_size();
1000 // FIXME. This need be cleaned up.
1001 if (NumArgs < NumNamedArgs) {
John McCallf89e55a2010-11-18 06:31:45 +00001002 Diag(lbrac, diag::err_typecheck_call_too_few_args)
1003 << 2 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +00001004 return false;
1005 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001006
Chris Lattner312531a2009-04-12 08:11:20 +00001007 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001008 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001009 // We can't do any type-checking on a type-dependent argument.
1010 if (Args[i]->isTypeDependent())
1011 continue;
1012
Chris Lattner85a932e2008-01-04 22:32:30 +00001013 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +00001014
John McCall5acb0c92011-10-17 18:40:02 +00001015 ParmVarDecl *param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +00001016 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +00001017
John McCall5acb0c92011-10-17 18:40:02 +00001018 // Strip the unbridged-cast placeholder expression off unless it's
1019 // a consumed argument.
1020 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1021 !param->hasAttr<CFConsumedAttr>())
1022 argExpr = stripARCUnbridgedCast(argExpr);
1023
Douglas Gregor688fc9b2010-04-21 23:24:10 +00001024 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall5acb0c92011-10-17 18:40:02 +00001025 param->getType(),
Douglas Gregor688fc9b2010-04-21 23:24:10 +00001026 PDiag(diag::err_call_incomplete_argument)
1027 << argExpr->getSourceRange()))
1028 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +00001029
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001030 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall5acb0c92011-10-17 18:40:02 +00001031 param);
John McCall3fa5cae2010-10-26 07:05:15 +00001032 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +00001033 if (ArgE.isInvalid())
1034 IsError = true;
1035 else
1036 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +00001037 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001038
1039 // Promote additional arguments to variadic methods.
1040 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001041 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
1042 if (Args[i]->isTypeDependent())
1043 continue;
1044
John Wiegley429bb272011-04-08 18:41:53 +00001045 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
1046 IsError |= Arg.isInvalid();
1047 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +00001048 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001049 } else {
1050 // Check for extra arguments to non-variadic methods.
1051 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001052 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001053 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001054 << 2 /*method*/ << NumNamedArgs << NumArgs
1055 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001056 << SourceRange(Args[NumNamedArgs]->getLocStart(),
1057 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001058 }
1059 }
1060
Douglas Gregor2725ca82010-04-21 19:57:20 +00001061 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001062
1063 // Do additional checkings on method.
1064 IsError |= CheckObjCMethodCall(Method, lbrac, Args, NumArgs);
1065
Chris Lattner312531a2009-04-12 08:11:20 +00001066 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +00001067}
1068
Douglas Gregorc737acb2011-09-27 16:10:05 +00001069bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +00001070 // 'self' is objc 'self' in an objc method only.
John McCall4b9c2d22011-11-06 09:01:30 +00001071 ObjCMethodDecl *method =
1072 dyn_cast<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1073 if (!method) return false;
1074
John McCallf85e1932011-06-15 23:02:42 +00001075 receiver = receiver->IgnoreParenLValueCasts();
1076 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCall4b9c2d22011-11-06 09:01:30 +00001077 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregorc737acb2011-09-27 16:10:05 +00001078 return true;
1079 return false;
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001080}
1081
Steve Narofff1afaf62009-02-26 15:55:06 +00001082// Helper method for ActOnClassMethod/ActOnInstanceMethod.
1083// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +00001084// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +00001085// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +00001086ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +00001087 ObjCInterfaceDecl *ClassDecl) {
1088 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +00001089 // lookup in class and all superclasses
1090 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001091 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001092 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001093
Steve Naroff5609ec02009-03-08 18:56:13 +00001094 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00001095 if (!Method)
1096 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Steve Naroff5609ec02009-03-08 18:56:13 +00001098 // Before we give up, check if the selector is an instance method.
1099 // But only in the root. This matches gcc's behaviour and what the
1100 // runtime expects.
1101 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001102 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001103 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +00001104 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +00001105 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +00001106 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1107 }
Mike Stump1eb44332009-09-09 15:08:12 +00001108
Steve Naroff5609ec02009-03-08 18:56:13 +00001109 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +00001110 }
Steve Naroff5609ec02009-03-08 18:56:13 +00001111 return Method;
1112}
1113
1114ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
1115 ObjCInterfaceDecl *ClassDecl) {
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00001116 if (!ClassDecl->hasDefinition())
1117 return 0;
1118
Steve Naroff5609ec02009-03-08 18:56:13 +00001119 ObjCMethodDecl *Method = 0;
1120 while (ClassDecl && !Method) {
1121 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001122 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001123 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Steve Naroff5609ec02009-03-08 18:56:13 +00001125 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00001126 if (!Method)
1127 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +00001128 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +00001129 }
Steve Narofff1afaf62009-02-26 15:55:06 +00001130 return Method;
1131}
1132
John McCall3c3b7f92011-10-25 17:37:35 +00001133/// LookupMethodInType - Look up a method in an ObjCObjectType.
1134ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1135 bool isInstance) {
1136 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1137 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1138 // Look it up in the main interface (and categories, etc.)
1139 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1140 return method;
1141
1142 // Okay, look for "private" methods declared in any
1143 // @implementations we've seen.
1144 if (isInstance) {
1145 if (ObjCMethodDecl *method = LookupPrivateInstanceMethod(sel, iface))
1146 return method;
1147 } else {
1148 if (ObjCMethodDecl *method = LookupPrivateClassMethod(sel, iface))
1149 return method;
1150 }
1151 }
1152
1153 // Check qualifiers.
1154 for (ObjCObjectType::qual_iterator
1155 i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i)
1156 if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance))
1157 return method;
1158
1159 return 0;
1160}
1161
Fariborz Jahanian61478062011-03-09 20:18:06 +00001162/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1163/// list of a qualified objective pointer type.
1164ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1165 const ObjCObjectPointerType *OPT,
1166 bool Instance)
1167{
1168 ObjCMethodDecl *MD = 0;
1169 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1170 E = OPT->qual_end(); I != E; ++I) {
1171 ObjCProtocolDecl *PROTO = (*I);
1172 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1173 return MD;
1174 }
1175 }
1176 return 0;
1177}
1178
Chris Lattner7f816522010-04-11 07:45:24 +00001179/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1180/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001181ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +00001182HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001183 Expr *BaseExpr, SourceLocation OpLoc,
1184 DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001185 SourceLocation MemberLoc,
1186 SourceLocation SuperLoc, QualType SuperType,
1187 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +00001188 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1189 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +00001190
1191 if (MemberName.getNameKind() != DeclarationName::Identifier) {
1192 Diag(MemberLoc, diag::err_invalid_property_name)
1193 << MemberName << QualType(OPT, 0);
1194 return ExprError();
1195 }
1196
Chris Lattner7f816522010-04-11 07:45:24 +00001197 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregorb3029962011-11-14 22:10:01 +00001198 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1199 : BaseExpr->getSourceRange();
1200 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
1201 PDiag(diag::err_property_not_found_forward_class)
1202 << MemberName << BaseRange))
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +00001203 return ExprError();
Douglas Gregorb3029962011-11-14 22:10:01 +00001204
Chris Lattner7f816522010-04-11 07:45:24 +00001205 // Search for a declared property first.
1206 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
1207 // Check whether we can reference this property.
1208 if (DiagnoseUseOfDecl(PD, MemberLoc))
1209 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +00001210
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001211 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +00001212 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001213 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001214 MemberLoc,
1215 SuperLoc, SuperType));
1216 else
John McCall3c3b7f92011-10-25 17:37:35 +00001217 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001218 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001219 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +00001220 }
1221 // Check protocols on qualified interfaces.
1222 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1223 E = OPT->qual_end(); I != E; ++I)
1224 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
1225 // Check whether we can reference this property.
1226 if (DiagnoseUseOfDecl(PD, MemberLoc))
1227 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +00001228
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001229 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +00001230 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1231 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001232 VK_LValue,
1233 OK_ObjCProperty,
1234 MemberLoc,
1235 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001236 else
John McCall3c3b7f92011-10-25 17:37:35 +00001237 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1238 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001239 VK_LValue,
1240 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001241 MemberLoc,
1242 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +00001243 }
1244 // If that failed, look for an "implicit" property by seeing if the nullary
1245 // selector is implemented.
1246
1247 // FIXME: The logic for looking up nullary and unary selectors should be
1248 // shared with the code in ActOnInstanceMessage.
1249
1250 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1251 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001252
1253 // May be founf in property's qualified list.
1254 if (!Getter)
1255 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +00001256
1257 // If this reference is in an @implementation, check for 'private' methods.
1258 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +00001259 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +00001260
1261 // Look through local category implementations associated with the class.
1262 if (!Getter)
1263 Getter = IFace->getCategoryInstanceMethod(Sel);
1264 if (Getter) {
1265 // Check if we can reference this property.
1266 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1267 return ExprError();
1268 }
1269 // If we found a getter then this may be a valid dot-reference, we
1270 // will look for the matching setter, in case it is needed.
1271 Selector SetterSel =
1272 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1273 PP.getSelectorTable(), Member);
1274 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001275
1276 // May be founf in property's qualified list.
1277 if (!Setter)
1278 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1279
Chris Lattner7f816522010-04-11 07:45:24 +00001280 if (!Setter) {
1281 // If this reference is in an @implementation, also check for 'private'
1282 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00001283 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +00001284 }
1285 // Look through local category implementations associated with the class.
1286 if (!Setter)
1287 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001288
Chris Lattner7f816522010-04-11 07:45:24 +00001289 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1290 return ExprError();
1291
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001292 if (Getter || Setter) {
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001293 if (Super)
John McCall12f78a62010-12-02 01:19:52 +00001294 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001295 Context.PseudoObjectTy,
1296 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001297 MemberLoc,
1298 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001299 else
John McCall12f78a62010-12-02 01:19:52 +00001300 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001301 Context.PseudoObjectTy,
1302 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001303 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001304
Chris Lattner7f816522010-04-11 07:45:24 +00001305 }
1306
1307 // Attempt to correct for typos in property names.
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001308 DeclFilterCCC<ObjCPropertyDecl> Validator;
1309 if (TypoCorrection Corrected = CorrectTypo(
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001310 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001311 NULL, Validator, IFace, false, OPT)) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001312 ObjCPropertyDecl *Property =
1313 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001314 DeclarationName TypoResult = Corrected.getCorrection();
Chris Lattner7f816522010-04-11 07:45:24 +00001315 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +00001316 << MemberName << QualType(OPT, 0) << TypoResult
1317 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +00001318 Diag(Property->getLocation(), diag::note_previous_decl)
1319 << Property->getDeclName();
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001320 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1321 TypoResult, MemberLoc,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001322 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +00001323 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001324 ObjCInterfaceDecl *ClassDeclared;
1325 if (ObjCIvarDecl *Ivar =
1326 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1327 QualType T = Ivar->getType();
1328 if (const ObjCObjectPointerType * OBJPT =
1329 T->getAsObjCInterfacePointerType()) {
Douglas Gregorb3029962011-11-14 22:10:01 +00001330 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
1331 PDiag(diag::err_property_not_as_forward_class)
1332 << MemberName << BaseExpr->getSourceRange()))
1333 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001334 }
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001335 Diag(MemberLoc,
1336 diag::err_ivar_access_using_property_syntax_suggest)
1337 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1338 << FixItHint::CreateReplacement(OpLoc, "->");
1339 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001340 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +00001341
Chris Lattner7f816522010-04-11 07:45:24 +00001342 Diag(MemberLoc, diag::err_property_not_found)
1343 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001344 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +00001345 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001346 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +00001347 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +00001348}
1349
1350
1351
John McCall60d7b3a2010-08-24 06:29:42 +00001352ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +00001353ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1354 IdentifierInfo &propertyName,
1355 SourceLocation receiverNameLoc,
1356 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001357
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001358 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +00001359 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1360 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +00001361
1362 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +00001363 if (IFace == 0) {
1364 // If the "receiver" is 'super' in a method, handle it as an expression-like
1365 // property reference.
John McCall26743b22011-02-03 09:00:02 +00001366 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00001367 IsSuper = true;
1368
Eli Friedmanb942cb22012-02-03 22:47:37 +00001369 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Chris Lattnereb483eb2010-04-11 08:28:14 +00001370 if (CurMethod->isInstanceMethod()) {
1371 QualType T =
1372 Context.getObjCInterfaceType(CurMethod->getClassInterface());
1373 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +00001374
1375 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001376 /*BaseExpr*/0,
1377 SourceLocation()/*OpLoc*/,
1378 &propertyName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001379 propertyNameLoc,
1380 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +00001381 }
Mike Stump1eb44332009-09-09 15:08:12 +00001382
Chris Lattnereb483eb2010-04-11 08:28:14 +00001383 // Otherwise, if this is a class method, try dispatching to our
1384 // superclass.
1385 IFace = CurMethod->getClassInterface()->getSuperClass();
1386 }
John McCall26743b22011-02-03 09:00:02 +00001387 }
Chris Lattnereb483eb2010-04-11 08:28:14 +00001388
1389 if (IFace == 0) {
1390 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
1391 return ExprError();
1392 }
1393 }
1394
1395 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +00001396 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001397 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001398
1399 // If this reference is in an @implementation, check for 'private' methods.
1400 if (!Getter)
1401 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1402 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001403 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001404 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001405
1406 if (Getter) {
1407 // FIXME: refactor/share with ActOnMemberReference().
1408 // Check if we can reference this property.
1409 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1410 return ExprError();
1411 }
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Steve Naroff61f72cb2009-03-09 21:12:44 +00001413 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00001414 Selector SetterSel =
1415 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +00001416 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +00001417
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001418 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001419 if (!Setter) {
1420 // If this reference is in an @implementation, also check for 'private'
1421 // methods.
1422 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1423 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001424 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001425 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001426 }
1427 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00001428 if (!Setter)
1429 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001430
1431 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1432 return ExprError();
1433
1434 if (Getter || Setter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00001435 if (IsSuper)
1436 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001437 Context.PseudoObjectTy,
1438 VK_LValue, OK_ObjCProperty,
Douglas Gregor926df6c2011-06-11 01:09:30 +00001439 propertyNameLoc,
1440 receiverNameLoc,
1441 Context.getObjCInterfaceType(IFace)));
1442
John McCall12f78a62010-12-02 01:19:52 +00001443 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001444 Context.PseudoObjectTy,
1445 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001446 propertyNameLoc,
1447 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +00001448 }
1449 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1450 << &propertyName << Context.getObjCInterfaceType(IFace));
1451}
1452
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001453namespace {
1454
1455class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1456 public:
1457 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1458 // Determine whether "super" is acceptable in the current context.
1459 if (Method && Method->getClassInterface())
1460 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1461 }
1462
1463 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1464 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1465 candidate.isKeyword("super");
1466 }
1467};
1468
1469}
1470
Douglas Gregor47bd5432010-04-14 02:46:37 +00001471Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +00001472 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +00001473 SourceLocation NameLoc,
1474 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +00001475 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +00001476 ParsedType &ReceiverType) {
1477 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +00001478
Douglas Gregor47bd5432010-04-14 02:46:37 +00001479 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +00001480 // messaging super. If the identifier is "super" and there is a
1481 // trailing dot, it's an instance message.
1482 if (IsSuper && S->isInObjcMethodScope())
1483 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001484
1485 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1486 LookupName(Result, S);
1487
1488 switch (Result.getResultKind()) {
1489 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +00001490 // Normal name lookup didn't find anything. If we're in an
1491 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +00001492 // FIXME: This is a hack. Ivar lookup should be part of normal
1493 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +00001494 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidisccc9e762011-11-09 00:22:48 +00001495 if (!Method->getClassInterface()) {
1496 // Fall back: let the parser try to parse it as an instance message.
1497 return ObjCInstanceMessage;
1498 }
1499
Douglas Gregored464422010-04-19 20:09:36 +00001500 ObjCInterfaceDecl *ClassDeclared;
1501 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1502 ClassDeclared))
1503 return ObjCInstanceMessage;
1504 }
Douglas Gregor95f42922010-10-14 22:11:03 +00001505
Douglas Gregor47bd5432010-04-14 02:46:37 +00001506 // Break out; we'll perform typo correction below.
1507 break;
1508
1509 case LookupResult::NotFoundInCurrentInstantiation:
1510 case LookupResult::FoundOverloaded:
1511 case LookupResult::FoundUnresolvedValue:
1512 case LookupResult::Ambiguous:
1513 Result.suppressDiagnostics();
1514 return ObjCInstanceMessage;
1515
1516 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +00001517 // If the identifier is a class or not, and there is a trailing dot,
1518 // it's an instance message.
1519 if (HasTrailingDot)
1520 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001521 // We found something. If it's a type, then we have a class
1522 // message. Otherwise, it's an instance message.
1523 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +00001524 QualType T;
1525 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1526 T = Context.getObjCInterfaceType(Class);
1527 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
1528 T = Context.getTypeDeclType(Type);
1529 else
1530 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001531
Douglas Gregor1569f952010-04-21 20:38:13 +00001532 // We have a class message, and T is the type we're
1533 // messaging. Build source-location information for it.
1534 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +00001535 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +00001536 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001537 }
1538 }
1539
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001540 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001541 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
1542 Result.getLookupKind(), S, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001543 Validator)) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001544 if (Corrected.isKeyword()) {
1545 // If we've found the keyword "super" (the only keyword that would be
1546 // returned by CorrectTypo), this is a send to super.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001547 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001548 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +00001549 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +00001550 return ObjCSuperMessage;
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001551 } else if (ObjCInterfaceDecl *Class =
1552 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1553 // If we found a declaration, correct when it refers to an Objective-C
1554 // class.
1555 Diag(NameLoc, diag::err_unknown_receiver_suggest)
1556 << Name << Corrected.getCorrection()
1557 << FixItHint::CreateReplacement(SourceRange(NameLoc),
1558 Class->getNameAsString());
1559 Diag(Class->getLocation(), diag::note_previous_decl)
1560 << Corrected.getCorrection();
1561
1562 QualType T = Context.getObjCInterfaceType(Class);
1563 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1564 ReceiverType = CreateParsedType(T, TSInfo);
1565 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001566 }
1567 }
1568
1569 // Fall back: let the parser try to parse it as an instance message.
1570 return ObjCInstanceMessage;
1571}
Steve Naroff61f72cb2009-03-09 21:12:44 +00001572
John McCall60d7b3a2010-08-24 06:29:42 +00001573ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001574 SourceLocation SuperLoc,
1575 Selector Sel,
1576 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001577 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001578 SourceLocation RBracLoc,
1579 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001580 // Determine whether we are inside a method or not.
Eli Friedmanb942cb22012-02-03 22:47:37 +00001581 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregorf95861a2010-04-21 20:01:04 +00001582 if (!Method) {
1583 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1584 return ExprError();
1585 }
Chris Lattner85a932e2008-01-04 22:32:30 +00001586
Douglas Gregorf95861a2010-04-21 20:01:04 +00001587 ObjCInterfaceDecl *Class = Method->getClassInterface();
1588 if (!Class) {
1589 Diag(SuperLoc, diag::error_no_super_class_message)
1590 << Method->getDeclName();
1591 return ExprError();
1592 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001593
Douglas Gregorf95861a2010-04-21 20:01:04 +00001594 ObjCInterfaceDecl *Super = Class->getSuperClass();
1595 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001596 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +00001597 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1598 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001599 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +00001600 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001601
Douglas Gregorf95861a2010-04-21 20:01:04 +00001602 // We are in a method whose class has a superclass, so 'super'
1603 // is acting as a keyword.
1604 if (Method->isInstanceMethod()) {
Nico Weber9a1ecf02011-08-22 17:25:57 +00001605 if (Sel.getMethodFamily() == OMF_dealloc)
1606 ObjCShouldCallSuperDealloc = false;
Nico Weber80cb6e62011-08-28 22:35:17 +00001607 if (Sel.getMethodFamily() == OMF_finalize)
1608 ObjCShouldCallSuperFinalize = false;
Nico Weber9a1ecf02011-08-22 17:25:57 +00001609
Douglas Gregorf95861a2010-04-21 20:01:04 +00001610 // Since we are in an instance method, this is an instance
1611 // message to the superclass instance.
1612 QualType SuperTy = Context.getObjCInterfaceType(Super);
1613 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +00001614 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001615 Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001616 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001617 }
Douglas Gregorf95861a2010-04-21 20:01:04 +00001618
1619 // Since we are in a class method, this is a class message to
1620 // the superclass.
1621 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1622 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001623 SuperLoc, Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001624 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001625}
1626
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001627
1628ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1629 bool isSuperReceiver,
1630 SourceLocation Loc,
1631 Selector Sel,
1632 ObjCMethodDecl *Method,
1633 MultiExprArg Args) {
1634 TypeSourceInfo *receiverTypeInfo = 0;
1635 if (!ReceiverType.isNull())
1636 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1637
1638 return BuildClassMessage(receiverTypeInfo, ReceiverType,
1639 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1640 Sel, Method, Loc, Loc, Loc, Args,
1641 /*isImplicit=*/true);
1642
1643}
1644
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001645static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
1646 unsigned DiagID,
1647 bool (*refactor)(const ObjCMessageExpr *,
1648 const NSAPI &, edit::Commit &)) {
1649 SourceLocation MsgLoc = Msg->getExprLoc();
1650 if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
1651 return;
1652
1653 SourceManager &SM = S.SourceMgr;
1654 edit::Commit ECommit(SM, S.LangOpts);
1655 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
1656 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
1657 << Msg->getSelector() << Msg->getSourceRange();
1658 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
1659 if (!ECommit.isCommitable())
1660 return;
1661 for (edit::Commit::edit_iterator
1662 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
1663 const edit::Commit::Edit &Edit = *I;
1664 switch (Edit.Kind) {
1665 case edit::Commit::Act_Insert:
1666 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
1667 Edit.Text,
1668 Edit.BeforePrev));
1669 break;
1670 case edit::Commit::Act_InsertFromRange:
1671 Builder.AddFixItHint(
1672 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
1673 Edit.getInsertFromRange(SM),
1674 Edit.BeforePrev));
1675 break;
1676 case edit::Commit::Act_Remove:
1677 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
1678 break;
1679 }
1680 }
1681 }
1682}
1683
1684static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
1685 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
1686 edit::rewriteObjCRedundantCallWithLiteral);
1687}
1688
Douglas Gregor2725ca82010-04-21 19:57:20 +00001689/// \brief Build an Objective-C class message expression.
1690///
1691/// This routine takes care of both normal class messages and
1692/// class messages to the superclass.
1693///
1694/// \param ReceiverTypeInfo Type source information that describes the
1695/// receiver of this message. This may be NULL, in which case we are
1696/// sending to the superclass and \p SuperLoc must be a valid source
1697/// location.
1698
1699/// \param ReceiverType The type of the object receiving the
1700/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1701/// type as that refers to. For a superclass send, this is the type of
1702/// the superclass.
1703///
1704/// \param SuperLoc The location of the "super" keyword in a
1705/// superclass message.
1706///
1707/// \param Sel The selector to which the message is being sent.
1708///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001709/// \param Method The method that this class message is invoking, if
1710/// already known.
1711///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001712/// \param LBracLoc The location of the opening square bracket ']'.
1713///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001714/// \param RBrac The location of the closing square bracket ']'.
1715///
1716/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001717ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001718 QualType ReceiverType,
1719 SourceLocation SuperLoc,
1720 Selector Sel,
1721 ObjCMethodDecl *Method,
1722 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001723 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001724 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001725 MultiExprArg ArgsIn,
1726 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001727 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001728 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001729 if (LBracLoc.isInvalid()) {
1730 Diag(Loc, diag::err_missing_open_square_message_send)
1731 << FixItHint::CreateInsertion(Loc, "[");
1732 LBracLoc = Loc;
1733 }
1734
Douglas Gregor92e986e2010-04-22 16:44:27 +00001735 if (ReceiverType->isDependentType()) {
1736 // If the receiver type is dependent, we can't type-check anything
1737 // at this point. Build a dependent expression.
1738 unsigned NumArgs = ArgsIn.size();
1739 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1740 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001741 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1742 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001743 Sel, SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001744 makeArrayRef(Args, NumArgs),RBracLoc,
1745 isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001746 }
Chris Lattner15faee12010-04-12 05:38:43 +00001747
Douglas Gregor2725ca82010-04-21 19:57:20 +00001748 // Find the class to which we are sending this message.
1749 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001750 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1751 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001752 Diag(Loc, diag::err_invalid_receiver_class_message)
1753 << ReceiverType;
1754 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001755 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001756 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian43bcdb22011-10-15 19:18:36 +00001757 // objc++ diagnoses during typename annotation.
David Blaikie4e4d0842012-03-11 07:00:24 +00001758 if (!getLangOpts().CPlusPlus)
Fariborz Jahanian43bcdb22011-10-15 19:18:36 +00001759 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001760 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001761 if (!Method) {
Douglas Gregorb3029962011-11-14 22:10:01 +00001762 SourceRange TypeRange
1763 = SuperLoc.isValid()? SourceRange(SuperLoc)
1764 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
1765 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikie4e4d0842012-03-11 07:00:24 +00001766 (getLangOpts().ObjCAutoRefCount
Douglas Gregorb3029962011-11-14 22:10:01 +00001767 ? PDiag(diag::err_arc_receiver_forward_class)
1768 : PDiag(diag::warn_receiver_forward_class))
1769 << TypeRange)) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001770 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001771 Method = LookupFactoryMethodInGlobalPool(Sel,
1772 SourceRange(LBracLoc, RBracLoc));
David Blaikie4e4d0842012-03-11 07:00:24 +00001773 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001774 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1775 << Method->getDeclName();
1776 }
1777 if (!Method)
1778 Method = Class->lookupClassMethod(Sel);
1779
1780 // If we have an implementation in scope, check "private" methods.
1781 if (!Method)
1782 Method = LookupPrivateClassMethod(Sel, Class);
1783
1784 if (Method && DiagnoseUseOfDecl(Method, Loc))
1785 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001786 }
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Douglas Gregor2725ca82010-04-21 19:57:20 +00001788 // Check the argument types and determine the result type.
1789 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001790 ExprValueKind VK = VK_RValue;
1791
Douglas Gregor2725ca82010-04-21 19:57:20 +00001792 unsigned NumArgs = ArgsIn.size();
1793 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001794 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1795 SuperLoc.isValid(), LBracLoc, RBracLoc,
1796 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001797 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001798
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001799 if (Method && !Method->getResultType()->isVoidType() &&
1800 RequireCompleteType(LBracLoc, Method->getResultType(),
1801 diag::err_illegal_message_expr_incomplete_type))
1802 return ExprError();
1803
Douglas Gregor2725ca82010-04-21 19:57:20 +00001804 // Construct the appropriate ObjCMessageExpr.
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001805 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001806 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001807 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001808 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001809 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001810 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001811 RBracLoc, isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001812 else {
John McCallf89e55a2010-11-18 06:31:45 +00001813 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001814 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001815 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001816 RBracLoc, isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001817 if (!isImplicit)
1818 checkCocoaAPI(*this, Result);
1819 }
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001820 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00001821}
1822
Douglas Gregor2725ca82010-04-21 19:57:20 +00001823// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00001824// ArgExprs is optional - if it is present, the number of expressions
1825// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001826ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00001827 ParsedType Receiver,
1828 Selector Sel,
1829 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001830 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor77328d12010-09-15 23:19:31 +00001831 SourceLocation RBracLoc,
1832 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001833 TypeSourceInfo *ReceiverTypeInfo;
1834 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1835 if (ReceiverType.isNull())
1836 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001837
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Douglas Gregor2725ca82010-04-21 19:57:20 +00001839 if (!ReceiverTypeInfo)
1840 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1841
1842 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00001843 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001844 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001845}
1846
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001847ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
1848 QualType ReceiverType,
1849 SourceLocation Loc,
1850 Selector Sel,
1851 ObjCMethodDecl *Method,
1852 MultiExprArg Args) {
1853 return BuildInstanceMessage(Receiver, ReceiverType,
1854 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
1855 Sel, Method, Loc, Loc, Loc, Args,
1856 /*isImplicit=*/true);
1857}
1858
Douglas Gregor2725ca82010-04-21 19:57:20 +00001859/// \brief Build an Objective-C instance message expression.
1860///
1861/// This routine takes care of both normal instance messages and
1862/// instance messages to the superclass instance.
1863///
1864/// \param Receiver The expression that computes the object that will
1865/// receive this message. This may be empty, in which case we are
1866/// sending to the superclass instance and \p SuperLoc must be a valid
1867/// source location.
1868///
1869/// \param ReceiverType The (static) type of the object receiving the
1870/// message. When a \p Receiver expression is provided, this is the
1871/// same type as that expression. For a superclass instance send, this
1872/// is a pointer to the type of the superclass.
1873///
1874/// \param SuperLoc The location of the "super" keyword in a
1875/// superclass instance message.
1876///
1877/// \param Sel The selector to which the message is being sent.
1878///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001879/// \param Method The method that this instance message is invoking, if
1880/// already known.
1881///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001882/// \param LBracLoc The location of the opening square bracket ']'.
1883///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001884/// \param RBrac The location of the closing square bracket ']'.
1885///
1886/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001887ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001888 QualType ReceiverType,
1889 SourceLocation SuperLoc,
1890 Selector Sel,
1891 ObjCMethodDecl *Method,
1892 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001893 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001894 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001895 MultiExprArg ArgsIn,
1896 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001897 // The location of the receiver.
1898 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1899
1900 if (LBracLoc.isInvalid()) {
1901 Diag(Loc, diag::err_missing_open_square_message_send)
1902 << FixItHint::CreateInsertion(Loc, "[");
1903 LBracLoc = Loc;
1904 }
1905
Douglas Gregor2725ca82010-04-21 19:57:20 +00001906 // If we have a receiver expression, perform appropriate promotions
1907 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00001908 if (Receiver) {
John McCall5acb0c92011-10-17 18:40:02 +00001909 if (Receiver->hasPlaceholderType()) {
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00001910 ExprResult Result;
1911 if (Receiver->getType() == Context.UnknownAnyTy)
1912 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
1913 else
1914 Result = CheckPlaceholderExpr(Receiver);
1915 if (Result.isInvalid()) return ExprError();
1916 Receiver = Result.take();
John McCall5acb0c92011-10-17 18:40:02 +00001917 }
1918
Douglas Gregor92e986e2010-04-22 16:44:27 +00001919 if (Receiver->isTypeDependent()) {
1920 // If the receiver is type-dependent, we can't type-check anything
1921 // at this point. Build a dependent expression.
1922 unsigned NumArgs = ArgsIn.size();
1923 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1924 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1925 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00001926 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001927 SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001928 makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001929 RBracLoc, isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001930 }
1931
Douglas Gregor2725ca82010-04-21 19:57:20 +00001932 // If necessary, apply function/array conversion to the receiver.
1933 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00001934 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1935 if (Result.isInvalid())
1936 return ExprError();
1937 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001938 ReceiverType = Receiver->getType();
1939 }
1940
Douglas Gregorf49bb082010-04-22 17:01:48 +00001941 if (!Method) {
1942 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00001943 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001944 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00001945 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1946 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001947 SourceRange(LBracLoc, RBracLoc),
1948 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001949 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00001950 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001951 SourceRange(LBracLoc, RBracLoc),
1952 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001953 } else if (ReceiverType->isObjCClassType() ||
1954 ReceiverType->isObjCQualifiedClassType()) {
1955 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001956 // We allow sending a message to a qualified Class ("Class<foo>"), which
1957 // is ok as long as one of the protocols implements the selector (if not, warn).
1958 if (const ObjCObjectPointerType *QClassTy
1959 = ReceiverType->getAsObjCQualifiedClassType()) {
1960 // Search protocols for class methods.
1961 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1962 if (!Method) {
1963 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1964 // warn if instance method found for a Class message.
1965 if (Method) {
1966 Diag(Loc, diag::warn_instance_method_on_class_found)
1967 << Method->getSelector() << Sel;
Ted Kremenek3306ec12012-02-27 22:55:11 +00001968 Diag(Method->getLocation(), diag::note_method_declared_at)
1969 << Method->getDeclName();
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001970 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001971 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001972 } else {
1973 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1974 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1975 // First check the public methods in the class interface.
1976 Method = ClassDecl->lookupClassMethod(Sel);
1977
1978 if (!Method)
1979 Method = LookupPrivateClassMethod(Sel, ClassDecl);
1980 }
1981 if (Method && DiagnoseUseOfDecl(Method, Loc))
1982 return ExprError();
1983 }
1984 if (!Method) {
1985 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregorc737acb2011-09-27 16:10:05 +00001986 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001987 Method = LookupFactoryMethodInGlobalPool(Sel,
1988 SourceRange(LBracLoc, RBracLoc),
1989 true);
1990 if (!Method) {
1991 // If no class (factory) method was found, check if an _instance_
1992 // method of the same name exists in the root class only.
1993 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001994 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001995 true);
1996 if (Method)
1997 if (const ObjCInterfaceDecl *ID =
1998 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1999 if (ID->getSuperClass())
2000 Diag(Loc, diag::warn_root_inst_method_not_found)
2001 << Sel << SourceRange(LBracLoc, RBracLoc);
2002 }
2003 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002004 }
2005 }
2006 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002007 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002008 ObjCInterfaceDecl* ClassDecl = 0;
2009
2010 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2011 // long as one of the protocols implements the selector (if not, warn).
2012 if (const ObjCObjectPointerType *QIdTy
2013 = ReceiverType->getAsObjCQualifiedIdType()) {
2014 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002015 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2016 if (!Method)
2017 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002018 } else if (const ObjCObjectPointerType *OCIType
2019 = ReceiverType->getAsObjCInterfacePointerType()) {
2020 // We allow sending a message to a pointer to an interface (an object).
2021 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00002022
Douglas Gregorb3029962011-11-14 22:10:01 +00002023 // Try to complete the type. Under ARC, this is a hard error from which
2024 // we don't try to recover.
2025 const ObjCInterfaceDecl *forwardClass = 0;
2026 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002027 getLangOpts().ObjCAutoRefCount
Douglas Gregorb3029962011-11-14 22:10:01 +00002028 ? PDiag(diag::err_arc_receiver_forward_instance)
2029 << (Receiver ? Receiver->getSourceRange()
2030 : SourceRange(SuperLoc))
Fariborz Jahanian4cc9b102012-02-03 01:02:44 +00002031 : PDiag(diag::warn_receiver_forward_instance)
2032 << (Receiver ? Receiver->getSourceRange()
2033 : SourceRange(SuperLoc)))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002034 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregorb3029962011-11-14 22:10:01 +00002035 return ExprError();
2036
2037 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian4cc9b102012-02-03 01:02:44 +00002038 Diag(Receiver ? Receiver->getLocStart()
2039 : SuperLoc, diag::note_receiver_is_id);
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00002040 Method = 0;
2041 } else {
2042 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCallf85e1932011-06-15 23:02:42 +00002043 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002044
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002045 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00002046 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002047 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2048
Douglas Gregorf49bb082010-04-22 17:01:48 +00002049 if (!Method) {
2050 // If we have implementations in scope, check "private" methods.
2051 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
2052
David Blaikie4e4d0842012-03-11 07:00:24 +00002053 if (!Method && getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002054 Diag(Loc, diag::err_arc_may_not_respond)
2055 << OCIType->getPointeeType() << Sel;
2056 return ExprError();
2057 }
2058
Douglas Gregorc737acb2011-09-27 16:10:05 +00002059 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002060 // If we still haven't found a method, look in the global pool. This
2061 // behavior isn't very desirable, however we need it for GCC
2062 // compatibility. FIXME: should we deviate??
2063 if (OCIType->qual_empty()) {
2064 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002065 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002066 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00002067 Diag(Loc, diag::warn_maynot_respond)
2068 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
2069 }
2070 }
2071 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002072 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00002073 return ExprError();
David Blaikie4e4d0842012-03-11 07:00:24 +00002074 } else if (!getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002075 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00002076 (ReceiverType->isPointerType() ||
2077 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002078 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00002079 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00002080 Diag(Loc, diag::warn_bad_receiver_type)
2081 << ReceiverType
2082 << Receiver->getSourceRange();
2083 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00002084 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002085 CK_CPointerToObjCPointerCast).take();
John McCall404cd162010-11-13 01:35:44 +00002086 else {
2087 // TODO: specialized warning on null receivers?
2088 bool IsNull = Receiver->isNullPointerConstant(Context,
2089 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00002090 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2091 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00002092 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002093 ReceiverType = Receiver->getType();
John McCall0bcc9bc2011-09-09 06:11:02 +00002094 } else {
John Wiegley429bb272011-04-08 18:41:53 +00002095 ExprResult ReceiverRes;
David Blaikie4e4d0842012-03-11 07:00:24 +00002096 if (getLangOpts().CPlusPlus)
John McCall0bcc9bc2011-09-09 06:11:02 +00002097 ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
John Wiegley429bb272011-04-08 18:41:53 +00002098 if (ReceiverRes.isUsable()) {
2099 Receiver = ReceiverRes.take();
John Wiegley429bb272011-04-08 18:41:53 +00002100 return BuildInstanceMessage(Receiver,
2101 ReceiverType,
2102 SuperLoc,
2103 Sel,
2104 Method,
2105 LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002106 SelectorLocs,
John Wiegley429bb272011-04-08 18:41:53 +00002107 RBracLoc,
2108 move(ArgsIn));
2109 } else {
2110 // Reject other random receiver types (e.g. structs).
2111 Diag(Loc, diag::err_bad_receiver_type)
2112 << ReceiverType << Receiver->getSourceRange();
2113 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00002114 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002115 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002116 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00002117 }
Mike Stump1eb44332009-09-09 15:08:12 +00002118
Douglas Gregor2725ca82010-04-21 19:57:20 +00002119 // Check the message arguments.
2120 unsigned NumArgs = ArgsIn.size();
2121 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
2122 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00002123 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00002124 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2125 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00002126 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
2127 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00002128 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00002129 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00002130
Douglas Gregor483dd2f2011-01-11 03:23:19 +00002131 if (Method && !Method->getResultType()->isVoidType() &&
2132 RequireCompleteType(LBracLoc, Method->getResultType(),
2133 diag::err_illegal_message_expr_incomplete_type))
2134 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002135
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002136 SourceLocation SelLoc = SelectorLocs.front();
2137
John McCallf85e1932011-06-15 23:02:42 +00002138 // In ARC, forbid the user from sending messages to
2139 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikie4e4d0842012-03-11 07:00:24 +00002140 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002141 ObjCMethodFamily family =
2142 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2143 switch (family) {
2144 case OMF_init:
2145 if (Method)
2146 checkInitMethod(Method, ReceiverType);
2147
2148 case OMF_None:
2149 case OMF_alloc:
2150 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +00002151 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +00002152 case OMF_mutableCopy:
2153 case OMF_new:
2154 case OMF_self:
2155 break;
2156
2157 case OMF_dealloc:
2158 case OMF_retain:
2159 case OMF_release:
2160 case OMF_autorelease:
2161 case OMF_retainCount:
2162 Diag(Loc, diag::err_arc_illegal_explicit_message)
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002163 << Sel << SelLoc;
John McCallf85e1932011-06-15 23:02:42 +00002164 break;
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002165
2166 case OMF_performSelector:
2167 if (Method && NumArgs >= 1) {
2168 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2169 Selector ArgSel = SelExp->getSelector();
2170 ObjCMethodDecl *SelMethod =
2171 LookupInstanceMethodInGlobalPool(ArgSel,
2172 SelExp->getSourceRange());
2173 if (!SelMethod)
2174 SelMethod =
2175 LookupFactoryMethodInGlobalPool(ArgSel,
2176 SelExp->getSourceRange());
2177 if (SelMethod) {
2178 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2179 switch (SelFamily) {
2180 case OMF_alloc:
2181 case OMF_copy:
2182 case OMF_mutableCopy:
2183 case OMF_new:
2184 case OMF_self:
2185 case OMF_init:
2186 // Issue error, unless ns_returns_not_retained.
2187 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2188 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002189 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002190 diag::err_arc_perform_selector_retains);
Ted Kremenek3306ec12012-02-27 22:55:11 +00002191 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2192 << SelMethod->getDeclName();
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002193 }
2194 break;
2195 default:
2196 // +0 call. OK. unless ns_returns_retained.
2197 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2198 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002199 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002200 diag::err_arc_perform_selector_retains);
Ted Kremenek3306ec12012-02-27 22:55:11 +00002201 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2202 << SelMethod->getDeclName();
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002203 }
2204 break;
2205 }
2206 }
2207 } else {
2208 // error (may leak).
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002209 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002210 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2211 }
2212 }
2213 break;
John McCallf85e1932011-06-15 23:02:42 +00002214 }
2215 }
2216
Douglas Gregor2725ca82010-04-21 19:57:20 +00002217 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00002218 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00002219 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00002220 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002221 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002222 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002223 makeArrayRef(Args, NumArgs), RBracLoc,
2224 isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002225 else {
John McCallf89e55a2010-11-18 06:31:45 +00002226 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002227 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002228 makeArrayRef(Args, NumArgs), RBracLoc,
2229 isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002230 if (!isImplicit)
2231 checkCocoaAPI(*this, Result);
2232 }
John McCallf85e1932011-06-15 23:02:42 +00002233
David Blaikie4e4d0842012-03-11 07:00:24 +00002234 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002235 // In ARC, annotate delegate init calls.
2236 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregorc737acb2011-09-27 16:10:05 +00002237 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCallf85e1932011-06-15 23:02:42 +00002238 // Only consider init calls *directly* in init implementations,
2239 // not within blocks.
2240 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2241 if (method && method->getMethodFamily() == OMF_init) {
2242 // The implicit assignment to self means we also don't want to
2243 // consume the result.
2244 Result->setDelegateInitCall(true);
2245 return Owned(Result);
2246 }
2247 }
2248
2249 // In ARC, check for message sends which are likely to introduce
2250 // retain cycles.
2251 checkRetainCycles(Result);
2252 }
2253
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002254 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00002255}
2256
2257// ActOnInstanceMessage - used for both unary and keyword messages.
2258// ArgExprs is optional - if it is present, the number of expressions
2259// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00002260ExprResult Sema::ActOnInstanceMessage(Scope *S,
2261 Expr *Receiver,
2262 Selector Sel,
2263 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002264 ArrayRef<SourceLocation> SelectorLocs,
John McCall60d7b3a2010-08-24 06:29:42 +00002265 SourceLocation RBracLoc,
2266 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00002267 if (!Receiver)
2268 return ExprError();
2269
John McCall9ae2f072010-08-23 23:25:46 +00002270 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00002271 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002272 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00002273}
Chris Lattnereca7be62008-04-07 05:30:13 +00002274
John McCallf85e1932011-06-15 23:02:42 +00002275enum ARCConversionTypeClass {
John McCall2cf031d2011-10-01 01:01:08 +00002276 /// int, void, struct A
John McCallf85e1932011-06-15 23:02:42 +00002277 ACTC_none,
John McCall2cf031d2011-10-01 01:01:08 +00002278
2279 /// id, void (^)()
John McCallf85e1932011-06-15 23:02:42 +00002280 ACTC_retainable,
John McCall2cf031d2011-10-01 01:01:08 +00002281
2282 /// id*, id***, void (^*)(),
2283 ACTC_indirectRetainable,
2284
2285 /// void* might be a normal C type, or it might a CF type.
2286 ACTC_voidPtr,
2287
2288 /// struct A*
2289 ACTC_coreFoundation
John McCallf85e1932011-06-15 23:02:42 +00002290};
John McCall2cf031d2011-10-01 01:01:08 +00002291static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2292 return (ACTC == ACTC_retainable ||
2293 ACTC == ACTC_coreFoundation ||
2294 ACTC == ACTC_voidPtr);
2295}
2296static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2297 return ACTC == ACTC_none ||
2298 ACTC == ACTC_voidPtr ||
2299 ACTC == ACTC_coreFoundation;
2300}
2301
John McCallf85e1932011-06-15 23:02:42 +00002302static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCall2cf031d2011-10-01 01:01:08 +00002303 bool isIndirect = false;
John McCallf85e1932011-06-15 23:02:42 +00002304
2305 // Ignore an outermost reference type.
John McCall2cf031d2011-10-01 01:01:08 +00002306 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCallf85e1932011-06-15 23:02:42 +00002307 type = ref->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00002308 isIndirect = true;
2309 }
John McCallf85e1932011-06-15 23:02:42 +00002310
2311 // Drill through pointers and arrays recursively.
2312 while (true) {
2313 if (const PointerType *ptr = type->getAs<PointerType>()) {
2314 type = ptr->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00002315
2316 // The first level of pointer may be the innermost pointer on a CF type.
2317 if (!isIndirect) {
2318 if (type->isVoidType()) return ACTC_voidPtr;
2319 if (type->isRecordType()) return ACTC_coreFoundation;
2320 }
John McCallf85e1932011-06-15 23:02:42 +00002321 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2322 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2323 } else {
2324 break;
2325 }
John McCall2cf031d2011-10-01 01:01:08 +00002326 isIndirect = true;
John McCallf85e1932011-06-15 23:02:42 +00002327 }
2328
John McCall2cf031d2011-10-01 01:01:08 +00002329 if (isIndirect) {
2330 if (type->isObjCARCBridgableType())
2331 return ACTC_indirectRetainable;
2332 return ACTC_none;
2333 }
2334
2335 if (type->isObjCARCBridgableType())
2336 return ACTC_retainable;
2337
2338 return ACTC_none;
John McCallf85e1932011-06-15 23:02:42 +00002339}
2340
2341namespace {
John McCall2cf031d2011-10-01 01:01:08 +00002342 /// A result from the cast checker.
2343 enum ACCResult {
2344 /// Cannot be casted.
2345 ACC_invalid,
2346
2347 /// Can be safely retained or not retained.
2348 ACC_bottom,
2349
2350 /// Can be casted at +0.
2351 ACC_plusZero,
2352
2353 /// Can be casted at +1.
2354 ACC_plusOne
2355 };
2356 ACCResult merge(ACCResult left, ACCResult right) {
2357 if (left == right) return left;
2358 if (left == ACC_bottom) return right;
2359 if (right == ACC_bottom) return left;
2360 return ACC_invalid;
2361 }
2362
2363 /// A checker which white-lists certain expressions whose conversion
2364 /// to or from retainable type would otherwise be forbidden in ARC.
2365 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2366 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2367
John McCallf85e1932011-06-15 23:02:42 +00002368 ASTContext &Context;
John McCall2cf031d2011-10-01 01:01:08 +00002369 ARCConversionTypeClass SourceClass;
2370 ARCConversionTypeClass TargetClass;
2371
2372 static bool isCFType(QualType type) {
2373 // Someday this can use ns_bridged. For now, it has to do this.
2374 return type->isCARCBridgableType();
John McCallf85e1932011-06-15 23:02:42 +00002375 }
John McCall2cf031d2011-10-01 01:01:08 +00002376
2377 public:
2378 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
2379 ARCConversionTypeClass target)
2380 : Context(Context), SourceClass(source), TargetClass(target) {}
2381
2382 using super::Visit;
2383 ACCResult Visit(Expr *e) {
2384 return super::Visit(e->IgnoreParens());
2385 }
2386
2387 ACCResult VisitStmt(Stmt *s) {
2388 return ACC_invalid;
2389 }
2390
2391 /// Null pointer constants can be casted however you please.
2392 ACCResult VisitExpr(Expr *e) {
2393 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2394 return ACC_bottom;
2395 return ACC_invalid;
2396 }
2397
2398 /// Objective-C string literals can be safely casted.
2399 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2400 // If we're casting to any retainable type, go ahead. Global
2401 // strings are immune to retains, so this is bottom.
2402 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2403
2404 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00002405 }
2406
John McCall2cf031d2011-10-01 01:01:08 +00002407 /// Look through certain implicit and explicit casts.
2408 ACCResult VisitCastExpr(CastExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00002409 switch (e->getCastKind()) {
2410 case CK_NullToPointer:
John McCall2cf031d2011-10-01 01:01:08 +00002411 return ACC_bottom;
2412
John McCallf85e1932011-06-15 23:02:42 +00002413 case CK_NoOp:
2414 case CK_LValueToRValue:
2415 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002416 case CK_CPointerToObjCPointerCast:
2417 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002418 case CK_AnyPointerToBlockPointerCast:
2419 return Visit(e->getSubExpr());
John McCall2cf031d2011-10-01 01:01:08 +00002420
John McCallf85e1932011-06-15 23:02:42 +00002421 default:
John McCall2cf031d2011-10-01 01:01:08 +00002422 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00002423 }
2424 }
John McCall2cf031d2011-10-01 01:01:08 +00002425
2426 /// Look through unary extension.
2427 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00002428 return Visit(e->getSubExpr());
2429 }
John McCall2cf031d2011-10-01 01:01:08 +00002430
2431 /// Ignore the LHS of a comma operator.
2432 ACCResult VisitBinComma(BinaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00002433 return Visit(e->getRHS());
2434 }
John McCall2cf031d2011-10-01 01:01:08 +00002435
2436 /// Conditional operators are okay if both sides are okay.
2437 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2438 ACCResult left = Visit(e->getTrueExpr());
2439 if (left == ACC_invalid) return ACC_invalid;
2440 return merge(left, Visit(e->getFalseExpr()));
John McCallf85e1932011-06-15 23:02:42 +00002441 }
John McCall2cf031d2011-10-01 01:01:08 +00002442
John McCall4b9c2d22011-11-06 09:01:30 +00002443 /// Look through pseudo-objects.
2444 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2445 // If we're getting here, we should always have a result.
2446 return Visit(e->getResultExpr());
2447 }
2448
John McCall2cf031d2011-10-01 01:01:08 +00002449 /// Statement expressions are okay if their result expression is okay.
2450 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00002451 return Visit(e->getSubStmt()->body_back());
2452 }
John McCallf85e1932011-06-15 23:02:42 +00002453
John McCall2cf031d2011-10-01 01:01:08 +00002454 /// Some declaration references are okay.
2455 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2456 // References to global constants from system headers are okay.
2457 // These are things like 'kCFStringTransformToLatin'. They are
2458 // can also be assumed to be immune to retains.
2459 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2460 if (isAnyRetainable(TargetClass) &&
2461 isAnyRetainable(SourceClass) &&
2462 var &&
2463 var->getStorageClass() == SC_Extern &&
2464 var->getType().isConstQualified() &&
2465 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2466 return ACC_bottom;
2467 }
2468
2469 // Nothing else.
2470 return ACC_invalid;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00002471 }
John McCall2cf031d2011-10-01 01:01:08 +00002472
2473 /// Some calls are okay.
2474 ACCResult VisitCallExpr(CallExpr *e) {
2475 if (FunctionDecl *fn = e->getDirectCallee())
2476 if (ACCResult result = checkCallToFunction(fn))
2477 return result;
2478
2479 return super::VisitCallExpr(e);
2480 }
2481
2482 ACCResult checkCallToFunction(FunctionDecl *fn) {
2483 // Require a CF*Ref return type.
2484 if (!isCFType(fn->getResultType()))
2485 return ACC_invalid;
2486
2487 if (!isAnyRetainable(TargetClass))
2488 return ACC_invalid;
2489
2490 // Honor an explicit 'not retained' attribute.
2491 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2492 return ACC_plusZero;
2493
2494 // Honor an explicit 'retained' attribute, except that for
2495 // now we're not going to permit implicit handling of +1 results,
2496 // because it's a bit frightening.
2497 if (fn->hasAttr<CFReturnsRetainedAttr>())
2498 return ACC_invalid; // ACC_plusOne if we start accepting this
2499
2500 // Recognize this specific builtin function, which is used by CFSTR.
2501 unsigned builtinID = fn->getBuiltinID();
2502 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2503 return ACC_bottom;
2504
2505 // Otherwise, don't do anything implicit with an unaudited function.
2506 if (!fn->hasAttr<CFAuditedTransferAttr>())
2507 return ACC_invalid;
2508
2509 // Otherwise, it's +0 unless it follows the create convention.
2510 if (ento::coreFoundation::followsCreateRule(fn))
2511 return ACC_invalid; // ACC_plusOne if we start accepting this
2512
2513 return ACC_plusZero;
2514 }
2515
2516 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
2517 return checkCallToMethod(e->getMethodDecl());
2518 }
2519
2520 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
2521 ObjCMethodDecl *method;
2522 if (e->isExplicitProperty())
2523 method = e->getExplicitProperty()->getGetterMethodDecl();
2524 else
2525 method = e->getImplicitPropertyGetter();
2526 return checkCallToMethod(method);
2527 }
2528
2529 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
2530 if (!method) return ACC_invalid;
2531
2532 // Check for message sends to functions returning CF types. We
2533 // just obey the Cocoa conventions with these, even though the
2534 // return type is CF.
2535 if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
2536 return ACC_invalid;
2537
2538 // If the method is explicitly marked not-retained, it's +0.
2539 if (method->hasAttr<CFReturnsNotRetainedAttr>())
2540 return ACC_plusZero;
2541
2542 // If the method is explicitly marked as returning retained, or its
2543 // selector follows a +1 Cocoa convention, treat it as +1.
2544 if (method->hasAttr<CFReturnsRetainedAttr>())
2545 return ACC_plusOne;
2546
2547 switch (method->getSelector().getMethodFamily()) {
2548 case OMF_alloc:
2549 case OMF_copy:
2550 case OMF_mutableCopy:
2551 case OMF_new:
2552 return ACC_plusOne;
2553
2554 default:
2555 // Otherwise, treat it as +0.
2556 return ACC_plusZero;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00002557 }
2558 }
John McCall2cf031d2011-10-01 01:01:08 +00002559 };
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00002560}
2561
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002562static bool
2563KnownName(Sema &S, const char *name) {
2564 LookupResult R(S, &S.Context.Idents.get(name), SourceLocation(),
2565 Sema::LookupOrdinaryName);
2566 return S.LookupName(R, S.TUScope, false);
2567}
2568
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00002569static void addFixitForObjCARCConversion(Sema &S,
2570 DiagnosticBuilder &DiagB,
2571 Sema::CheckedConversionKind CCK,
2572 SourceLocation afterLParen,
2573 QualType castType,
2574 Expr *castExpr,
2575 const char *bridgeKeyword,
2576 const char *CFBridgeName) {
2577 // We handle C-style and implicit casts here.
2578 switch (CCK) {
2579 case Sema::CCK_ImplicitConversion:
2580 case Sema::CCK_CStyleCast:
2581 break;
2582 case Sema::CCK_FunctionalCast:
2583 case Sema::CCK_OtherCast:
2584 return;
2585 }
2586
2587 if (CFBridgeName) {
2588 Expr *castedE = castExpr;
2589 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
2590 castedE = CCE->getSubExpr();
2591 castedE = castedE->IgnoreImpCasts();
2592 SourceRange range = castedE->getSourceRange();
2593 if (isa<ParenExpr>(castedE)) {
2594 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2595 CFBridgeName));
2596 } else {
2597 std::string namePlusParen = CFBridgeName;
2598 namePlusParen += "(";
2599 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2600 namePlusParen));
2601 DiagB.AddFixItHint(FixItHint::CreateInsertion(
2602 S.PP.getLocForEndOfToken(range.getEnd()),
2603 ")"));
2604 }
2605 return;
2606 }
2607
2608 if (CCK == Sema::CCK_CStyleCast) {
2609 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
2610 } else {
2611 std::string castCode = "(";
2612 castCode += bridgeKeyword;
2613 castCode += castType.getAsString();
2614 castCode += ")";
2615 Expr *castedE = castExpr->IgnoreImpCasts();
2616 SourceRange range = castedE->getSourceRange();
2617 if (isa<ParenExpr>(castedE)) {
2618 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2619 castCode));
2620 } else {
2621 castCode += "(";
2622 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2623 castCode));
2624 DiagB.AddFixItHint(FixItHint::CreateInsertion(
2625 S.PP.getLocForEndOfToken(range.getEnd()),
2626 ")"));
2627 }
2628 }
2629}
2630
John McCall5acb0c92011-10-17 18:40:02 +00002631static void
2632diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
2633 QualType castType, ARCConversionTypeClass castACTC,
2634 Expr *castExpr, ARCConversionTypeClass exprACTC,
2635 Sema::CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00002636 SourceLocation loc =
John McCall2cf031d2011-10-01 01:01:08 +00002637 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCallf85e1932011-06-15 23:02:42 +00002638
John McCall5acb0c92011-10-17 18:40:02 +00002639 if (S.makeUnavailableInSystemHeader(loc,
John McCall2cf031d2011-10-01 01:01:08 +00002640 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCallf85e1932011-06-15 23:02:42 +00002641 return;
John McCall5acb0c92011-10-17 18:40:02 +00002642
2643 QualType castExprType = castExpr->getType();
John McCallf85e1932011-06-15 23:02:42 +00002644
John McCall71c482c2011-06-17 06:50:50 +00002645 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00002646 switch (exprACTC) {
John McCall2cf031d2011-10-01 01:01:08 +00002647 case ACTC_none:
2648 case ACTC_coreFoundation:
2649 case ACTC_voidPtr:
2650 srcKind = (castExprType->isPointerType() ? 1 : 0);
2651 break;
2652 case ACTC_retainable:
2653 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
2654 break;
2655 case ACTC_indirectRetainable:
2656 srcKind = 4;
2657 break;
John McCallf85e1932011-06-15 23:02:42 +00002658 }
2659
John McCall5acb0c92011-10-17 18:40:02 +00002660 // Check whether this could be fixed with a bridge cast.
2661 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
2662 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCallf85e1932011-06-15 23:02:42 +00002663
John McCall5acb0c92011-10-17 18:40:02 +00002664 // Bridge from an ARC type to a CF type.
2665 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002666
John McCall5acb0c92011-10-17 18:40:02 +00002667 S.Diag(loc, diag::err_arc_cast_requires_bridge)
2668 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2669 << 2 // of C pointer type
2670 << castExprType
2671 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
2672 << castType
2673 << castRange
2674 << castExpr->getSourceRange();
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002675 bool br = KnownName(S, "CFBridgingRelease");
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00002676 {
2677 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2678 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2679 castType, castExpr, "__bridge ", 0);
2680 }
2681 {
2682 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_transfer)
2683 << castExprType << br;
2684 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2685 castType, castExpr, "__bridge_transfer ",
2686 br ? "CFBridgingRelease" : 0);
2687 }
John McCall5acb0c92011-10-17 18:40:02 +00002688
2689 return;
2690 }
2691
2692 // Bridge from a CF type to an ARC type.
2693 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002694 bool br = KnownName(S, "CFBridgingRetain");
John McCall5acb0c92011-10-17 18:40:02 +00002695 S.Diag(loc, diag::err_arc_cast_requires_bridge)
2696 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2697 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
2698 << castExprType
2699 << 2 // to C pointer type
2700 << castType
2701 << castRange
2702 << castExpr->getSourceRange();
2703
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00002704 {
2705 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2706 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2707 castType, castExpr, "__bridge ", 0);
2708 }
2709 {
2710 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_retained)
2711 << castType << br;
2712 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2713 castType, castExpr, "__bridge_retained ",
2714 br ? "CFBridgingRetain" : 0);
2715 }
John McCall5acb0c92011-10-17 18:40:02 +00002716
2717 return;
John McCallf85e1932011-06-15 23:02:42 +00002718 }
2719
John McCall5acb0c92011-10-17 18:40:02 +00002720 S.Diag(loc, diag::err_arc_mismatched_cast)
2721 << (CCK != Sema::CCK_ImplicitConversion)
2722 << srcKind << castExprType << castType
John McCallf85e1932011-06-15 23:02:42 +00002723 << castRange << castExpr->getSourceRange();
2724}
2725
John McCall5acb0c92011-10-17 18:40:02 +00002726Sema::ARCConversionResult
2727Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
2728 Expr *&castExpr, CheckedConversionKind CCK) {
2729 QualType castExprType = castExpr->getType();
2730
2731 // For the purposes of the classification, we assume reference types
2732 // will bind to temporaries.
2733 QualType effCastType = castType;
2734 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
2735 effCastType = ref->getPointeeType();
2736
2737 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
2738 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002739 if (exprACTC == castACTC) {
2740 // check for viablity and report error if casting an rvalue to a
2741 // life-time qualifier.
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00002742 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002743 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00002744 (castType != castExprType)) {
2745 const Type *DT = castType.getTypePtr();
2746 QualType QDT = castType;
2747 // We desugar some types but not others. We ignore those
2748 // that cannot happen in a cast; i.e. auto, and those which
2749 // should not be de-sugared; i.e typedef.
2750 if (const ParenType *PT = dyn_cast<ParenType>(DT))
2751 QDT = PT->desugar();
2752 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
2753 QDT = TP->desugar();
2754 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
2755 QDT = AT->desugar();
2756 if (QDT != castType &&
2757 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
2758 SourceLocation loc =
2759 (castRange.isValid() ? castRange.getBegin()
2760 : castExpr->getExprLoc());
2761 Diag(loc, diag::err_arc_nolifetime_behavior);
2762 }
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002763 }
2764 return ACR_okay;
2765 }
2766
John McCall5acb0c92011-10-17 18:40:02 +00002767 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
2768
2769 // Allow all of these types to be cast to integer types (but not
2770 // vice-versa).
2771 if (castACTC == ACTC_none && castType->isIntegralType(Context))
2772 return ACR_okay;
2773
2774 // Allow casts between pointers to lifetime types (e.g., __strong id*)
2775 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
2776 // must be explicit.
2777 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
2778 return ACR_okay;
2779 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
2780 CCK != CCK_ImplicitConversion)
2781 return ACR_okay;
2782
2783 switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
2784 // For invalid casts, fall through.
2785 case ACC_invalid:
2786 break;
2787
2788 // Do nothing for both bottom and +0.
2789 case ACC_bottom:
2790 case ACC_plusZero:
2791 return ACR_okay;
2792
2793 // If the result is +1, consume it here.
2794 case ACC_plusOne:
2795 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
2796 CK_ARCConsumeObject, castExpr,
2797 0, VK_RValue);
2798 ExprNeedsCleanups = true;
2799 return ACR_okay;
2800 }
2801
2802 // If this is a non-implicit cast from id or block type to a
2803 // CoreFoundation type, delay complaining in case the cast is used
2804 // in an acceptable context.
2805 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
2806 CCK != CCK_ImplicitConversion)
2807 return ACR_unbridged;
2808
2809 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
2810 castExpr, exprACTC, CCK);
2811 return ACR_okay;
2812}
2813
2814/// Given that we saw an expression with the ARCUnbridgedCastTy
2815/// placeholder type, complain bitterly.
2816void Sema::diagnoseARCUnbridgedCast(Expr *e) {
2817 // We expect the spurious ImplicitCastExpr to already have been stripped.
2818 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
2819 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
2820
2821 SourceRange castRange;
2822 QualType castType;
2823 CheckedConversionKind CCK;
2824
2825 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
2826 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
2827 castType = cast->getTypeAsWritten();
2828 CCK = CCK_CStyleCast;
2829 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
2830 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
2831 castType = cast->getTypeAsWritten();
2832 CCK = CCK_OtherCast;
2833 } else {
2834 castType = cast->getType();
2835 CCK = CCK_ImplicitConversion;
2836 }
2837
2838 ARCConversionTypeClass castACTC =
2839 classifyTypeForARCConversion(castType.getNonReferenceType());
2840
2841 Expr *castExpr = realCast->getSubExpr();
2842 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
2843
2844 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
2845 castExpr, ACTC_retainable, CCK);
2846}
2847
2848/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
2849/// type, remove the placeholder cast.
2850Expr *Sema::stripARCUnbridgedCast(Expr *e) {
2851 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
2852
2853 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
2854 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
2855 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
2856 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
2857 assert(uo->getOpcode() == UO_Extension);
2858 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
2859 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
2860 sub->getValueKind(), sub->getObjectKind(),
2861 uo->getOperatorLoc());
2862 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
2863 assert(!gse->isResultDependent());
2864
2865 unsigned n = gse->getNumAssocs();
2866 SmallVector<Expr*, 4> subExprs(n);
2867 SmallVector<TypeSourceInfo*, 4> subTypes(n);
2868 for (unsigned i = 0; i != n; ++i) {
2869 subTypes[i] = gse->getAssocTypeSourceInfo(i);
2870 Expr *sub = gse->getAssocExpr(i);
2871 if (i == gse->getResultIndex())
2872 sub = stripARCUnbridgedCast(sub);
2873 subExprs[i] = sub;
2874 }
2875
2876 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
2877 gse->getControllingExpr(),
2878 subTypes.data(), subExprs.data(),
2879 n, gse->getDefaultLoc(),
2880 gse->getRParenLoc(),
2881 gse->containsUnexpandedParameterPack(),
2882 gse->getResultIndex());
2883 } else {
2884 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
2885 return cast<ImplicitCastExpr>(e)->getSubExpr();
2886 }
2887}
2888
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00002889bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
2890 QualType exprType) {
2891 QualType canCastType =
2892 Context.getCanonicalType(castType).getUnqualifiedType();
2893 QualType canExprType =
2894 Context.getCanonicalType(exprType).getUnqualifiedType();
2895 if (isa<ObjCObjectPointerType>(canCastType) &&
2896 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
2897 canExprType->isObjCObjectPointerType()) {
2898 if (const ObjCObjectPointerType *ObjT =
2899 canExprType->getAs<ObjCObjectPointerType>())
2900 if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
2901 return false;
2902 }
2903 return true;
2904}
2905
John McCall7e5e5f42011-07-07 06:58:02 +00002906/// Look for an ObjCReclaimReturnedObject cast and destroy it.
2907static Expr *maybeUndoReclaimObject(Expr *e) {
2908 // For now, we just undo operands that are *immediately* reclaim
2909 // expressions, which prevents the vast majority of potential
2910 // problems here. To catch them all, we'd need to rebuild arbitrary
2911 // value-propagating subexpressions --- we can't reliably rebuild
2912 // in-place because of expression sharing.
2913 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall33e56f32011-09-10 06:18:15 +00002914 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall7e5e5f42011-07-07 06:58:02 +00002915 return ice->getSubExpr();
2916
2917 return e;
2918}
2919
John McCallf85e1932011-06-15 23:02:42 +00002920ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
2921 ObjCBridgeCastKind Kind,
2922 SourceLocation BridgeKeywordLoc,
2923 TypeSourceInfo *TSInfo,
2924 Expr *SubExpr) {
John McCall4906cf92011-08-26 00:48:42 +00002925 ExprResult SubResult = UsualUnaryConversions(SubExpr);
2926 if (SubResult.isInvalid()) return ExprError();
2927 SubExpr = SubResult.take();
2928
John McCallf85e1932011-06-15 23:02:42 +00002929 QualType T = TSInfo->getType();
2930 QualType FromType = SubExpr->getType();
2931
John McCall1d9b3b22011-09-09 05:25:32 +00002932 CastKind CK;
2933
John McCallf85e1932011-06-15 23:02:42 +00002934 bool MustConsume = false;
2935 if (T->isDependentType() || SubExpr->isTypeDependent()) {
2936 // Okay: we'll build a dependent expression type.
John McCall1d9b3b22011-09-09 05:25:32 +00002937 CK = CK_Dependent;
John McCallf85e1932011-06-15 23:02:42 +00002938 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
2939 // Casting CF -> id
John McCall1d9b3b22011-09-09 05:25:32 +00002940 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
2941 : CK_CPointerToObjCPointerCast);
John McCallf85e1932011-06-15 23:02:42 +00002942 switch (Kind) {
2943 case OBC_Bridge:
2944 break;
2945
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002946 case OBC_BridgeRetained: {
2947 bool br = KnownName(*this, "CFBridgingRelease");
John McCallf85e1932011-06-15 23:02:42 +00002948 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2949 << 2
2950 << FromType
2951 << (T->isBlockPointerType()? 1 : 0)
2952 << T
2953 << SubExpr->getSourceRange()
2954 << Kind;
2955 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2956 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
2957 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002958 << FromType << br
John McCallf85e1932011-06-15 23:02:42 +00002959 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002960 br ? "CFBridgingRelease "
2961 : "__bridge_transfer ");
John McCallf85e1932011-06-15 23:02:42 +00002962
2963 Kind = OBC_Bridge;
2964 break;
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002965 }
John McCallf85e1932011-06-15 23:02:42 +00002966
2967 case OBC_BridgeTransfer:
2968 // We must consume the Objective-C object produced by the cast.
2969 MustConsume = true;
2970 break;
2971 }
2972 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
2973 // Okay: id -> CF
John McCall1d9b3b22011-09-09 05:25:32 +00002974 CK = CK_BitCast;
John McCallf85e1932011-06-15 23:02:42 +00002975 switch (Kind) {
2976 case OBC_Bridge:
John McCall7e5e5f42011-07-07 06:58:02 +00002977 // Reclaiming a value that's going to be __bridge-casted to CF
2978 // is very dangerous, so we don't do it.
2979 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCallf85e1932011-06-15 23:02:42 +00002980 break;
2981
2982 case OBC_BridgeRetained:
2983 // Produce the object before casting it.
2984 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall33e56f32011-09-10 06:18:15 +00002985 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00002986 SubExpr, 0, VK_RValue);
2987 break;
2988
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002989 case OBC_BridgeTransfer: {
2990 bool br = KnownName(*this, "CFBridgingRetain");
John McCallf85e1932011-06-15 23:02:42 +00002991 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2992 << (FromType->isBlockPointerType()? 1 : 0)
2993 << FromType
2994 << 2
2995 << T
2996 << SubExpr->getSourceRange()
2997 << Kind;
2998
2999 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3000 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3001 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003002 << T << br
3003 << FixItHint::CreateReplacement(BridgeKeywordLoc,
3004 br ? "CFBridgingRetain " : "__bridge_retained");
John McCallf85e1932011-06-15 23:02:42 +00003005
3006 Kind = OBC_Bridge;
3007 break;
3008 }
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003009 }
John McCallf85e1932011-06-15 23:02:42 +00003010 } else {
3011 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3012 << FromType << T << Kind
3013 << SubExpr->getSourceRange()
3014 << TSInfo->getTypeLoc().getSourceRange();
3015 return ExprError();
3016 }
3017
John McCall1d9b3b22011-09-09 05:25:32 +00003018 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCallf85e1932011-06-15 23:02:42 +00003019 BridgeKeywordLoc,
3020 TSInfo, SubExpr);
3021
3022 if (MustConsume) {
3023 ExprNeedsCleanups = true;
John McCall33e56f32011-09-10 06:18:15 +00003024 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
John McCallf85e1932011-06-15 23:02:42 +00003025 0, VK_RValue);
3026 }
3027
3028 return Result;
3029}
3030
3031ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
3032 SourceLocation LParenLoc,
3033 ObjCBridgeCastKind Kind,
3034 SourceLocation BridgeKeywordLoc,
3035 ParsedType Type,
3036 SourceLocation RParenLoc,
3037 Expr *SubExpr) {
3038 TypeSourceInfo *TSInfo = 0;
3039 QualType T = GetTypeFromParser(Type, &TSInfo);
3040 if (!TSInfo)
3041 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3042 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
3043 SubExpr);
3044}