1 //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for Objective-C expressions.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Lookup.h"
16 #include "clang/Sema/Scope.h"
17 #include "clang/Sema/ScopeInfo.h"
18 #include "clang/Sema/Initialization.h"
19 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
20 #include "clang/Edit/Rewriters.h"
21 #include "clang/Edit/Commit.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "clang/Lex/Preprocessor.h"
30 using namespace clang;
32 using llvm::makeArrayRef;
34 ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
36 unsigned NumStrings) {
37 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
39 // 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.
43 StringLiteral *S = Strings[0];
45 // If we have a multi-part string, merge it all together.
46 if (NumStrings != 1) {
47 // Concatenate objc strings.
48 SmallString<128> StrBuf;
49 SmallVector<SourceLocation, 8> StrLocs;
51 for (unsigned i = 0; i != NumStrings; ++i) {
54 // ObjC strings can't be wide or UTF.
56 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
57 << S->getSourceRange();
62 StrBuf += S->getString();
64 // Get the locations of the string tokens.
65 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
68 // Create the aggregate string with the appropriate content and location
70 S = StringLiteral::Create(Context, StrBuf,
71 StringLiteral::Ascii, /*Pascal=*/false,
72 Context.getPointerType(Context.CharTy),
73 &StrLocs[0], StrLocs.size());
76 return BuildObjCStringLiteral(AtLocs[0], S);
79 ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
80 // Verify that this composite string is acceptable for ObjC strings.
81 if (CheckObjCString(S))
84 // Initialize the constant string interface lazily. This assumes
85 // 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).
88 QualType Ty = Context.getObjCConstantStringInterface();
90 Ty = Context.getObjCObjectPointerType(Ty);
91 } else if (getLangOpts().NoConstantCFStrings) {
92 IdentifierInfo *NSIdent=0;
93 std::string StringClass(getLangOpts().ObjCConstantStringClass);
95 if (StringClass.empty())
96 NSIdent = &Context.Idents.get("NSConstantString");
98 NSIdent = &Context.Idents.get(StringClass);
100 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
102 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
103 Context.setObjCConstantStringInterface(StrIF);
104 Ty = Context.getObjCConstantStringInterface();
105 Ty = Context.getObjCObjectPointerType(Ty);
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();
114 IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
115 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
117 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
118 Context.setObjCConstantStringInterface(StrIF);
119 Ty = Context.getObjCConstantStringInterface();
120 Ty = Context.getObjCObjectPointerType(Ty);
122 // 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();
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);
136 Ty = Context.getObjCObjectPointerType(Ty);
140 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
143 /// \brief Retrieve the NSNumber factory method that should be used to create
144 /// an Objective-C literal for the given type.
145 static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
146 QualType T, QualType ReturnType,
148 llvm::Optional<NSAPI::NSNumberLiteralMethodKind> Kind
149 = S.NSAPIObj->getNSNumberFactoryMethodKind(T);
152 S.Diag(Loc, diag::err_invalid_nsnumber_type)
157 // If we already looked up this method, we're done.
158 if (S.NSNumberLiteralMethods[*Kind])
159 return S.NSNumberLiteralMethods[*Kind];
161 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
164 // Look for the appropriate method within NSNumber.
165 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);;
166 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
167 TypeSourceInfo *ResultTInfo = 0;
168 Method = ObjCMethodDecl::Create(S.Context, SourceLocation(), SourceLocation(), Sel,
171 S.Context.getTranslationUnitDecl(),
172 false /*Instance*/, false/*isVariadic*/,
173 /*isSynthesized=*/false,
174 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
175 ObjCMethodDecl::Required,
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>());
185 S.Diag(Loc, diag::err_undeclared_nsnumber_method) << Sel;
189 // Make sure the return type is reasonable.
190 if (!Method->getResultType()->isObjCObjectPointerType()) {
191 S.Diag(Loc, diag::err_objc_literal_method_sig)
193 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
194 << Method->getResultType();
198 // Note: if the parameter type is out-of-line, we'll catch it later in the
199 // implicit conversion.
201 S.NSNumberLiteralMethods[*Kind] = Method;
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.
208 ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
209 // Look up the NSNumber class, if we haven't done so already.
211 NamedDecl *IF = LookupSingleName(TUScope,
212 NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber),
213 AtLoc, LookupOrdinaryName);
214 NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
216 if (!NSNumberDecl && getLangOpts().DebuggerObjCLiteral)
217 NSNumberDecl = ObjCInterfaceDecl::Create (Context,
218 Context.getTranslationUnitDecl(),
220 NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber),
221 0, SourceLocation());
223 Diag(AtLoc, diag::err_undeclared_nsnumber);
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;
238 case CharacterLiteral::Wide:
239 NumberType = Context.getWCharType();
242 case CharacterLiteral::UTF16:
243 NumberType = Context.Char16Ty;
246 case CharacterLiteral::UTF32:
247 NumberType = Context.Char32Ty;
252 ObjCMethodDecl *Method = 0;
253 // Look for the appropriate method within NSNumber.
254 // Construct the literal.
256 = Context.getObjCObjectPointerType(
257 Context.getObjCInterfaceType(NSNumberDecl));
258 Method = getNSNumberFactoryMethod(*this, AtLoc,
260 Number->getSourceRange());
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,
269 if (ConvertedNumber.isInvalid())
271 Number = ConvertedNumber.get();
273 return MaybeBindToTemporary(
274 new (Context) ObjCNumericLiteral(Number, Ty, Method, AtLoc));
277 ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
278 SourceLocation ValueLoc,
281 if (getLangOpts().CPlusPlus) {
282 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
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);
291 return BuildObjCNumericLiteral(AtLoc, Inner.get());
294 /// \brief Check that the given expression is a valid element of an Objective-C
295 /// collection literal.
296 static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
298 // If the expression is type-dependent, there's nothing for us to do.
299 if (Element->isTypeDependent())
302 ExprResult Result = S.CheckPlaceholderExpr(Element);
303 if (Result.isInvalid())
305 Element = Result.get();
307 // In C++, check for an implicit conversion to an Objective-C object pointer
309 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
310 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);
316 return Seq.Perform(S, Entity, Kind, MultiExprArg(S, &Element, 1));
319 Expr *OrigElement = Element;
321 // Perform lvalue-to-rvalue conversion.
322 Result = S.DefaultLvalueConversion(Element);
323 if (Result.isInvalid())
325 Element = Result.get();
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;
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
344 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
345 << Which << OrigElement->getSourceRange()
346 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
348 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
350 if (Result.isInvalid())
353 Element = Result.get();
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(), "@");
364 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
365 if (Result.isInvalid())
368 Element = Result.get();
374 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
375 << Element->getType();
380 // Make sure that the element has the type that the container factory
382 return S.PerformCopyInitialization(
383 InitializedEntity::InitializeParameter(S.Context, T,
385 Element->getLocStart(), Element);
388 ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
390 ObjCMethodDecl *getterMethod,
391 ObjCMethodDecl *setterMethod) {
392 // Feature support is for modern abi.
393 if (!LangOpts.ObjCNonFragileABI)
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())
401 IndexExpr = Result.get();
403 // Perform lvalue-to-rvalue conversion.
404 Result = DefaultLvalueConversion(BaseExpr);
405 if (Result.isInvalid())
407 BaseExpr = Result.get();
408 return Owned(ObjCSubscriptRefExpr::Create(Context,
411 Context.PseudoObjectTy,
417 ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
418 // Look up the NSArray class, if we haven't done so already.
420 NamedDecl *IF = LookupSingleName(TUScope,
421 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
424 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
425 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
426 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
427 Context.getTranslationUnitDecl(),
429 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
430 0, SourceLocation());
433 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
438 // Find the arrayWithObjects:count: method, if we haven't done so already.
439 QualType IdT = Context.getObjCIdType();
440 if (!ArrayWithObjectsMethod) {
442 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
443 ArrayWithObjectsMethod = NSArrayDecl->lookupClassMethod(Sel);
444 if (!ArrayWithObjectsMethod && getLangOpts().DebuggerObjCLiteral) {
445 TypeSourceInfo *ResultTInfo = 0;
446 ArrayWithObjectsMethod =
447 ObjCMethodDecl::Create(Context,
448 SourceLocation(), SourceLocation(), Sel,
451 Context.getTranslationUnitDecl(),
452 false /*Instance*/, false/*isVariadic*/,
453 /*isSynthesized=*/false,
454 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
455 ObjCMethodDecl::Required,
457 SmallVector<ParmVarDecl *, 2> Params;
458 ParmVarDecl *objects = ParmVarDecl::Create(Context, ArrayWithObjectsMethod,
459 SourceLocation(), SourceLocation(),
460 &Context.Idents.get("objects"),
461 Context.getPointerType(IdT),
466 Params.push_back(objects);
467 ParmVarDecl *cnt = ParmVarDecl::Create(Context, ArrayWithObjectsMethod,
468 SourceLocation(), SourceLocation(),
469 &Context.Idents.get("cnt"),
470 Context.UnsignedLongTy,
475 Params.push_back(cnt);
476 ArrayWithObjectsMethod->setMethodParams(Context, Params,
477 ArrayRef<SourceLocation>());
482 if (!ArrayWithObjectsMethod) {
483 Diag(SR.getBegin(), diag::err_undeclared_arraywithobjects) << Sel;
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();
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>();
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)
508 << Context.getPointerType(IdT.withConst());
511 T = PtrT->getPointeeType();
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)
520 << ArrayWithObjectsMethod->param_begin()[1]->getType()
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,
532 if (Converted.isInvalid())
535 ElementsBuffer[I] = Converted.get();
539 = Context.getObjCObjectPointerType(
540 Context.getObjCInterfaceType(NSArrayDecl));
542 return MaybeBindToTemporary(
543 ObjCArrayLiteral::Create(Context,
544 llvm::makeArrayRef(Elements.get(),
546 Ty, ArrayWithObjectsMethod, SR));
549 ExprResult 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);
558 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
559 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
560 Context.getTranslationUnitDecl(),
562 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
563 0, SourceLocation());
565 if (!NSDictionaryDecl) {
566 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
571 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
573 QualType IdT = Context.getObjCIdType();
574 if (!DictionaryWithObjectsMethod) {
575 Selector Sel = NSAPIObj->getNSDictionarySelector(
576 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
577 DictionaryWithObjectsMethod = NSDictionaryDecl->lookupClassMethod(Sel);
578 if (!DictionaryWithObjectsMethod && getLangOpts().DebuggerObjCLiteral) {
579 DictionaryWithObjectsMethod =
580 ObjCMethodDecl::Create(Context,
581 SourceLocation(), SourceLocation(), Sel,
583 0 /*TypeSourceInfo */,
584 Context.getTranslationUnitDecl(),
585 false /*Instance*/, false/*isVariadic*/,
586 /*isSynthesized=*/false,
587 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
588 ObjCMethodDecl::Required,
590 SmallVector<ParmVarDecl *, 3> Params;
591 ParmVarDecl *objects = ParmVarDecl::Create(Context, DictionaryWithObjectsMethod,
592 SourceLocation(), SourceLocation(),
593 &Context.Idents.get("objects"),
594 Context.getPointerType(IdT),
599 Params.push_back(objects);
600 ParmVarDecl *keys = ParmVarDecl::Create(Context, DictionaryWithObjectsMethod,
601 SourceLocation(), SourceLocation(),
602 &Context.Idents.get("keys"),
603 Context.getPointerType(IdT),
608 Params.push_back(keys);
609 ParmVarDecl *cnt = ParmVarDecl::Create(Context, DictionaryWithObjectsMethod,
610 SourceLocation(), SourceLocation(),
611 &Context.Idents.get("cnt"),
612 Context.UnsignedLongTy,
617 Params.push_back(cnt);
618 DictionaryWithObjectsMethod->setMethodParams(Context, Params,
619 ArrayRef<SourceLocation>());
622 if (!DictionaryWithObjectsMethod) {
623 Diag(SR.getBegin(), diag::err_undeclared_dictwithobjects) << Sel;
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();
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>();
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)
648 << Context.getPointerType(IdT.withConst());
651 ValueT = PtrValue->getPointeeType();
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>();
657 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
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};
667 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
668 (ObjCProtocolDecl**) PQ,1);
669 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
672 if (!QIDNSCopying.isNull())
673 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
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)
683 << Context.getPointerType(IdT.withConst());
687 KeyT = PtrKey->getPointeeType();
689 // Check that the 'count' parameter is integral.
690 if (!DictionaryWithObjectsMethod->param_begin()[2]->getType()
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)
697 << DictionaryWithObjectsMethod->param_begin()[2]->getType()
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) {
707 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
714 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
715 if (Value.isInvalid())
718 Elements[I].Key = Key.get();
719 Elements[I].Value = Value.get();
721 if (Elements[I].EllipsisLoc.isInvalid())
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());
733 HasPackExpansions = true;
738 = Context.getObjCObjectPointerType(
739 Context.getObjCInterfaceType(NSDictionaryDecl));
740 return MaybeBindToTemporary(
741 ObjCDictionaryLiteral::Create(Context,
742 llvm::makeArrayRef(Elements,
746 DictionaryWithObjectsMethod, SR));
749 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
750 TypeSourceInfo *EncodedTypeInfo,
751 SourceLocation RParenLoc) {
752 QualType EncodedType = EncodedTypeInfo->getType();
754 if (EncodedType->isDependentType())
755 StrTy = Context.DependentTy;
757 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
758 !EncodedType->isVoidType()) // void is handled too.
759 if (RequireCompleteType(AtLoc, EncodedType,
760 PDiag(diag::err_incomplete_type_objc_at_encode)
761 << EncodedTypeInfo->getTypeLoc().getSourceRange()))
765 Context.getObjCEncodingForType(EncodedType, Str);
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).
771 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
773 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
774 ArrayType::Normal, 0);
777 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
780 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
781 SourceLocation EncodeLoc,
782 SourceLocation LParenLoc,
784 SourceLocation RParenLoc) {
785 // FIXME: Preserve type source info ?
786 TypeSourceInfo *TInfo;
787 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
789 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
790 PP.getLocForEndOfToken(LParenLoc));
792 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
795 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
796 SourceLocation AtLoc,
797 SourceLocation SelLoc,
798 SourceLocation LParenLoc,
799 SourceLocation RParenLoc) {
800 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
801 SourceRange(LParenLoc, RParenLoc), false, false);
803 Method = LookupFactoryMethodInGlobalPool(Sel,
804 SourceRange(LParenLoc, RParenLoc));
806 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
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));
816 // In ARC, forbid the user from using @selector for
817 // retain/release/autorelease/dealloc/retainCount.
818 if (getLangOpts().ObjCAutoRefCount) {
819 switch (Sel.getMethodFamily()) {
822 case OMF_autorelease:
823 case OMF_retainCount:
825 Diag(AtLoc, diag::err_arc_illegal_selector) <<
826 Sel << SourceRange(LParenLoc, RParenLoc);
834 case OMF_mutableCopy:
837 case OMF_performSelector:
841 QualType Ty = Context.getObjCSelType();
842 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
845 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
846 SourceLocation AtLoc,
847 SourceLocation ProtoLoc,
848 SourceLocation LParenLoc,
849 SourceLocation RParenLoc) {
850 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
852 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
856 QualType Ty = Context.getObjCProtoType();
859 Ty = Context.getObjCObjectPointerType(Ty);
860 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
863 /// Try to capture an implicit reference to 'self'.
864 ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
865 DeclContext *DC = getFunctionLevelDeclContext();
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);
874 tryCaptureVariable(method->getSelfDecl(), Loc);
879 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
880 if (T == Context.getObjCInstanceType())
881 return Context.getObjCIdType();
886 QualType 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();
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
897 if (Method->isInstanceMethod() && isClassMessage)
898 return stripObjCInstanceType(Context, Method->getSendResultType());
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));
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())
917 return stripObjCInstanceType(Context, Method->getSendResultType());
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.
925 void Sema::EmitRelatedResultTypeNote(const Expr *E) {
926 E = E->IgnoreParenImpCasts();
927 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
931 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
935 if (!Method->hasRelatedResultType())
938 if (Context.hasSameUnqualifiedType(Method->getResultType()
939 .getNonReferenceType(),
943 if (!Context.hasSameUnqualifiedType(Method->getResultType(),
944 Context.getObjCInstanceType()))
947 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
948 << Method->isInstanceMethod() << Method->getSelector()
949 << MsgSend->getType();
952 bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
953 Expr **Args, unsigned NumArgs,
954 Selector Sel, ObjCMethodDecl *Method,
955 bool isClassMessage, bool isSuperMessage,
956 SourceLocation lbrac, SourceLocation rbrac,
957 QualType &ReturnType, ExprValueKind &VK) {
959 // Apply default argument promotion as for (C99 6.5.2.2p6).
960 for (unsigned i = 0; i != NumArgs; i++) {
961 if (Args[i]->isTypeDependent())
964 ExprResult Result = DefaultArgumentPromotion(Args[i]);
965 if (Result.isInvalid())
967 Args[i] = Result.take();
971 if (getLangOpts().ObjCAutoRefCount)
972 DiagID = diag::err_arc_method_not_found;
974 DiagID = isClassMessage ? diag::warn_class_method_not_found
975 : diag::warn_inst_method_not_found;
976 if (!getLangOpts().DebuggerSupport)
978 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
980 // In debuggers, we want to use __unknown_anytype for these
981 // results so that clients can cast them.
982 if (getLangOpts().DebuggerSupport) {
983 ReturnType = Context.UnknownAnyTy;
985 ReturnType = Context.getObjCIdType();
991 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
993 VK = Expr::getValueKindForType(Method->getResultType());
995 unsigned NumNamedArgs = Sel.getNumArgs();
996 // 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) {
1002 Diag(lbrac, diag::err_typecheck_call_too_few_args)
1003 << 2 << NumNamedArgs << NumArgs;
1007 bool IsError = false;
1008 for (unsigned i = 0; i < NumNamedArgs; i++) {
1009 // We can't do any type-checking on a type-dependent argument.
1010 if (Args[i]->isTypeDependent())
1013 Expr *argExpr = Args[i];
1015 ParmVarDecl *param = Method->param_begin()[i];
1016 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
1018 // 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);
1024 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
1026 PDiag(diag::err_call_incomplete_argument)
1027 << argExpr->getSourceRange()))
1030 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1032 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
1033 if (ArgE.isInvalid())
1036 Args[i] = ArgE.takeAs<Expr>();
1039 // Promote additional arguments to variadic methods.
1040 if (Method->isVariadic()) {
1041 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
1042 if (Args[i]->isTypeDependent())
1045 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
1046 IsError |= Arg.isInvalid();
1047 Args[i] = Arg.take();
1050 // Check for extra arguments to non-variadic methods.
1051 if (NumArgs != NumNamedArgs) {
1052 Diag(Args[NumNamedArgs]->getLocStart(),
1053 diag::err_typecheck_call_too_many_args)
1054 << 2 /*method*/ << NumNamedArgs << NumArgs
1055 << Method->getSourceRange()
1056 << SourceRange(Args[NumNamedArgs]->getLocStart(),
1057 Args[NumArgs-1]->getLocEnd());
1061 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
1063 // Do additional checkings on method.
1064 IsError |= CheckObjCMethodCall(Method, lbrac, Args, NumArgs);
1069 bool Sema::isSelfExpr(Expr *receiver) {
1070 // 'self' is objc 'self' in an objc method only.
1071 ObjCMethodDecl *method =
1072 dyn_cast<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1073 if (!method) return false;
1075 receiver = receiver->IgnoreParenLValueCasts();
1076 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
1077 if (DRE->getDecl() == method->getSelfDecl())
1082 // Helper method for ActOnClassMethod/ActOnInstanceMethod.
1083 // Will search "local" class/category implementations for a method decl.
1084 // If failed, then we search in class's root for an instance method.
1085 // Returns 0 if no method is found.
1086 ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
1087 ObjCInterfaceDecl *ClassDecl) {
1088 ObjCMethodDecl *Method = 0;
1089 // lookup in class and all superclasses
1090 while (ClassDecl && !Method) {
1091 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
1092 Method = ImpDecl->getClassMethod(Sel);
1094 // Look through local category implementations associated with the class.
1096 Method = ClassDecl->getCategoryClassMethod(Sel);
1098 // 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
1101 if (!Method && !ClassDecl->getSuperClass()) {
1102 Method = ClassDecl->lookupInstanceMethod(Sel);
1103 // Look through local category implementations associated
1104 // with the root class.
1106 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1109 ClassDecl = ClassDecl->getSuperClass();
1114 ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
1115 ObjCInterfaceDecl *ClassDecl) {
1116 if (!ClassDecl->hasDefinition())
1119 ObjCMethodDecl *Method = 0;
1120 while (ClassDecl && !Method) {
1121 // If we have implementations in scope, check "private" methods.
1122 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
1123 Method = ImpDecl->getInstanceMethod(Sel);
1125 // Look through local category implementations associated with the class.
1127 Method = ClassDecl->getCategoryInstanceMethod(Sel);
1128 ClassDecl = ClassDecl->getSuperClass();
1133 /// LookupMethodInType - Look up a method in an ObjCObjectType.
1134 ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
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))
1142 // Okay, look for "private" methods declared in any
1143 // @implementations we've seen.
1145 if (ObjCMethodDecl *method = LookupPrivateInstanceMethod(sel, iface))
1148 if (ObjCMethodDecl *method = LookupPrivateClassMethod(sel, iface))
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))
1162 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1163 /// list of a qualified objective pointer type.
1164 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1165 const ObjCObjectPointerType *OPT,
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))) {
1179 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1180 /// objective C interface. This is a property reference expression.
1182 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
1183 Expr *BaseExpr, SourceLocation OpLoc,
1184 DeclarationName MemberName,
1185 SourceLocation MemberLoc,
1186 SourceLocation SuperLoc, QualType SuperType,
1188 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1189 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
1191 if (MemberName.getNameKind() != DeclarationName::Identifier) {
1192 Diag(MemberLoc, diag::err_invalid_property_name)
1193 << MemberName << QualType(OPT, 0);
1197 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1198 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))
1205 // 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))
1212 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
1213 VK_LValue, OK_ObjCProperty,
1215 SuperLoc, SuperType));
1217 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
1218 VK_LValue, OK_ObjCProperty,
1219 MemberLoc, BaseExpr));
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))
1230 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1231 Context.PseudoObjectTy,
1235 SuperLoc, SuperType));
1237 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1238 Context.PseudoObjectTy,
1244 // If that failed, look for an "implicit" property by seeing if the nullary
1245 // selector is implemented.
1247 // FIXME: The logic for looking up nullary and unary selectors should be
1248 // shared with the code in ActOnInstanceMessage.
1250 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1251 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1253 // May be founf in property's qualified list.
1255 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
1257 // If this reference is in an @implementation, check for 'private' methods.
1259 Getter = IFace->lookupPrivateMethod(Sel);
1261 // Look through local category implementations associated with the class.
1263 Getter = IFace->getCategoryInstanceMethod(Sel);
1265 // Check if we can reference this property.
1266 if (DiagnoseUseOfDecl(Getter, MemberLoc))
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);
1276 // May be founf in property's qualified list.
1278 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1281 // If this reference is in an @implementation, also check for 'private'
1283 Setter = IFace->lookupPrivateMethod(SetterSel);
1285 // Look through local category implementations associated with the class.
1287 Setter = IFace->getCategoryInstanceMethod(SetterSel);
1289 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1292 if (Getter || Setter) {
1294 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1295 Context.PseudoObjectTy,
1296 VK_LValue, OK_ObjCProperty,
1298 SuperLoc, SuperType));
1300 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1301 Context.PseudoObjectTy,
1302 VK_LValue, OK_ObjCProperty,
1303 MemberLoc, BaseExpr));
1307 // Attempt to correct for typos in property names.
1308 DeclFilterCCC<ObjCPropertyDecl> Validator;
1309 if (TypoCorrection Corrected = CorrectTypo(
1310 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
1311 NULL, Validator, IFace, false, OPT)) {
1312 ObjCPropertyDecl *Property =
1313 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>();
1314 DeclarationName TypoResult = Corrected.getCorrection();
1315 Diag(MemberLoc, diag::err_property_not_found_suggest)
1316 << MemberName << QualType(OPT, 0) << TypoResult
1317 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
1318 Diag(Property->getLocation(), diag::note_previous_decl)
1319 << Property->getDeclName();
1320 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1321 TypoResult, MemberLoc,
1322 SuperLoc, SuperType, Super);
1324 ObjCInterfaceDecl *ClassDeclared;
1325 if (ObjCIvarDecl *Ivar =
1326 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1327 QualType T = Ivar->getType();
1328 if (const ObjCObjectPointerType * OBJPT =
1329 T->getAsObjCInterfacePointerType()) {
1330 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
1331 PDiag(diag::err_property_not_as_forward_class)
1332 << MemberName << BaseExpr->getSourceRange()))
1336 diag::err_ivar_access_using_property_syntax_suggest)
1337 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1338 << FixItHint::CreateReplacement(OpLoc, "->");
1342 Diag(MemberLoc, diag::err_property_not_found)
1343 << MemberName << QualType(OPT, 0);
1345 Diag(Setter->getLocation(), diag::note_getter_unavailable)
1346 << MemberName << BaseExpr->getSourceRange();
1353 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1354 IdentifierInfo &propertyName,
1355 SourceLocation receiverNameLoc,
1356 SourceLocation propertyNameLoc) {
1358 IdentifierInfo *receiverNamePtr = &receiverName;
1359 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1362 bool IsSuper = false;
1364 // If the "receiver" is 'super' in a method, handle it as an expression-like
1365 // property reference.
1366 if (receiverNamePtr->isStr("super")) {
1369 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
1370 if (CurMethod->isInstanceMethod()) {
1372 Context.getObjCInterfaceType(CurMethod->getClassInterface());
1373 T = Context.getObjCObjectPointerType(T);
1375 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
1377 SourceLocation()/*OpLoc*/,
1380 receiverNameLoc, T, true);
1383 // Otherwise, if this is a class method, try dispatching to our
1385 IFace = CurMethod->getClassInterface()->getSuperClass();
1390 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
1395 // Search for a declared property first.
1396 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
1397 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
1399 // If this reference is in an @implementation, check for 'private' methods.
1401 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1402 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1403 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
1404 Getter = ImpDecl->getClassMethod(Sel);
1407 // FIXME: refactor/share with ActOnMemberReference().
1408 // Check if we can reference this property.
1409 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1413 // Look for the matching setter, in case it is needed.
1414 Selector SetterSel =
1415 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1416 PP.getSelectorTable(), &propertyName);
1418 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1420 // If this reference is in an @implementation, also check for 'private'
1422 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1423 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1424 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
1425 Setter = ImpDecl->getClassMethod(SetterSel);
1427 // Look through local category implementations associated with the class.
1429 Setter = IFace->getCategoryClassMethod(SetterSel);
1431 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1434 if (Getter || Setter) {
1436 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1437 Context.PseudoObjectTy,
1438 VK_LValue, OK_ObjCProperty,
1441 Context.getObjCInterfaceType(IFace)));
1443 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1444 Context.PseudoObjectTy,
1445 VK_LValue, OK_ObjCProperty,
1447 receiverNameLoc, IFace));
1449 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1450 << &propertyName << Context.getObjCInterfaceType(IFace));
1455 class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1457 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1458 // Determine whether "super" is acceptable in the current context.
1459 if (Method && Method->getClassInterface())
1460 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1463 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1464 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1465 candidate.isKeyword("super");
1471 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
1472 IdentifierInfo *Name,
1473 SourceLocation NameLoc,
1475 bool HasTrailingDot,
1476 ParsedType &ReceiverType) {
1477 ReceiverType = ParsedType();
1479 // If the identifier is "super" and there is no trailing dot, we're
1480 // 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;
1485 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1486 LookupName(Result, S);
1488 switch (Result.getResultKind()) {
1489 case LookupResult::NotFound:
1490 // 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!
1492 // FIXME: This is a hack. Ivar lookup should be part of normal
1494 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
1495 if (!Method->getClassInterface()) {
1496 // Fall back: let the parser try to parse it as an instance message.
1497 return ObjCInstanceMessage;
1500 ObjCInterfaceDecl *ClassDeclared;
1501 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1503 return ObjCInstanceMessage;
1506 // Break out; we'll perform typo correction below.
1509 case LookupResult::NotFoundInCurrentInstantiation:
1510 case LookupResult::FoundOverloaded:
1511 case LookupResult::FoundUnresolvedValue:
1512 case LookupResult::Ambiguous:
1513 Result.suppressDiagnostics();
1514 return ObjCInstanceMessage;
1516 case LookupResult::Found: {
1517 // If the identifier is a class or not, and there is a trailing dot,
1518 // it's an instance message.
1520 return ObjCInstanceMessage;
1521 // 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();
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);
1530 return ObjCInstanceMessage;
1532 // 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);
1535 ReceiverType = CreateParsedType(T, TSInfo);
1536 return ObjCClassMessage;
1540 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
1541 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
1542 Result.getLookupKind(), S, NULL,
1544 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.
1547 Diag(NameLoc, diag::err_unknown_receiver_suggest)
1548 << Name << Corrected.getCorrection()
1549 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
1550 return ObjCSuperMessage;
1551 } else if (ObjCInterfaceDecl *Class =
1552 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1553 // If we found a declaration, correct when it refers to an Objective-C
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();
1562 QualType T = Context.getObjCInterfaceType(Class);
1563 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1564 ReceiverType = CreateParsedType(T, TSInfo);
1565 return ObjCClassMessage;
1569 // Fall back: let the parser try to parse it as an instance message.
1570 return ObjCInstanceMessage;
1573 ExprResult Sema::ActOnSuperMessage(Scope *S,
1574 SourceLocation SuperLoc,
1576 SourceLocation LBracLoc,
1577 ArrayRef<SourceLocation> SelectorLocs,
1578 SourceLocation RBracLoc,
1579 MultiExprArg Args) {
1580 // Determine whether we are inside a method or not.
1581 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
1583 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1587 ObjCInterfaceDecl *Class = Method->getClassInterface();
1589 Diag(SuperLoc, diag::error_no_super_class_message)
1590 << Method->getDeclName();
1594 ObjCInterfaceDecl *Super = Class->getSuperClass();
1596 // The current class does not have a superclass.
1597 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1598 << Class->getIdentifier();
1602 // We are in a method whose class has a superclass, so 'super'
1603 // is acting as a keyword.
1604 if (Method->isInstanceMethod()) {
1605 if (Sel.getMethodFamily() == OMF_dealloc)
1606 ObjCShouldCallSuperDealloc = false;
1607 if (Sel.getMethodFamily() == OMF_finalize)
1608 ObjCShouldCallSuperFinalize = false;
1610 // 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);
1614 return BuildInstanceMessage(0, SuperTy, SuperLoc,
1616 LBracLoc, SelectorLocs, RBracLoc, move(Args));
1619 // Since we are in a class method, this is a class message to
1621 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1622 Context.getObjCInterfaceType(Super),
1623 SuperLoc, Sel, /*Method=*/0,
1624 LBracLoc, SelectorLocs, RBracLoc, move(Args));
1628 ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1629 bool isSuperReceiver,
1632 ObjCMethodDecl *Method,
1633 MultiExprArg Args) {
1634 TypeSourceInfo *receiverTypeInfo = 0;
1635 if (!ReceiverType.isNull())
1636 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1638 return BuildClassMessage(receiverTypeInfo, ReceiverType,
1639 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1640 Sel, Method, Loc, Loc, Loc, Args,
1641 /*isImplicit=*/true);
1645 static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
1647 bool (*refactor)(const ObjCMessageExpr *,
1648 const NSAPI &, edit::Commit &)) {
1649 SourceLocation MsgLoc = Msg->getExprLoc();
1650 if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
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())
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,
1670 case edit::Commit::Act_InsertFromRange:
1671 Builder.AddFixItHint(
1672 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
1673 Edit.getInsertFromRange(SM),
1676 case edit::Commit::Act_Remove:
1677 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
1684 static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
1685 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
1686 edit::rewriteObjCRedundantCallWithLiteral);
1689 /// \brief Build an Objective-C class message expression.
1691 /// This routine takes care of both normal class messages and
1692 /// class messages to the superclass.
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
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
1704 /// \param SuperLoc The location of the "super" keyword in a
1705 /// superclass message.
1707 /// \param Sel The selector to which the message is being sent.
1709 /// \param Method The method that this class message is invoking, if
1712 /// \param LBracLoc The location of the opening square bracket ']'.
1714 /// \param RBrac The location of the closing square bracket ']'.
1716 /// \param Args The message arguments.
1717 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
1718 QualType ReceiverType,
1719 SourceLocation SuperLoc,
1721 ObjCMethodDecl *Method,
1722 SourceLocation LBracLoc,
1723 ArrayRef<SourceLocation> SelectorLocs,
1724 SourceLocation RBracLoc,
1725 MultiExprArg ArgsIn,
1727 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
1728 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
1729 if (LBracLoc.isInvalid()) {
1730 Diag(Loc, diag::err_missing_open_square_message_send)
1731 << FixItHint::CreateInsertion(Loc, "[");
1735 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");
1741 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1742 VK_RValue, LBracLoc, ReceiverTypeInfo,
1743 Sel, SelectorLocs, /*Method=*/0,
1744 makeArrayRef(Args, NumArgs),RBracLoc,
1748 // Find the class to which we are sending this message.
1749 ObjCInterfaceDecl *Class = 0;
1750 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1751 if (!ClassType || !(Class = ClassType->getInterface())) {
1752 Diag(Loc, diag::err_invalid_receiver_class_message)
1756 assert(Class && "We don't know which class we're messaging?");
1757 // objc++ diagnoses during typename annotation.
1758 if (!getLangOpts().CPlusPlus)
1759 (void)DiagnoseUseOfDecl(Class, Loc);
1760 // Find the method we are messaging.
1762 SourceRange TypeRange
1763 = SuperLoc.isValid()? SourceRange(SuperLoc)
1764 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
1765 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
1766 (getLangOpts().ObjCAutoRefCount
1767 ? PDiag(diag::err_arc_receiver_forward_class)
1768 : PDiag(diag::warn_receiver_forward_class))
1770 // A forward class used in messaging is treated as a 'Class'
1771 Method = LookupFactoryMethodInGlobalPool(Sel,
1772 SourceRange(LBracLoc, RBracLoc));
1773 if (Method && !getLangOpts().ObjCAutoRefCount)
1774 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1775 << Method->getDeclName();
1778 Method = Class->lookupClassMethod(Sel);
1780 // If we have an implementation in scope, check "private" methods.
1782 Method = LookupPrivateClassMethod(Sel, Class);
1784 if (Method && DiagnoseUseOfDecl(Method, Loc))
1788 // Check the argument types and determine the result type.
1789 QualType ReturnType;
1790 ExprValueKind VK = VK_RValue;
1792 unsigned NumArgs = ArgsIn.size();
1793 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1794 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1795 SuperLoc.isValid(), LBracLoc, RBracLoc,
1799 if (Method && !Method->getResultType()->isVoidType() &&
1800 RequireCompleteType(LBracLoc, Method->getResultType(),
1801 diag::err_illegal_message_expr_incomplete_type))
1804 // Construct the appropriate ObjCMessageExpr.
1805 ObjCMessageExpr *Result;
1806 if (SuperLoc.isValid())
1807 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1808 SuperLoc, /*IsInstanceSuper=*/false,
1809 ReceiverType, Sel, SelectorLocs,
1810 Method, makeArrayRef(Args, NumArgs),
1811 RBracLoc, isImplicit);
1813 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1814 ReceiverTypeInfo, Sel, SelectorLocs,
1815 Method, makeArrayRef(Args, NumArgs),
1816 RBracLoc, isImplicit);
1818 checkCocoaAPI(*this, Result);
1820 return MaybeBindToTemporary(Result);
1823 // ActOnClassMessage - used for both unary and keyword messages.
1824 // ArgExprs is optional - if it is present, the number of expressions
1825 // is obtained from Sel.getNumArgs().
1826 ExprResult Sema::ActOnClassMessage(Scope *S,
1827 ParsedType Receiver,
1829 SourceLocation LBracLoc,
1830 ArrayRef<SourceLocation> SelectorLocs,
1831 SourceLocation RBracLoc,
1832 MultiExprArg Args) {
1833 TypeSourceInfo *ReceiverTypeInfo;
1834 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1835 if (ReceiverType.isNull())
1839 if (!ReceiverTypeInfo)
1840 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1842 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
1843 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
1844 LBracLoc, SelectorLocs, RBracLoc, move(Args));
1847 ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
1848 QualType ReceiverType,
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);
1859 /// \brief Build an Objective-C instance message expression.
1861 /// This routine takes care of both normal instance messages and
1862 /// instance messages to the superclass instance.
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.
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.
1874 /// \param SuperLoc The location of the "super" keyword in a
1875 /// superclass instance message.
1877 /// \param Sel The selector to which the message is being sent.
1879 /// \param Method The method that this instance message is invoking, if
1882 /// \param LBracLoc The location of the opening square bracket ']'.
1884 /// \param RBrac The location of the closing square bracket ']'.
1886 /// \param Args The message arguments.
1887 ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
1888 QualType ReceiverType,
1889 SourceLocation SuperLoc,
1891 ObjCMethodDecl *Method,
1892 SourceLocation LBracLoc,
1893 ArrayRef<SourceLocation> SelectorLocs,
1894 SourceLocation RBracLoc,
1895 MultiExprArg ArgsIn,
1897 // The location of the receiver.
1898 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1900 if (LBracLoc.isInvalid()) {
1901 Diag(Loc, diag::err_missing_open_square_message_send)
1902 << FixItHint::CreateInsertion(Loc, "[");
1906 // If we have a receiver expression, perform appropriate promotions
1907 // and determine receiver type.
1909 if (Receiver->hasPlaceholderType()) {
1911 if (Receiver->getType() == Context.UnknownAnyTy)
1912 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
1914 Result = CheckPlaceholderExpr(Receiver);
1915 if (Result.isInvalid()) return ExprError();
1916 Receiver = Result.take();
1919 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,
1926 VK_RValue, LBracLoc, Receiver, Sel,
1927 SelectorLocs, /*Method=*/0,
1928 makeArrayRef(Args, NumArgs),
1929 RBracLoc, isImplicit));
1932 // If necessary, apply function/array conversion to the receiver.
1933 // C99 6.7.5.3p[7,8].
1934 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1935 if (Result.isInvalid())
1937 Receiver = Result.take();
1938 ReceiverType = Receiver->getType();
1942 // Handle messages to id.
1943 bool receiverIsId = ReceiverType->isObjCIdType();
1944 if (receiverIsId || ReceiverType->isBlockPointerType() ||
1945 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1946 Method = LookupInstanceMethodInGlobalPool(Sel,
1947 SourceRange(LBracLoc, RBracLoc),
1950 Method = LookupFactoryMethodInGlobalPool(Sel,
1951 SourceRange(LBracLoc, RBracLoc),
1953 } else if (ReceiverType->isObjCClassType() ||
1954 ReceiverType->isObjCQualifiedClassType()) {
1955 // Handle messages to Class.
1956 // 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);
1963 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1964 // warn if instance method found for a Class message.
1966 Diag(Loc, diag::warn_instance_method_on_class_found)
1967 << Method->getSelector() << Sel;
1968 Diag(Method->getLocation(), diag::note_method_declared_at)
1969 << Method->getDeclName();
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);
1979 Method = LookupPrivateClassMethod(Sel, ClassDecl);
1981 if (Method && DiagnoseUseOfDecl(Method, Loc))
1985 // If not messaging 'self', look for any factory method named 'Sel'.
1986 if (!Receiver || !isSelfExpr(Receiver)) {
1987 Method = LookupFactoryMethodInGlobalPool(Sel,
1988 SourceRange(LBracLoc, RBracLoc),
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,
1994 SourceRange(LBracLoc, RBracLoc),
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);
2008 ObjCInterfaceDecl* ClassDecl = 0;
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.
2015 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2017 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
2018 } 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();
2023 // 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(),
2027 getLangOpts().ObjCAutoRefCount
2028 ? PDiag(diag::err_arc_receiver_forward_instance)
2029 << (Receiver ? Receiver->getSourceRange()
2030 : SourceRange(SuperLoc))
2031 : PDiag(diag::warn_receiver_forward_instance)
2032 << (Receiver ? Receiver->getSourceRange()
2033 : SourceRange(SuperLoc)))) {
2034 if (getLangOpts().ObjCAutoRefCount)
2037 forwardClass = OCIType->getInterfaceDecl();
2038 Diag(Receiver ? Receiver->getLocStart()
2039 : SuperLoc, diag::note_receiver_is_id);
2042 Method = ClassDecl->lookupInstanceMethod(Sel);
2046 // Search protocol qualifiers.
2047 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2050 // If we have implementations in scope, check "private" methods.
2051 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
2053 if (!Method && getLangOpts().ObjCAutoRefCount) {
2054 Diag(Loc, diag::err_arc_may_not_respond)
2055 << OCIType->getPointeeType() << Sel;
2059 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
2060 // 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,
2065 SourceRange(LBracLoc, RBracLoc));
2066 if (Method && !forwardClass)
2067 Diag(Loc, diag::warn_maynot_respond)
2068 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
2072 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
2074 } else if (!getLangOpts().ObjCAutoRefCount &&
2075 !Context.getObjCIdType().isNull() &&
2076 (ReceiverType->isPointerType() ||
2077 ReceiverType->isIntegerType())) {
2078 // Implicitly convert integers and pointers to 'id' but emit a warning.
2080 Diag(Loc, diag::warn_bad_receiver_type)
2082 << Receiver->getSourceRange();
2083 if (ReceiverType->isPointerType())
2084 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2085 CK_CPointerToObjCPointerCast).take();
2087 // TODO: specialized warning on null receivers?
2088 bool IsNull = Receiver->isNullPointerConstant(Context,
2089 Expr::NPC_ValueDependentIsNull);
2090 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2091 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
2093 ReceiverType = Receiver->getType();
2095 ExprResult ReceiverRes;
2096 if (getLangOpts().CPlusPlus)
2097 ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
2098 if (ReceiverRes.isUsable()) {
2099 Receiver = ReceiverRes.take();
2100 return BuildInstanceMessage(Receiver,
2110 // Reject other random receiver types (e.g. structs).
2111 Diag(Loc, diag::err_bad_receiver_type)
2112 << ReceiverType << Receiver->getSourceRange();
2119 // Check the message arguments.
2120 unsigned NumArgs = ArgsIn.size();
2121 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
2122 QualType ReturnType;
2123 ExprValueKind VK = VK_RValue;
2124 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2125 ReceiverType->isObjCQualifiedClassType());
2126 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
2127 ClassMessage, SuperLoc.isValid(),
2128 LBracLoc, RBracLoc, ReturnType, VK))
2131 if (Method && !Method->getResultType()->isVoidType() &&
2132 RequireCompleteType(LBracLoc, Method->getResultType(),
2133 diag::err_illegal_message_expr_incomplete_type))
2136 SourceLocation SelLoc = SelectorLocs.front();
2138 // In ARC, forbid the user from sending messages to
2139 // retain/release/autorelease/dealloc/retainCount explicitly.
2140 if (getLangOpts().ObjCAutoRefCount) {
2141 ObjCMethodFamily family =
2142 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2146 checkInitMethod(Method, ReceiverType);
2152 case OMF_mutableCopy:
2160 case OMF_autorelease:
2161 case OMF_retainCount:
2162 Diag(Loc, diag::err_arc_illegal_explicit_message)
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());
2175 LookupFactoryMethodInGlobalPool(ArgSel,
2176 SelExp->getSourceRange());
2178 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2179 switch (SelFamily) {
2182 case OMF_mutableCopy:
2186 // Issue error, unless ns_returns_not_retained.
2187 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2188 // selector names a +1 method
2190 diag::err_arc_perform_selector_retains);
2191 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2192 << SelMethod->getDeclName();
2196 // +0 call. OK. unless ns_returns_retained.
2197 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2198 // selector names a +1 method
2200 diag::err_arc_perform_selector_retains);
2201 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2202 << SelMethod->getDeclName();
2208 // error (may leak).
2209 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
2210 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2217 // Construct the appropriate ObjCMessageExpr instance.
2218 ObjCMessageExpr *Result;
2219 if (SuperLoc.isValid())
2220 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2221 SuperLoc, /*IsInstanceSuper=*/true,
2222 ReceiverType, Sel, SelectorLocs, Method,
2223 makeArrayRef(Args, NumArgs), RBracLoc,
2226 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2227 Receiver, Sel, SelectorLocs, Method,
2228 makeArrayRef(Args, NumArgs), RBracLoc,
2231 checkCocoaAPI(*this, Result);
2234 if (getLangOpts().ObjCAutoRefCount) {
2236 (Receiver->IgnoreParenImpCasts()->getType().getObjCLifetime()
2237 == Qualifiers::OCL_Weak))
2238 Diag(Receiver->getLocStart(), diag::warn_receiver_is_weak);
2240 // In ARC, annotate delegate init calls.
2241 if (Result->getMethodFamily() == OMF_init &&
2242 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2243 // Only consider init calls *directly* in init implementations,
2244 // not within blocks.
2245 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2246 if (method && method->getMethodFamily() == OMF_init) {
2247 // The implicit assignment to self means we also don't want to
2248 // consume the result.
2249 Result->setDelegateInitCall(true);
2250 return Owned(Result);
2254 // In ARC, check for message sends which are likely to introduce
2256 checkRetainCycles(Result);
2259 return MaybeBindToTemporary(Result);
2262 // ActOnInstanceMessage - used for both unary and keyword messages.
2263 // ArgExprs is optional - if it is present, the number of expressions
2264 // is obtained from Sel.getNumArgs().
2265 ExprResult Sema::ActOnInstanceMessage(Scope *S,
2268 SourceLocation LBracLoc,
2269 ArrayRef<SourceLocation> SelectorLocs,
2270 SourceLocation RBracLoc,
2271 MultiExprArg Args) {
2275 return BuildInstanceMessage(Receiver, Receiver->getType(),
2276 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
2277 LBracLoc, SelectorLocs, RBracLoc, move(Args));
2280 enum ARCConversionTypeClass {
2281 /// int, void, struct A
2287 /// id*, id***, void (^*)(),
2288 ACTC_indirectRetainable,
2290 /// void* might be a normal C type, or it might a CF type.
2296 static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2297 return (ACTC == ACTC_retainable ||
2298 ACTC == ACTC_coreFoundation ||
2299 ACTC == ACTC_voidPtr);
2301 static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2302 return ACTC == ACTC_none ||
2303 ACTC == ACTC_voidPtr ||
2304 ACTC == ACTC_coreFoundation;
2307 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
2308 bool isIndirect = false;
2310 // Ignore an outermost reference type.
2311 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
2312 type = ref->getPointeeType();
2316 // Drill through pointers and arrays recursively.
2318 if (const PointerType *ptr = type->getAs<PointerType>()) {
2319 type = ptr->getPointeeType();
2321 // The first level of pointer may be the innermost pointer on a CF type.
2323 if (type->isVoidType()) return ACTC_voidPtr;
2324 if (type->isRecordType()) return ACTC_coreFoundation;
2326 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2327 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2335 if (type->isObjCARCBridgableType())
2336 return ACTC_indirectRetainable;
2340 if (type->isObjCARCBridgableType())
2341 return ACTC_retainable;
2347 /// A result from the cast checker.
2349 /// Cannot be casted.
2352 /// Can be safely retained or not retained.
2355 /// Can be casted at +0.
2358 /// Can be casted at +1.
2361 ACCResult merge(ACCResult left, ACCResult right) {
2362 if (left == right) return left;
2363 if (left == ACC_bottom) return right;
2364 if (right == ACC_bottom) return left;
2368 /// A checker which white-lists certain expressions whose conversion
2369 /// to or from retainable type would otherwise be forbidden in ARC.
2370 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2371 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2373 ASTContext &Context;
2374 ARCConversionTypeClass SourceClass;
2375 ARCConversionTypeClass TargetClass;
2377 static bool isCFType(QualType type) {
2378 // Someday this can use ns_bridged. For now, it has to do this.
2379 return type->isCARCBridgableType();
2383 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
2384 ARCConversionTypeClass target)
2385 : Context(Context), SourceClass(source), TargetClass(target) {}
2388 ACCResult Visit(Expr *e) {
2389 return super::Visit(e->IgnoreParens());
2392 ACCResult VisitStmt(Stmt *s) {
2396 /// Null pointer constants can be casted however you please.
2397 ACCResult VisitExpr(Expr *e) {
2398 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2403 /// Objective-C string literals can be safely casted.
2404 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2405 // If we're casting to any retainable type, go ahead. Global
2406 // strings are immune to retains, so this is bottom.
2407 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2412 /// Look through certain implicit and explicit casts.
2413 ACCResult VisitCastExpr(CastExpr *e) {
2414 switch (e->getCastKind()) {
2415 case CK_NullToPointer:
2419 case CK_LValueToRValue:
2421 case CK_CPointerToObjCPointerCast:
2422 case CK_BlockPointerToObjCPointerCast:
2423 case CK_AnyPointerToBlockPointerCast:
2424 return Visit(e->getSubExpr());
2431 /// Look through unary extension.
2432 ACCResult VisitUnaryExtension(UnaryOperator *e) {
2433 return Visit(e->getSubExpr());
2436 /// Ignore the LHS of a comma operator.
2437 ACCResult VisitBinComma(BinaryOperator *e) {
2438 return Visit(e->getRHS());
2441 /// Conditional operators are okay if both sides are okay.
2442 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2443 ACCResult left = Visit(e->getTrueExpr());
2444 if (left == ACC_invalid) return ACC_invalid;
2445 return merge(left, Visit(e->getFalseExpr()));
2448 /// Look through pseudo-objects.
2449 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2450 // If we're getting here, we should always have a result.
2451 return Visit(e->getResultExpr());
2454 /// Statement expressions are okay if their result expression is okay.
2455 ACCResult VisitStmtExpr(StmtExpr *e) {
2456 return Visit(e->getSubStmt()->body_back());
2459 /// Some declaration references are okay.
2460 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2461 // References to global constants from system headers are okay.
2462 // These are things like 'kCFStringTransformToLatin'. They are
2463 // can also be assumed to be immune to retains.
2464 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2465 if (isAnyRetainable(TargetClass) &&
2466 isAnyRetainable(SourceClass) &&
2468 var->getStorageClass() == SC_Extern &&
2469 var->getType().isConstQualified() &&
2470 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2478 /// Some calls are okay.
2479 ACCResult VisitCallExpr(CallExpr *e) {
2480 if (FunctionDecl *fn = e->getDirectCallee())
2481 if (ACCResult result = checkCallToFunction(fn))
2484 return super::VisitCallExpr(e);
2487 ACCResult checkCallToFunction(FunctionDecl *fn) {
2488 // Require a CF*Ref return type.
2489 if (!isCFType(fn->getResultType()))
2492 if (!isAnyRetainable(TargetClass))
2495 // Honor an explicit 'not retained' attribute.
2496 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2497 return ACC_plusZero;
2499 // Honor an explicit 'retained' attribute, except that for
2500 // now we're not going to permit implicit handling of +1 results,
2501 // because it's a bit frightening.
2502 if (fn->hasAttr<CFReturnsRetainedAttr>())
2503 return ACC_invalid; // ACC_plusOne if we start accepting this
2505 // Recognize this specific builtin function, which is used by CFSTR.
2506 unsigned builtinID = fn->getBuiltinID();
2507 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2510 // Otherwise, don't do anything implicit with an unaudited function.
2511 if (!fn->hasAttr<CFAuditedTransferAttr>())
2514 // Otherwise, it's +0 unless it follows the create convention.
2515 if (ento::coreFoundation::followsCreateRule(fn))
2516 return ACC_invalid; // ACC_plusOne if we start accepting this
2518 return ACC_plusZero;
2521 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
2522 return checkCallToMethod(e->getMethodDecl());
2525 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
2526 ObjCMethodDecl *method;
2527 if (e->isExplicitProperty())
2528 method = e->getExplicitProperty()->getGetterMethodDecl();
2530 method = e->getImplicitPropertyGetter();
2531 return checkCallToMethod(method);
2534 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
2535 if (!method) return ACC_invalid;
2537 // Check for message sends to functions returning CF types. We
2538 // just obey the Cocoa conventions with these, even though the
2539 // return type is CF.
2540 if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
2543 // If the method is explicitly marked not-retained, it's +0.
2544 if (method->hasAttr<CFReturnsNotRetainedAttr>())
2545 return ACC_plusZero;
2547 // If the method is explicitly marked as returning retained, or its
2548 // selector follows a +1 Cocoa convention, treat it as +1.
2549 if (method->hasAttr<CFReturnsRetainedAttr>())
2552 switch (method->getSelector().getMethodFamily()) {
2555 case OMF_mutableCopy:
2560 // Otherwise, treat it as +0.
2561 return ACC_plusZero;
2568 KnownName(Sema &S, const char *name) {
2569 LookupResult R(S, &S.Context.Idents.get(name), SourceLocation(),
2570 Sema::LookupOrdinaryName);
2571 return S.LookupName(R, S.TUScope, false);
2574 static void addFixitForObjCARCConversion(Sema &S,
2575 DiagnosticBuilder &DiagB,
2576 Sema::CheckedConversionKind CCK,
2577 SourceLocation afterLParen,
2580 const char *bridgeKeyword,
2581 const char *CFBridgeName) {
2582 // We handle C-style and implicit casts here.
2584 case Sema::CCK_ImplicitConversion:
2585 case Sema::CCK_CStyleCast:
2587 case Sema::CCK_FunctionalCast:
2588 case Sema::CCK_OtherCast:
2593 Expr *castedE = castExpr;
2594 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
2595 castedE = CCE->getSubExpr();
2596 castedE = castedE->IgnoreImpCasts();
2597 SourceRange range = castedE->getSourceRange();
2598 if (isa<ParenExpr>(castedE)) {
2599 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2602 std::string namePlusParen = CFBridgeName;
2603 namePlusParen += "(";
2604 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2606 DiagB.AddFixItHint(FixItHint::CreateInsertion(
2607 S.PP.getLocForEndOfToken(range.getEnd()),
2613 if (CCK == Sema::CCK_CStyleCast) {
2614 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
2616 std::string castCode = "(";
2617 castCode += bridgeKeyword;
2618 castCode += castType.getAsString();
2620 Expr *castedE = castExpr->IgnoreImpCasts();
2621 SourceRange range = castedE->getSourceRange();
2622 if (isa<ParenExpr>(castedE)) {
2623 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2627 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2629 DiagB.AddFixItHint(FixItHint::CreateInsertion(
2630 S.PP.getLocForEndOfToken(range.getEnd()),
2637 diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
2638 QualType castType, ARCConversionTypeClass castACTC,
2639 Expr *castExpr, ARCConversionTypeClass exprACTC,
2640 Sema::CheckedConversionKind CCK) {
2641 SourceLocation loc =
2642 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
2644 if (S.makeUnavailableInSystemHeader(loc,
2645 "converts between Objective-C and C pointers in -fobjc-arc"))
2648 QualType castExprType = castExpr->getType();
2650 unsigned srcKind = 0;
2653 case ACTC_coreFoundation:
2655 srcKind = (castExprType->isPointerType() ? 1 : 0);
2657 case ACTC_retainable:
2658 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
2660 case ACTC_indirectRetainable:
2665 // Check whether this could be fixed with a bridge cast.
2666 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
2667 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
2669 // Bridge from an ARC type to a CF type.
2670 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
2672 S.Diag(loc, diag::err_arc_cast_requires_bridge)
2673 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2674 << 2 // of C pointer type
2676 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
2679 << castExpr->getSourceRange();
2680 bool br = KnownName(S, "CFBridgingRelease");
2682 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2683 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2684 castType, castExpr, "__bridge ", 0);
2687 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_transfer)
2688 << castExprType << br;
2689 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2690 castType, castExpr, "__bridge_transfer ",
2691 br ? "CFBridgingRelease" : 0);
2697 // Bridge from a CF type to an ARC type.
2698 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
2699 bool br = KnownName(S, "CFBridgingRetain");
2700 S.Diag(loc, diag::err_arc_cast_requires_bridge)
2701 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2702 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
2704 << 2 // to C pointer type
2707 << castExpr->getSourceRange();
2710 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2711 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2712 castType, castExpr, "__bridge ", 0);
2715 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_retained)
2717 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2718 castType, castExpr, "__bridge_retained ",
2719 br ? "CFBridgingRetain" : 0);
2725 S.Diag(loc, diag::err_arc_mismatched_cast)
2726 << (CCK != Sema::CCK_ImplicitConversion)
2727 << srcKind << castExprType << castType
2728 << castRange << castExpr->getSourceRange();
2731 Sema::ARCConversionResult
2732 Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
2733 Expr *&castExpr, CheckedConversionKind CCK) {
2734 QualType castExprType = castExpr->getType();
2736 // For the purposes of the classification, we assume reference types
2737 // will bind to temporaries.
2738 QualType effCastType = castType;
2739 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
2740 effCastType = ref->getPointeeType();
2742 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
2743 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
2744 if (exprACTC == castACTC) {
2745 // check for viablity and report error if casting an rvalue to a
2746 // life-time qualifier.
2747 if ((castACTC == ACTC_retainable) &&
2748 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
2749 (castType != castExprType)) {
2750 const Type *DT = castType.getTypePtr();
2751 QualType QDT = castType;
2752 // We desugar some types but not others. We ignore those
2753 // that cannot happen in a cast; i.e. auto, and those which
2754 // should not be de-sugared; i.e typedef.
2755 if (const ParenType *PT = dyn_cast<ParenType>(DT))
2756 QDT = PT->desugar();
2757 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
2758 QDT = TP->desugar();
2759 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
2760 QDT = AT->desugar();
2761 if (QDT != castType &&
2762 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
2763 SourceLocation loc =
2764 (castRange.isValid() ? castRange.getBegin()
2765 : castExpr->getExprLoc());
2766 Diag(loc, diag::err_arc_nolifetime_behavior);
2772 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
2774 // Allow all of these types to be cast to integer types (but not
2776 if (castACTC == ACTC_none && castType->isIntegralType(Context))
2779 // Allow casts between pointers to lifetime types (e.g., __strong id*)
2780 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
2781 // must be explicit.
2782 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
2784 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
2785 CCK != CCK_ImplicitConversion)
2788 switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
2789 // For invalid casts, fall through.
2793 // Do nothing for both bottom and +0.
2798 // If the result is +1, consume it here.
2800 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
2801 CK_ARCConsumeObject, castExpr,
2803 ExprNeedsCleanups = true;
2807 // If this is a non-implicit cast from id or block type to a
2808 // CoreFoundation type, delay complaining in case the cast is used
2809 // in an acceptable context.
2810 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
2811 CCK != CCK_ImplicitConversion)
2812 return ACR_unbridged;
2814 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
2815 castExpr, exprACTC, CCK);
2819 /// Given that we saw an expression with the ARCUnbridgedCastTy
2820 /// placeholder type, complain bitterly.
2821 void Sema::diagnoseARCUnbridgedCast(Expr *e) {
2822 // We expect the spurious ImplicitCastExpr to already have been stripped.
2823 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
2824 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
2826 SourceRange castRange;
2828 CheckedConversionKind CCK;
2830 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
2831 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
2832 castType = cast->getTypeAsWritten();
2833 CCK = CCK_CStyleCast;
2834 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
2835 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
2836 castType = cast->getTypeAsWritten();
2837 CCK = CCK_OtherCast;
2839 castType = cast->getType();
2840 CCK = CCK_ImplicitConversion;
2843 ARCConversionTypeClass castACTC =
2844 classifyTypeForARCConversion(castType.getNonReferenceType());
2846 Expr *castExpr = realCast->getSubExpr();
2847 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
2849 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
2850 castExpr, ACTC_retainable, CCK);
2853 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
2854 /// type, remove the placeholder cast.
2855 Expr *Sema::stripARCUnbridgedCast(Expr *e) {
2856 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
2858 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
2859 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
2860 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
2861 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
2862 assert(uo->getOpcode() == UO_Extension);
2863 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
2864 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
2865 sub->getValueKind(), sub->getObjectKind(),
2866 uo->getOperatorLoc());
2867 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
2868 assert(!gse->isResultDependent());
2870 unsigned n = gse->getNumAssocs();
2871 SmallVector<Expr*, 4> subExprs(n);
2872 SmallVector<TypeSourceInfo*, 4> subTypes(n);
2873 for (unsigned i = 0; i != n; ++i) {
2874 subTypes[i] = gse->getAssocTypeSourceInfo(i);
2875 Expr *sub = gse->getAssocExpr(i);
2876 if (i == gse->getResultIndex())
2877 sub = stripARCUnbridgedCast(sub);
2881 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
2882 gse->getControllingExpr(),
2883 subTypes.data(), subExprs.data(),
2884 n, gse->getDefaultLoc(),
2885 gse->getRParenLoc(),
2886 gse->containsUnexpandedParameterPack(),
2887 gse->getResultIndex());
2889 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
2890 return cast<ImplicitCastExpr>(e)->getSubExpr();
2894 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
2895 QualType exprType) {
2896 QualType canCastType =
2897 Context.getCanonicalType(castType).getUnqualifiedType();
2898 QualType canExprType =
2899 Context.getCanonicalType(exprType).getUnqualifiedType();
2900 if (isa<ObjCObjectPointerType>(canCastType) &&
2901 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
2902 canExprType->isObjCObjectPointerType()) {
2903 if (const ObjCObjectPointerType *ObjT =
2904 canExprType->getAs<ObjCObjectPointerType>())
2905 if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
2911 /// Look for an ObjCReclaimReturnedObject cast and destroy it.
2912 static Expr *maybeUndoReclaimObject(Expr *e) {
2913 // For now, we just undo operands that are *immediately* reclaim
2914 // expressions, which prevents the vast majority of potential
2915 // problems here. To catch them all, we'd need to rebuild arbitrary
2916 // value-propagating subexpressions --- we can't reliably rebuild
2917 // in-place because of expression sharing.
2918 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2919 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
2920 return ice->getSubExpr();
2925 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
2926 ObjCBridgeCastKind Kind,
2927 SourceLocation BridgeKeywordLoc,
2928 TypeSourceInfo *TSInfo,
2930 ExprResult SubResult = UsualUnaryConversions(SubExpr);
2931 if (SubResult.isInvalid()) return ExprError();
2932 SubExpr = SubResult.take();
2934 QualType T = TSInfo->getType();
2935 QualType FromType = SubExpr->getType();
2939 bool MustConsume = false;
2940 if (T->isDependentType() || SubExpr->isTypeDependent()) {
2941 // Okay: we'll build a dependent expression type.
2943 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
2945 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
2946 : CK_CPointerToObjCPointerCast);
2951 case OBC_BridgeRetained: {
2952 bool br = KnownName(*this, "CFBridgingRelease");
2953 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2956 << (T->isBlockPointerType()? 1 : 0)
2958 << SubExpr->getSourceRange()
2960 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2961 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
2962 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
2964 << FixItHint::CreateReplacement(BridgeKeywordLoc,
2965 br ? "CFBridgingRelease "
2966 : "__bridge_transfer ");
2972 case OBC_BridgeTransfer:
2973 // We must consume the Objective-C object produced by the cast.
2977 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
2982 // Reclaiming a value that's going to be __bridge-casted to CF
2983 // is very dangerous, so we don't do it.
2984 SubExpr = maybeUndoReclaimObject(SubExpr);
2987 case OBC_BridgeRetained:
2988 // Produce the object before casting it.
2989 SubExpr = ImplicitCastExpr::Create(Context, FromType,
2990 CK_ARCProduceObject,
2991 SubExpr, 0, VK_RValue);
2994 case OBC_BridgeTransfer: {
2995 bool br = KnownName(*this, "CFBridgingRetain");
2996 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2997 << (FromType->isBlockPointerType()? 1 : 0)
3001 << SubExpr->getSourceRange()
3004 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3005 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3006 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
3008 << FixItHint::CreateReplacement(BridgeKeywordLoc,
3009 br ? "CFBridgingRetain " : "__bridge_retained");
3016 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3017 << FromType << T << Kind
3018 << SubExpr->getSourceRange()
3019 << TSInfo->getTypeLoc().getSourceRange();
3023 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
3028 ExprNeedsCleanups = true;
3029 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
3036 ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
3037 SourceLocation LParenLoc,
3038 ObjCBridgeCastKind Kind,
3039 SourceLocation BridgeKeywordLoc,
3041 SourceLocation RParenLoc,
3043 TypeSourceInfo *TSInfo = 0;
3044 QualType T = GetTypeFromParser(Type, &TSInfo);
3046 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3047 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,