1 //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for Objective-C expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/ExprObjC.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
21 #include "clang/Edit/Commit.h"
22 #include "clang/Edit/Rewriters.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Sema/Initialization.h"
25 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/ScopeInfo.h"
28 #include "llvm/ADT/SmallString.h"
29 
30 using namespace clang;
31 using namespace sema;
32 using llvm::makeArrayRef;
33 
34 ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
35                                         Expr **strings,
36                                         unsigned NumStrings) {
37   StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
38 
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];
44 
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;
50 
51     for (unsigned i = 0; i != NumStrings; ++i) {
52       S = Strings[i];
53 
54       // ObjC strings can't be wide or UTF.
55       if (!S->isAscii()) {
56         Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
57           << S->getSourceRange();
58         return true;
59       }
60 
61       // Append the string.
62       StrBuf += S->getString();
63 
64       // Get the locations of the string tokens.
65       StrLocs.append(S->tokloc_begin(), S->tokloc_end());
66     }
67 
68     // Create the aggregate string with the appropriate content and location
69     // information.
70     const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
71     assert(CAT && "String literal not of constant array type!");
72     QualType StrTy = Context.getConstantArrayType(
73         CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1),
74         CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
75     S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
76                               /*Pascal=*/false, StrTy, &StrLocs[0],
77                               StrLocs.size());
78   }
79 
80   return BuildObjCStringLiteral(AtLocs[0], S);
81 }
82 
83 ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
84   // Verify that this composite string is acceptable for ObjC strings.
85   if (CheckObjCString(S))
86     return true;
87 
88   // Initialize the constant string interface lazily. This assumes
89   // the NSString interface is seen in this translation unit. Note: We
90   // don't use NSConstantString, since the runtime team considers this
91   // interface private (even though it appears in the header files).
92   QualType Ty = Context.getObjCConstantStringInterface();
93   if (!Ty.isNull()) {
94     Ty = Context.getObjCObjectPointerType(Ty);
95   } else if (getLangOpts().NoConstantCFStrings) {
96     IdentifierInfo *NSIdent=0;
97     std::string StringClass(getLangOpts().ObjCConstantStringClass);
98 
99     if (StringClass.empty())
100       NSIdent = &Context.Idents.get("NSConstantString");
101     else
102       NSIdent = &Context.Idents.get(StringClass);
103 
104     NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
105                                      LookupOrdinaryName);
106     if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
107       Context.setObjCConstantStringInterface(StrIF);
108       Ty = Context.getObjCConstantStringInterface();
109       Ty = Context.getObjCObjectPointerType(Ty);
110     } else {
111       // If there is no NSConstantString interface defined then treat this
112       // as error and recover from it.
113       Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
114         << S->getSourceRange();
115       Ty = Context.getObjCIdType();
116     }
117   } else {
118     IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
119     NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
120                                      LookupOrdinaryName);
121     if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
122       Context.setObjCConstantStringInterface(StrIF);
123       Ty = Context.getObjCConstantStringInterface();
124       Ty = Context.getObjCObjectPointerType(Ty);
125     } else {
126       // If there is no NSString interface defined, implicitly declare
127       // a @class NSString; and use that instead. This is to make sure
128       // type of an NSString literal is represented correctly, instead of
129       // being an 'id' type.
130       Ty = Context.getObjCNSStringType();
131       if (Ty.isNull()) {
132         ObjCInterfaceDecl *NSStringIDecl =
133           ObjCInterfaceDecl::Create (Context,
134                                      Context.getTranslationUnitDecl(),
135                                      SourceLocation(), NSIdent,
136                                      0, SourceLocation());
137         Ty = Context.getObjCInterfaceType(NSStringIDecl);
138         Context.setObjCNSStringType(Ty);
139       }
140       Ty = Context.getObjCObjectPointerType(Ty);
141     }
142   }
143 
144   return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
145 }
146 
147 /// \brief Emits an error if the given method does not exist, or if the return
148 /// type is not an Objective-C object.
149 static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
150                                  const ObjCInterfaceDecl *Class,
151                                  Selector Sel, const ObjCMethodDecl *Method) {
152   if (!Method) {
153     // FIXME: Is there a better way to avoid quotes than using getName()?
154     S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
155     return false;
156   }
157 
158   // Make sure the return type is reasonable.
159   QualType ReturnType = Method->getReturnType();
160   if (!ReturnType->isObjCObjectPointerType()) {
161     S.Diag(Loc, diag::err_objc_literal_method_sig)
162       << Sel;
163     S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
164       << ReturnType;
165     return false;
166   }
167 
168   return true;
169 }
170 
171 /// \brief Retrieve the NSNumber factory method that should be used to create
172 /// an Objective-C literal for the given type.
173 static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
174                                                 QualType NumberType,
175                                                 bool isLiteral = false,
176                                                 SourceRange R = SourceRange()) {
177   Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
178       S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
179 
180   if (!Kind) {
181     if (isLiteral) {
182       S.Diag(Loc, diag::err_invalid_nsnumber_type)
183         << NumberType << R;
184     }
185     return 0;
186   }
187 
188   // If we already looked up this method, we're done.
189   if (S.NSNumberLiteralMethods[*Kind])
190     return S.NSNumberLiteralMethods[*Kind];
191 
192   Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
193                                                         /*Instance=*/false);
194 
195   ASTContext &CX = S.Context;
196 
197   // Look up the NSNumber class, if we haven't done so already. It's cached
198   // in the Sema instance.
199   if (!S.NSNumberDecl) {
200     IdentifierInfo *NSNumberId =
201       S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber);
202     NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId,
203                                        Loc, Sema::LookupOrdinaryName);
204     S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
205     if (!S.NSNumberDecl) {
206       if (S.getLangOpts().DebuggerObjCLiteral) {
207         // Create a stub definition of NSNumber.
208         S.NSNumberDecl = ObjCInterfaceDecl::Create(CX,
209                                                    CX.getTranslationUnitDecl(),
210                                                    SourceLocation(), NSNumberId,
211                                                    0, SourceLocation());
212       } else {
213         // Otherwise, require a declaration of NSNumber.
214         S.Diag(Loc, diag::err_undeclared_nsnumber);
215         return 0;
216       }
217     } else if (!S.NSNumberDecl->hasDefinition()) {
218       S.Diag(Loc, diag::err_undeclared_nsnumber);
219       return 0;
220     }
221 
222     // generate the pointer to NSNumber type.
223     QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
224     S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
225   }
226 
227   // Look for the appropriate method within NSNumber.
228   ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
229   if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
230     // create a stub definition this NSNumber factory method.
231     TypeSourceInfo *ReturnTInfo = 0;
232     Method =
233         ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
234                                S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
235                                /*isInstance=*/false, /*isVariadic=*/false,
236                                /*isPropertyAccessor=*/false,
237                                /*isImplicitlyDeclared=*/true,
238                                /*isDefined=*/false, ObjCMethodDecl::Required,
239                                /*HasRelatedResultType=*/false);
240     ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
241                                              SourceLocation(), SourceLocation(),
242                                              &CX.Idents.get("value"),
243                                              NumberType, /*TInfo=*/0, SC_None,
244                                              0);
245     Method->setMethodParams(S.Context, value, None);
246   }
247 
248   if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
249     return 0;
250 
251   // Note: if the parameter type is out-of-line, we'll catch it later in the
252   // implicit conversion.
253 
254   S.NSNumberLiteralMethods[*Kind] = Method;
255   return Method;
256 }
257 
258 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
259 /// numeric literal expression. Type of the expression will be "NSNumber *".
260 ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
261   // Determine the type of the literal.
262   QualType NumberType = Number->getType();
263   if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
264     // In C, character literals have type 'int'. That's not the type we want
265     // to use to determine the Objective-c literal kind.
266     switch (Char->getKind()) {
267     case CharacterLiteral::Ascii:
268       NumberType = Context.CharTy;
269       break;
270 
271     case CharacterLiteral::Wide:
272       NumberType = Context.getWideCharType();
273       break;
274 
275     case CharacterLiteral::UTF16:
276       NumberType = Context.Char16Ty;
277       break;
278 
279     case CharacterLiteral::UTF32:
280       NumberType = Context.Char32Ty;
281       break;
282     }
283   }
284 
285   // Look for the appropriate method within NSNumber.
286   // Construct the literal.
287   SourceRange NR(Number->getSourceRange());
288   ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
289                                                     true, NR);
290   if (!Method)
291     return ExprError();
292 
293   // Convert the number to the type that the parameter expects.
294   ParmVarDecl *ParamDecl = Method->param_begin()[0];
295   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
296                                                                     ParamDecl);
297   ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
298                                                          SourceLocation(),
299                                                          Owned(Number));
300   if (ConvertedNumber.isInvalid())
301     return ExprError();
302   Number = ConvertedNumber.get();
303 
304   // Use the effective source range of the literal, including the leading '@'.
305   return MaybeBindToTemporary(
306            new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
307                                        SourceRange(AtLoc, NR.getEnd())));
308 }
309 
310 ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
311                                       SourceLocation ValueLoc,
312                                       bool Value) {
313   ExprResult Inner;
314   if (getLangOpts().CPlusPlus) {
315     Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
316   } else {
317     // C doesn't actually have a way to represent literal values of type
318     // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
319     Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
320     Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
321                               CK_IntegralToBoolean);
322   }
323 
324   return BuildObjCNumericLiteral(AtLoc, Inner.get());
325 }
326 
327 /// \brief Check that the given expression is a valid element of an Objective-C
328 /// collection literal.
329 static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
330                                                     QualType T,
331                                                     bool ArrayLiteral = false) {
332   // If the expression is type-dependent, there's nothing for us to do.
333   if (Element->isTypeDependent())
334     return Element;
335 
336   ExprResult Result = S.CheckPlaceholderExpr(Element);
337   if (Result.isInvalid())
338     return ExprError();
339   Element = Result.get();
340 
341   // In C++, check for an implicit conversion to an Objective-C object pointer
342   // type.
343   if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
344     InitializedEntity Entity
345       = InitializedEntity::InitializeParameter(S.Context, T,
346                                                /*Consumed=*/false);
347     InitializationKind Kind
348       = InitializationKind::CreateCopy(Element->getLocStart(),
349                                        SourceLocation());
350     InitializationSequence Seq(S, Entity, Kind, Element);
351     if (!Seq.Failed())
352       return Seq.Perform(S, Entity, Kind, Element);
353   }
354 
355   Expr *OrigElement = Element;
356 
357   // Perform lvalue-to-rvalue conversion.
358   Result = S.DefaultLvalueConversion(Element);
359   if (Result.isInvalid())
360     return ExprError();
361   Element = Result.get();
362 
363   // Make sure that we have an Objective-C pointer type or block.
364   if (!Element->getType()->isObjCObjectPointerType() &&
365       !Element->getType()->isBlockPointerType()) {
366     bool Recovered = false;
367 
368     // If this is potentially an Objective-C numeric literal, add the '@'.
369     if (isa<IntegerLiteral>(OrigElement) ||
370         isa<CharacterLiteral>(OrigElement) ||
371         isa<FloatingLiteral>(OrigElement) ||
372         isa<ObjCBoolLiteralExpr>(OrigElement) ||
373         isa<CXXBoolLiteralExpr>(OrigElement)) {
374       if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
375         int Which = isa<CharacterLiteral>(OrigElement) ? 1
376                   : (isa<CXXBoolLiteralExpr>(OrigElement) ||
377                      isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
378                   : 3;
379 
380         S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
381           << Which << OrigElement->getSourceRange()
382           << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
383 
384         Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
385                                            OrigElement);
386         if (Result.isInvalid())
387           return ExprError();
388 
389         Element = Result.get();
390         Recovered = true;
391       }
392     }
393     // If this is potentially an Objective-C string literal, add the '@'.
394     else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
395       if (String->isAscii()) {
396         S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
397           << 0 << OrigElement->getSourceRange()
398           << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
399 
400         Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
401         if (Result.isInvalid())
402           return ExprError();
403 
404         Element = Result.get();
405         Recovered = true;
406       }
407     }
408 
409     if (!Recovered) {
410       S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
411         << Element->getType();
412       return ExprError();
413     }
414   }
415   if (ArrayLiteral)
416     if (ObjCStringLiteral *getString =
417           dyn_cast<ObjCStringLiteral>(OrigElement)) {
418       if (StringLiteral *SL = getString->getString()) {
419         unsigned numConcat = SL->getNumConcatenated();
420         if (numConcat > 1) {
421           // Only warn if the concatenated string doesn't come from a macro.
422           bool hasMacro = false;
423           for (unsigned i = 0; i < numConcat ; ++i)
424             if (SL->getStrTokenLoc(i).isMacroID()) {
425               hasMacro = true;
426               break;
427             }
428           if (!hasMacro)
429             S.Diag(Element->getLocStart(),
430                    diag::warn_concatenated_nsarray_literal)
431               << Element->getType();
432         }
433       }
434     }
435 
436   // Make sure that the element has the type that the container factory
437   // function expects.
438   return S.PerformCopyInitialization(
439            InitializedEntity::InitializeParameter(S.Context, T,
440                                                   /*Consumed=*/false),
441            Element->getLocStart(), Element);
442 }
443 
444 ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
445   if (ValueExpr->isTypeDependent()) {
446     ObjCBoxedExpr *BoxedExpr =
447       new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, NULL, SR);
448     return Owned(BoxedExpr);
449   }
450   ObjCMethodDecl *BoxingMethod = NULL;
451   QualType BoxedType;
452   // Convert the expression to an RValue, so we can check for pointer types...
453   ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
454   if (RValue.isInvalid()) {
455     return ExprError();
456   }
457   ValueExpr = RValue.get();
458   QualType ValueType(ValueExpr->getType());
459   if (const PointerType *PT = ValueType->getAs<PointerType>()) {
460     QualType PointeeType = PT->getPointeeType();
461     if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
462 
463       if (!NSStringDecl) {
464         IdentifierInfo *NSStringId =
465           NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
466         NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
467                                            SR.getBegin(), LookupOrdinaryName);
468         NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
469         if (!NSStringDecl) {
470           if (getLangOpts().DebuggerObjCLiteral) {
471             // Support boxed expressions in the debugger w/o NSString declaration.
472             DeclContext *TU = Context.getTranslationUnitDecl();
473             NSStringDecl = ObjCInterfaceDecl::Create(Context, TU,
474                                                      SourceLocation(),
475                                                      NSStringId,
476                                                      0, SourceLocation());
477           } else {
478             Diag(SR.getBegin(), diag::err_undeclared_nsstring);
479             return ExprError();
480           }
481         } else if (!NSStringDecl->hasDefinition()) {
482           Diag(SR.getBegin(), diag::err_undeclared_nsstring);
483           return ExprError();
484         }
485         assert(NSStringDecl && "NSStringDecl should not be NULL");
486         QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
487         NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
488       }
489 
490       if (!StringWithUTF8StringMethod) {
491         IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
492         Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
493 
494         // Look for the appropriate method within NSString.
495         BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
496         if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
497           // Debugger needs to work even if NSString hasn't been defined.
498           TypeSourceInfo *ReturnTInfo = 0;
499           ObjCMethodDecl *M = ObjCMethodDecl::Create(
500               Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
501               NSStringPointer, ReturnTInfo, NSStringDecl,
502               /*isInstance=*/false, /*isVariadic=*/false,
503               /*isPropertyAccessor=*/false,
504               /*isImplicitlyDeclared=*/true,
505               /*isDefined=*/false, ObjCMethodDecl::Required,
506               /*HasRelatedResultType=*/false);
507           QualType ConstCharType = Context.CharTy.withConst();
508           ParmVarDecl *value =
509             ParmVarDecl::Create(Context, M,
510                                 SourceLocation(), SourceLocation(),
511                                 &Context.Idents.get("value"),
512                                 Context.getPointerType(ConstCharType),
513                                 /*TInfo=*/0,
514                                 SC_None, 0);
515           M->setMethodParams(Context, value, None);
516           BoxingMethod = M;
517         }
518 
519         if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
520                                   stringWithUTF8String, BoxingMethod))
521            return ExprError();
522 
523         StringWithUTF8StringMethod = BoxingMethod;
524       }
525 
526       BoxingMethod = StringWithUTF8StringMethod;
527       BoxedType = NSStringPointer;
528     }
529   } else if (ValueType->isBuiltinType()) {
530     // The other types we support are numeric, char and BOOL/bool. We could also
531     // provide limited support for structure types, such as NSRange, NSRect, and
532     // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
533     // for more details.
534 
535     // Check for a top-level character literal.
536     if (const CharacterLiteral *Char =
537         dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
538       // In C, character literals have type 'int'. That's not the type we want
539       // to use to determine the Objective-c literal kind.
540       switch (Char->getKind()) {
541       case CharacterLiteral::Ascii:
542         ValueType = Context.CharTy;
543         break;
544 
545       case CharacterLiteral::Wide:
546         ValueType = Context.getWideCharType();
547         break;
548 
549       case CharacterLiteral::UTF16:
550         ValueType = Context.Char16Ty;
551         break;
552 
553       case CharacterLiteral::UTF32:
554         ValueType = Context.Char32Ty;
555         break;
556       }
557     }
558 
559     // FIXME:  Do I need to do anything special with BoolTy expressions?
560 
561     // Look for the appropriate method within NSNumber.
562     BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
563     BoxedType = NSNumberPointer;
564 
565   } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
566     if (!ET->getDecl()->isComplete()) {
567       Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type)
568         << ValueType << ValueExpr->getSourceRange();
569       return ExprError();
570     }
571 
572     BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(),
573                                             ET->getDecl()->getIntegerType());
574     BoxedType = NSNumberPointer;
575   }
576 
577   if (!BoxingMethod) {
578     Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
579       << ValueType << ValueExpr->getSourceRange();
580     return ExprError();
581   }
582 
583   // Convert the expression to the type that the parameter requires.
584   ParmVarDecl *ParamDecl = BoxingMethod->param_begin()[0];
585   InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
586                                                                     ParamDecl);
587   ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
588                                                             SourceLocation(),
589                                                             Owned(ValueExpr));
590   if (ConvertedValueExpr.isInvalid())
591     return ExprError();
592   ValueExpr = ConvertedValueExpr.get();
593 
594   ObjCBoxedExpr *BoxedExpr =
595     new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
596                                       BoxingMethod, SR);
597   return MaybeBindToTemporary(BoxedExpr);
598 }
599 
600 /// Build an ObjC subscript pseudo-object expression, given that
601 /// that's supported by the runtime.
602 ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
603                                         Expr *IndexExpr,
604                                         ObjCMethodDecl *getterMethod,
605                                         ObjCMethodDecl *setterMethod) {
606   assert(!LangOpts.isSubscriptPointerArithmetic());
607 
608   // We can't get dependent types here; our callers should have
609   // filtered them out.
610   assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
611          "base or index cannot have dependent type here");
612 
613   // Filter out placeholders in the index.  In theory, overloads could
614   // be preserved here, although that might not actually work correctly.
615   ExprResult Result = CheckPlaceholderExpr(IndexExpr);
616   if (Result.isInvalid())
617     return ExprError();
618   IndexExpr = Result.get();
619 
620   // Perform lvalue-to-rvalue conversion on the base.
621   Result = DefaultLvalueConversion(BaseExpr);
622   if (Result.isInvalid())
623     return ExprError();
624   BaseExpr = Result.get();
625 
626   // Build the pseudo-object expression.
627   return Owned(ObjCSubscriptRefExpr::Create(Context,
628                                             BaseExpr,
629                                             IndexExpr,
630                                             Context.PseudoObjectTy,
631                                             getterMethod,
632                                             setterMethod, RB));
633 
634 }
635 
636 ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
637   // Look up the NSArray class, if we haven't done so already.
638   if (!NSArrayDecl) {
639     NamedDecl *IF = LookupSingleName(TUScope,
640                                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
641                                  SR.getBegin(),
642                                  LookupOrdinaryName);
643     NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
644     if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
645       NSArrayDecl =  ObjCInterfaceDecl::Create (Context,
646                             Context.getTranslationUnitDecl(),
647                             SourceLocation(),
648                             NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
649                             0, SourceLocation());
650 
651     if (!NSArrayDecl) {
652       Diag(SR.getBegin(), diag::err_undeclared_nsarray);
653       return ExprError();
654     }
655   }
656 
657   // Find the arrayWithObjects:count: method, if we haven't done so already.
658   QualType IdT = Context.getObjCIdType();
659   if (!ArrayWithObjectsMethod) {
660     Selector
661       Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
662     ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
663     if (!Method && getLangOpts().DebuggerObjCLiteral) {
664       TypeSourceInfo *ReturnTInfo = 0;
665       Method = ObjCMethodDecl::Create(
666           Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
667           Context.getTranslationUnitDecl(), false /*Instance*/,
668           false /*isVariadic*/,
669           /*isPropertyAccessor=*/false,
670           /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
671           ObjCMethodDecl::Required, false);
672       SmallVector<ParmVarDecl *, 2> Params;
673       ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
674                                                  SourceLocation(),
675                                                  SourceLocation(),
676                                                  &Context.Idents.get("objects"),
677                                                  Context.getPointerType(IdT),
678                                                  /*TInfo=*/0, SC_None, 0);
679       Params.push_back(objects);
680       ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
681                                              SourceLocation(),
682                                              SourceLocation(),
683                                              &Context.Idents.get("cnt"),
684                                              Context.UnsignedLongTy,
685                                              /*TInfo=*/0, SC_None, 0);
686       Params.push_back(cnt);
687       Method->setMethodParams(Context, Params, None);
688     }
689 
690     if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
691       return ExprError();
692 
693     // Dig out the type that all elements should be converted to.
694     QualType T = Method->param_begin()[0]->getType();
695     const PointerType *PtrT = T->getAs<PointerType>();
696     if (!PtrT ||
697         !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
698       Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
699         << Sel;
700       Diag(Method->param_begin()[0]->getLocation(),
701            diag::note_objc_literal_method_param)
702         << 0 << T
703         << Context.getPointerType(IdT.withConst());
704       return ExprError();
705     }
706 
707     // Check that the 'count' parameter is integral.
708     if (!Method->param_begin()[1]->getType()->isIntegerType()) {
709       Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
710         << Sel;
711       Diag(Method->param_begin()[1]->getLocation(),
712            diag::note_objc_literal_method_param)
713         << 1
714         << Method->param_begin()[1]->getType()
715         << "integral";
716       return ExprError();
717     }
718 
719     // We've found a good +arrayWithObjects:count: method. Save it!
720     ArrayWithObjectsMethod = Method;
721   }
722 
723   QualType ObjectsType = ArrayWithObjectsMethod->param_begin()[0]->getType();
724   QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
725 
726   // Check that each of the elements provided is valid in a collection literal,
727   // performing conversions as necessary.
728   Expr **ElementsBuffer = Elements.data();
729   for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
730     ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
731                                                              ElementsBuffer[I],
732                                                              RequiredType, true);
733     if (Converted.isInvalid())
734       return ExprError();
735 
736     ElementsBuffer[I] = Converted.get();
737   }
738 
739   QualType Ty
740     = Context.getObjCObjectPointerType(
741                                     Context.getObjCInterfaceType(NSArrayDecl));
742 
743   return MaybeBindToTemporary(
744            ObjCArrayLiteral::Create(Context, Elements, Ty,
745                                     ArrayWithObjectsMethod, SR));
746 }
747 
748 ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
749                                             ObjCDictionaryElement *Elements,
750                                             unsigned NumElements) {
751   // Look up the NSDictionary class, if we haven't done so already.
752   if (!NSDictionaryDecl) {
753     NamedDecl *IF = LookupSingleName(TUScope,
754                             NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
755                             SR.getBegin(), LookupOrdinaryName);
756     NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
757     if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
758       NSDictionaryDecl =  ObjCInterfaceDecl::Create (Context,
759                             Context.getTranslationUnitDecl(),
760                             SourceLocation(),
761                             NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
762                             0, SourceLocation());
763 
764     if (!NSDictionaryDecl) {
765       Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
766       return ExprError();
767     }
768   }
769 
770   // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
771   // so already.
772   QualType IdT = Context.getObjCIdType();
773   if (!DictionaryWithObjectsMethod) {
774     Selector Sel = NSAPIObj->getNSDictionarySelector(
775                                NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
776     ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
777     if (!Method && getLangOpts().DebuggerObjCLiteral) {
778       Method = ObjCMethodDecl::Create(Context,
779                            SourceLocation(), SourceLocation(), Sel,
780                            IdT,
781                            0 /*TypeSourceInfo */,
782                            Context.getTranslationUnitDecl(),
783                            false /*Instance*/, false/*isVariadic*/,
784                            /*isPropertyAccessor=*/false,
785                            /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
786                            ObjCMethodDecl::Required,
787                            false);
788       SmallVector<ParmVarDecl *, 3> Params;
789       ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
790                                                  SourceLocation(),
791                                                  SourceLocation(),
792                                                  &Context.Idents.get("objects"),
793                                                  Context.getPointerType(IdT),
794                                                  /*TInfo=*/0, SC_None, 0);
795       Params.push_back(objects);
796       ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
797                                               SourceLocation(),
798                                               SourceLocation(),
799                                               &Context.Idents.get("keys"),
800                                               Context.getPointerType(IdT),
801                                               /*TInfo=*/0, SC_None, 0);
802       Params.push_back(keys);
803       ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
804                                              SourceLocation(),
805                                              SourceLocation(),
806                                              &Context.Idents.get("cnt"),
807                                              Context.UnsignedLongTy,
808                                              /*TInfo=*/0, SC_None, 0);
809       Params.push_back(cnt);
810       Method->setMethodParams(Context, Params, None);
811     }
812 
813     if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
814                               Method))
815        return ExprError();
816 
817     // Dig out the type that all values should be converted to.
818     QualType ValueT = Method->param_begin()[0]->getType();
819     const PointerType *PtrValue = ValueT->getAs<PointerType>();
820     if (!PtrValue ||
821         !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
822       Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
823         << Sel;
824       Diag(Method->param_begin()[0]->getLocation(),
825            diag::note_objc_literal_method_param)
826         << 0 << ValueT
827         << Context.getPointerType(IdT.withConst());
828       return ExprError();
829     }
830 
831     // Dig out the type that all keys should be converted to.
832     QualType KeyT = Method->param_begin()[1]->getType();
833     const PointerType *PtrKey = KeyT->getAs<PointerType>();
834     if (!PtrKey ||
835         !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
836                                         IdT)) {
837       bool err = true;
838       if (PtrKey) {
839         if (QIDNSCopying.isNull()) {
840           // key argument of selector is id<NSCopying>?
841           if (ObjCProtocolDecl *NSCopyingPDecl =
842               LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
843             ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
844             QIDNSCopying =
845               Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
846                                         (ObjCProtocolDecl**) PQ,1);
847             QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
848           }
849         }
850         if (!QIDNSCopying.isNull())
851           err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
852                                                 QIDNSCopying);
853       }
854 
855       if (err) {
856         Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
857           << Sel;
858         Diag(Method->param_begin()[1]->getLocation(),
859              diag::note_objc_literal_method_param)
860           << 1 << KeyT
861           << Context.getPointerType(IdT.withConst());
862         return ExprError();
863       }
864     }
865 
866     // Check that the 'count' parameter is integral.
867     QualType CountType = Method->param_begin()[2]->getType();
868     if (!CountType->isIntegerType()) {
869       Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
870         << Sel;
871       Diag(Method->param_begin()[2]->getLocation(),
872            diag::note_objc_literal_method_param)
873         << 2 << CountType
874         << "integral";
875       return ExprError();
876     }
877 
878     // We've found a good +dictionaryWithObjects:keys:count: method; save it!
879     DictionaryWithObjectsMethod = Method;
880   }
881 
882   QualType ValuesT = DictionaryWithObjectsMethod->param_begin()[0]->getType();
883   QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
884   QualType KeysT = DictionaryWithObjectsMethod->param_begin()[1]->getType();
885   QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
886 
887   // Check that each of the keys and values provided is valid in a collection
888   // literal, performing conversions as necessary.
889   bool HasPackExpansions = false;
890   for (unsigned I = 0, N = NumElements; I != N; ++I) {
891     // Check the key.
892     ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
893                                                        KeyT);
894     if (Key.isInvalid())
895       return ExprError();
896 
897     // Check the value.
898     ExprResult Value
899       = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
900     if (Value.isInvalid())
901       return ExprError();
902 
903     Elements[I].Key = Key.get();
904     Elements[I].Value = Value.get();
905 
906     if (Elements[I].EllipsisLoc.isInvalid())
907       continue;
908 
909     if (!Elements[I].Key->containsUnexpandedParameterPack() &&
910         !Elements[I].Value->containsUnexpandedParameterPack()) {
911       Diag(Elements[I].EllipsisLoc,
912            diag::err_pack_expansion_without_parameter_packs)
913         << SourceRange(Elements[I].Key->getLocStart(),
914                        Elements[I].Value->getLocEnd());
915       return ExprError();
916     }
917 
918     HasPackExpansions = true;
919   }
920 
921 
922   QualType Ty
923     = Context.getObjCObjectPointerType(
924                                 Context.getObjCInterfaceType(NSDictionaryDecl));
925   return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
926       Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty,
927       DictionaryWithObjectsMethod, SR));
928 }
929 
930 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
931                                       TypeSourceInfo *EncodedTypeInfo,
932                                       SourceLocation RParenLoc) {
933   QualType EncodedType = EncodedTypeInfo->getType();
934   QualType StrTy;
935   if (EncodedType->isDependentType())
936     StrTy = Context.DependentTy;
937   else {
938     if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
939         !EncodedType->isVoidType()) // void is handled too.
940       if (RequireCompleteType(AtLoc, EncodedType,
941                               diag::err_incomplete_type_objc_at_encode,
942                               EncodedTypeInfo->getTypeLoc()))
943         return ExprError();
944 
945     std::string Str;
946     Context.getObjCEncodingForType(EncodedType, Str);
947 
948     // The type of @encode is the same as the type of the corresponding string,
949     // which is an array type.
950     StrTy = Context.CharTy;
951     // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
952     if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
953       StrTy.addConst();
954     StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
955                                          ArrayType::Normal, 0);
956   }
957 
958   return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
959 }
960 
961 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
962                                            SourceLocation EncodeLoc,
963                                            SourceLocation LParenLoc,
964                                            ParsedType ty,
965                                            SourceLocation RParenLoc) {
966   // FIXME: Preserve type source info ?
967   TypeSourceInfo *TInfo;
968   QualType EncodedType = GetTypeFromParser(ty, &TInfo);
969   if (!TInfo)
970     TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
971                                              PP.getLocForEndOfToken(LParenLoc));
972 
973   return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
974 }
975 
976 static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
977                                                SourceLocation AtLoc,
978                                                ObjCMethodDecl *Method,
979                                                ObjCMethodList &MethList) {
980   ObjCMethodList *M = &MethList;
981   bool Warned = false;
982   for (M = M->getNext(); M; M=M->getNext()) {
983     ObjCMethodDecl *MatchingMethodDecl = M->Method;
984     if (MatchingMethodDecl == Method ||
985         isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
986         MatchingMethodDecl->getSelector() != Method->getSelector())
987       continue;
988     if (!S.MatchTwoMethodDeclarations(Method,
989                                       MatchingMethodDecl, Sema::MMS_loose)) {
990       if (!Warned) {
991         Warned = true;
992         S.Diag(AtLoc, diag::warning_multiple_selectors)
993           << Method->getSelector();
994         S.Diag(Method->getLocation(), diag::note_method_declared_at)
995           << Method->getDeclName();
996       }
997       S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
998         << MatchingMethodDecl->getDeclName();
999     }
1000   }
1001   return Warned;
1002 }
1003 
1004 static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
1005                                         ObjCMethodDecl *Method) {
1006   if (S.Diags.getDiagnosticLevel(diag::warning_multiple_selectors,
1007                                  SourceLocation())
1008         == DiagnosticsEngine::Ignored)
1009     return;
1010   bool Warned = false;
1011   for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1012        e = S.MethodPool.end(); b != e; b++) {
1013     // first, instance methods
1014     ObjCMethodList &InstMethList = b->second.first;
1015     if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc,
1016                                                       Method, InstMethList))
1017       Warned = true;
1018 
1019     // second, class methods
1020     ObjCMethodList &ClsMethList = b->second.second;
1021     if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc,
1022                                                       Method, ClsMethList) ||
1023         Warned)
1024       return;
1025   }
1026 }
1027 
1028 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1029                                              SourceLocation AtLoc,
1030                                              SourceLocation SelLoc,
1031                                              SourceLocation LParenLoc,
1032                                              SourceLocation RParenLoc) {
1033   ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1034                              SourceRange(LParenLoc, RParenLoc), false, false);
1035   if (!Method)
1036     Method = LookupFactoryMethodInGlobalPool(Sel,
1037                                           SourceRange(LParenLoc, RParenLoc));
1038   if (!Method) {
1039     if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1040       Selector MatchedSel = OM->getSelector();
1041       SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1042                                 RParenLoc.getLocWithOffset(-1));
1043       Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1044         << Sel << MatchedSel
1045         << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1046 
1047     } else
1048         Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
1049   } else
1050     DiagnoseMismatchedSelectors(*this, AtLoc, Method);
1051 
1052   if (!Method ||
1053       Method->getImplementationControl() != ObjCMethodDecl::Optional) {
1054     llvm::DenseMap<Selector, SourceLocation>::iterator Pos
1055       = ReferencedSelectors.find(Sel);
1056     if (Pos == ReferencedSelectors.end())
1057       ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
1058   }
1059 
1060   // In ARC, forbid the user from using @selector for
1061   // retain/release/autorelease/dealloc/retainCount.
1062   if (getLangOpts().ObjCAutoRefCount) {
1063     switch (Sel.getMethodFamily()) {
1064     case OMF_retain:
1065     case OMF_release:
1066     case OMF_autorelease:
1067     case OMF_retainCount:
1068     case OMF_dealloc:
1069       Diag(AtLoc, diag::err_arc_illegal_selector) <<
1070         Sel << SourceRange(LParenLoc, RParenLoc);
1071       break;
1072 
1073     case OMF_None:
1074     case OMF_alloc:
1075     case OMF_copy:
1076     case OMF_finalize:
1077     case OMF_init:
1078     case OMF_mutableCopy:
1079     case OMF_new:
1080     case OMF_self:
1081     case OMF_performSelector:
1082       break;
1083     }
1084   }
1085   QualType Ty = Context.getObjCSelType();
1086   return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
1087 }
1088 
1089 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1090                                              SourceLocation AtLoc,
1091                                              SourceLocation ProtoLoc,
1092                                              SourceLocation LParenLoc,
1093                                              SourceLocation ProtoIdLoc,
1094                                              SourceLocation RParenLoc) {
1095   ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
1096   if (!PDecl) {
1097     Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
1098     return true;
1099   }
1100 
1101   QualType Ty = Context.getObjCProtoType();
1102   if (Ty.isNull())
1103     return true;
1104   Ty = Context.getObjCObjectPointerType(Ty);
1105   return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
1106 }
1107 
1108 /// Try to capture an implicit reference to 'self'.
1109 ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1110   DeclContext *DC = getFunctionLevelDeclContext();
1111 
1112   // If we're not in an ObjC method, error out.  Note that, unlike the
1113   // C++ case, we don't require an instance method --- class methods
1114   // still have a 'self', and we really do still need to capture it!
1115   ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1116   if (!method)
1117     return 0;
1118 
1119   tryCaptureVariable(method->getSelfDecl(), Loc);
1120 
1121   return method;
1122 }
1123 
1124 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1125   if (T == Context.getObjCInstanceType())
1126     return Context.getObjCIdType();
1127 
1128   return T;
1129 }
1130 
1131 QualType Sema::getMessageSendResultType(QualType ReceiverType,
1132                                         ObjCMethodDecl *Method,
1133                                     bool isClassMessage, bool isSuperMessage) {
1134   assert(Method && "Must have a method");
1135   if (!Method->hasRelatedResultType())
1136     return Method->getSendResultType();
1137 
1138   // If a method has a related return type:
1139   //   - if the method found is an instance method, but the message send
1140   //     was a class message send, T is the declared return type of the method
1141   //     found
1142   if (Method->isInstanceMethod() && isClassMessage)
1143     return stripObjCInstanceType(Context, Method->getSendResultType());
1144 
1145   //   - if the receiver is super, T is a pointer to the class of the
1146   //     enclosing method definition
1147   if (isSuperMessage) {
1148     if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1149       if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1150         return Context.getObjCObjectPointerType(
1151                                         Context.getObjCInterfaceType(Class));
1152   }
1153 
1154   //   - if the receiver is the name of a class U, T is a pointer to U
1155   if (ReceiverType->getAs<ObjCInterfaceType>() ||
1156       ReceiverType->isObjCQualifiedInterfaceType())
1157     return Context.getObjCObjectPointerType(ReceiverType);
1158   //   - if the receiver is of type Class or qualified Class type,
1159   //     T is the declared return type of the method.
1160   if (ReceiverType->isObjCClassType() ||
1161       ReceiverType->isObjCQualifiedClassType())
1162     return stripObjCInstanceType(Context, Method->getSendResultType());
1163 
1164   //   - if the receiver is id, qualified id, Class, or qualified Class, T
1165   //     is the receiver type, otherwise
1166   //   - T is the type of the receiver expression.
1167   return ReceiverType;
1168 }
1169 
1170 /// Look for an ObjC method whose result type exactly matches the given type.
1171 static const ObjCMethodDecl *
1172 findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1173                                  QualType instancetype) {
1174   if (MD->getReturnType() == instancetype)
1175     return MD;
1176 
1177   // For these purposes, a method in an @implementation overrides a
1178   // declaration in the @interface.
1179   if (const ObjCImplDecl *impl =
1180         dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1181     const ObjCContainerDecl *iface;
1182     if (const ObjCCategoryImplDecl *catImpl =
1183           dyn_cast<ObjCCategoryImplDecl>(impl)) {
1184       iface = catImpl->getCategoryDecl();
1185     } else {
1186       iface = impl->getClassInterface();
1187     }
1188 
1189     const ObjCMethodDecl *ifaceMD =
1190       iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1191     if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1192   }
1193 
1194   SmallVector<const ObjCMethodDecl *, 4> overrides;
1195   MD->getOverriddenMethods(overrides);
1196   for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1197     if (const ObjCMethodDecl *result =
1198           findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1199       return result;
1200   }
1201 
1202   return 0;
1203 }
1204 
1205 void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1206   // Only complain if we're in an ObjC method and the required return
1207   // type doesn't match the method's declared return type.
1208   ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1209   if (!MD || !MD->hasRelatedResultType() ||
1210       Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
1211     return;
1212 
1213   // Look for a method overridden by this method which explicitly uses
1214   // 'instancetype'.
1215   if (const ObjCMethodDecl *overridden =
1216         findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
1217     SourceLocation loc;
1218     SourceRange range;
1219     if (TypeSourceInfo *TSI = overridden->getReturnTypeSourceInfo()) {
1220       range = TSI->getTypeLoc().getSourceRange();
1221       loc = range.getBegin();
1222     }
1223     if (loc.isInvalid())
1224       loc = overridden->getLocation();
1225     Diag(loc, diag::note_related_result_type_explicit)
1226       << /*current method*/ 1 << range;
1227     return;
1228   }
1229 
1230   // Otherwise, if we have an interesting method family, note that.
1231   // This should always trigger if the above didn't.
1232   if (ObjCMethodFamily family = MD->getMethodFamily())
1233     Diag(MD->getLocation(), diag::note_related_result_type_family)
1234       << /*current method*/ 1
1235       << family;
1236 }
1237 
1238 void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1239   E = E->IgnoreParenImpCasts();
1240   const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1241   if (!MsgSend)
1242     return;
1243 
1244   const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1245   if (!Method)
1246     return;
1247 
1248   if (!Method->hasRelatedResultType())
1249     return;
1250 
1251   if (Context.hasSameUnqualifiedType(
1252           Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
1253     return;
1254 
1255   if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
1256                                       Context.getObjCInstanceType()))
1257     return;
1258 
1259   Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1260     << Method->isInstanceMethod() << Method->getSelector()
1261     << MsgSend->getType();
1262 }
1263 
1264 bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
1265                                      MultiExprArg Args,
1266                                      Selector Sel,
1267                                      ArrayRef<SourceLocation> SelectorLocs,
1268                                      ObjCMethodDecl *Method,
1269                                      bool isClassMessage, bool isSuperMessage,
1270                                      SourceLocation lbrac, SourceLocation rbrac,
1271                                      QualType &ReturnType, ExprValueKind &VK) {
1272   SourceLocation SelLoc;
1273   if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1274     SelLoc = SelectorLocs.front();
1275   else
1276     SelLoc = lbrac;
1277 
1278   if (!Method) {
1279     // Apply default argument promotion as for (C99 6.5.2.2p6).
1280     for (unsigned i = 0, e = Args.size(); i != e; i++) {
1281       if (Args[i]->isTypeDependent())
1282         continue;
1283 
1284       ExprResult result;
1285       if (getLangOpts().DebuggerSupport) {
1286         QualType paramTy; // ignored
1287         result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
1288       } else {
1289         result = DefaultArgumentPromotion(Args[i]);
1290       }
1291       if (result.isInvalid())
1292         return true;
1293       Args[i] = result.take();
1294     }
1295 
1296     unsigned DiagID;
1297     if (getLangOpts().ObjCAutoRefCount)
1298       DiagID = diag::err_arc_method_not_found;
1299     else
1300       DiagID = isClassMessage ? diag::warn_class_method_not_found
1301                               : diag::warn_inst_method_not_found;
1302     if (!getLangOpts().DebuggerSupport) {
1303       const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
1304       if (OMD && !OMD->isInvalidDecl()) {
1305         if (getLangOpts().ObjCAutoRefCount)
1306           DiagID = diag::error_method_not_found_with_typo;
1307         else
1308           DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1309                                   : diag::warn_instance_method_not_found_with_typo;
1310         Selector MatchedSel = OMD->getSelector();
1311         SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
1312         Diag(SelLoc, DiagID)
1313           << Sel<< isClassMessage << MatchedSel
1314           << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1315       }
1316       else
1317         Diag(SelLoc, DiagID)
1318           << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
1319                                                 SelectorLocs.back());
1320       // Find the class to which we are sending this message.
1321       if (ReceiverType->isObjCObjectPointerType()) {
1322         if (ObjCInterfaceDecl *Class =
1323               ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl())
1324           Diag(Class->getLocation(), diag::note_receiver_class_declared);
1325       }
1326     }
1327 
1328     // In debuggers, we want to use __unknown_anytype for these
1329     // results so that clients can cast them.
1330     if (getLangOpts().DebuggerSupport) {
1331       ReturnType = Context.UnknownAnyTy;
1332     } else {
1333       ReturnType = Context.getObjCIdType();
1334     }
1335     VK = VK_RValue;
1336     return false;
1337   }
1338 
1339   ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1340                                         isSuperMessage);
1341   VK = Expr::getValueKindForType(Method->getReturnType());
1342 
1343   unsigned NumNamedArgs = Sel.getNumArgs();
1344   // Method might have more arguments than selector indicates. This is due
1345   // to addition of c-style arguments in method.
1346   if (Method->param_size() > Sel.getNumArgs())
1347     NumNamedArgs = Method->param_size();
1348   // FIXME. This need be cleaned up.
1349   if (Args.size() < NumNamedArgs) {
1350     Diag(SelLoc, diag::err_typecheck_call_too_few_args)
1351       << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
1352     return false;
1353   }
1354 
1355   bool IsError = false;
1356   for (unsigned i = 0; i < NumNamedArgs; i++) {
1357     // We can't do any type-checking on a type-dependent argument.
1358     if (Args[i]->isTypeDependent())
1359       continue;
1360 
1361     Expr *argExpr = Args[i];
1362 
1363     ParmVarDecl *param = Method->param_begin()[i];
1364     assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
1365 
1366     // Strip the unbridged-cast placeholder expression off unless it's
1367     // a consumed argument.
1368     if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1369         !param->hasAttr<CFConsumedAttr>())
1370       argExpr = stripARCUnbridgedCast(argExpr);
1371 
1372     // If the parameter is __unknown_anytype, infer its type
1373     // from the argument.
1374     if (param->getType() == Context.UnknownAnyTy) {
1375       QualType paramType;
1376       ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
1377       if (argE.isInvalid()) {
1378         IsError = true;
1379       } else {
1380         Args[i] = argE.take();
1381 
1382         // Update the parameter type in-place.
1383         param->setType(paramType);
1384       }
1385       continue;
1386     }
1387 
1388     if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
1389                             param->getType(),
1390                             diag::err_call_incomplete_argument, argExpr))
1391       return true;
1392 
1393     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1394                                                                       param);
1395     ExprResult ArgE = PerformCopyInitialization(Entity, SelLoc, Owned(argExpr));
1396     if (ArgE.isInvalid())
1397       IsError = true;
1398     else
1399       Args[i] = ArgE.takeAs<Expr>();
1400   }
1401 
1402   // Promote additional arguments to variadic methods.
1403   if (Method->isVariadic()) {
1404     for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
1405       if (Args[i]->isTypeDependent())
1406         continue;
1407 
1408       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
1409                                                         0);
1410       IsError |= Arg.isInvalid();
1411       Args[i] = Arg.take();
1412     }
1413   } else {
1414     // Check for extra arguments to non-variadic methods.
1415     if (Args.size() != NumNamedArgs) {
1416       Diag(Args[NumNamedArgs]->getLocStart(),
1417            diag::err_typecheck_call_too_many_args)
1418         << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
1419         << Method->getSourceRange()
1420         << SourceRange(Args[NumNamedArgs]->getLocStart(),
1421                        Args.back()->getLocEnd());
1422     }
1423   }
1424 
1425   DiagnoseSentinelCalls(Method, SelLoc, Args);
1426 
1427   // Do additional checkings on method.
1428   IsError |= CheckObjCMethodCall(
1429       Method, SelLoc, makeArrayRef<const Expr *>(Args.data(), Args.size()));
1430 
1431   return IsError;
1432 }
1433 
1434 bool Sema::isSelfExpr(Expr *RExpr) {
1435   // 'self' is objc 'self' in an objc method only.
1436   ObjCMethodDecl *Method =
1437       dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1438   return isSelfExpr(RExpr, Method);
1439 }
1440 
1441 bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
1442   if (!method) return false;
1443 
1444   receiver = receiver->IgnoreParenLValueCasts();
1445   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
1446     if (DRE->getDecl() == method->getSelfDecl())
1447       return true;
1448   return false;
1449 }
1450 
1451 /// LookupMethodInType - Look up a method in an ObjCObjectType.
1452 ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1453                                                bool isInstance) {
1454   const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1455   if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1456     // Look it up in the main interface (and categories, etc.)
1457     if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1458       return method;
1459 
1460     // Okay, look for "private" methods declared in any
1461     // @implementations we've seen.
1462     if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1463       return method;
1464   }
1465 
1466   // Check qualifiers.
1467   for (const auto *I : objType->quals())
1468     if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
1469       return method;
1470 
1471   return 0;
1472 }
1473 
1474 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1475 /// list of a qualified objective pointer type.
1476 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1477                                               const ObjCObjectPointerType *OPT,
1478                                               bool Instance)
1479 {
1480   ObjCMethodDecl *MD = 0;
1481   for (const auto *PROTO : OPT->quals()) {
1482     if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1483       return MD;
1484     }
1485   }
1486   return 0;
1487 }
1488 
1489 static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1490   if (!Receiver)
1491     return;
1492 
1493   if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver))
1494     Receiver = OVE->getSourceExpr();
1495 
1496   Expr *RExpr = Receiver->IgnoreParenImpCasts();
1497   SourceLocation Loc = RExpr->getLocStart();
1498   QualType T = RExpr->getType();
1499   const ObjCPropertyDecl *PDecl = 0;
1500   const ObjCMethodDecl *GDecl = 0;
1501   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1502     RExpr = POE->getSyntacticForm();
1503     if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1504       if (PRE->isImplicitProperty()) {
1505         GDecl = PRE->getImplicitPropertyGetter();
1506         if (GDecl) {
1507           T = GDecl->getReturnType();
1508         }
1509       }
1510       else {
1511         PDecl = PRE->getExplicitProperty();
1512         if (PDecl) {
1513           T = PDecl->getType();
1514         }
1515       }
1516     }
1517   }
1518   else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) {
1519     // See if receiver is a method which envokes a synthesized getter
1520     // backing a 'weak' property.
1521     ObjCMethodDecl *Method = ME->getMethodDecl();
1522     if (Method && Method->getSelector().getNumArgs() == 0) {
1523       PDecl = Method->findPropertyDecl();
1524       if (PDecl)
1525         T = PDecl->getType();
1526     }
1527   }
1528 
1529   if (T.getObjCLifetime() != Qualifiers::OCL_Weak) {
1530     if (!PDecl)
1531       return;
1532     if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak))
1533       return;
1534   }
1535 
1536   S.Diag(Loc, diag::warn_receiver_is_weak)
1537     << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1538 
1539   if (PDecl)
1540     S.Diag(PDecl->getLocation(), diag::note_property_declare);
1541   else if (GDecl)
1542     S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
1543 
1544   S.Diag(Loc, diag::note_arc_assign_to_strong);
1545 }
1546 
1547 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1548 /// objective C interface.  This is a property reference expression.
1549 ExprResult Sema::
1550 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
1551                           Expr *BaseExpr, SourceLocation OpLoc,
1552                           DeclarationName MemberName,
1553                           SourceLocation MemberLoc,
1554                           SourceLocation SuperLoc, QualType SuperType,
1555                           bool Super) {
1556   const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1557   ObjCInterfaceDecl *IFace = IFaceT->getDecl();
1558 
1559   if (!MemberName.isIdentifier()) {
1560     Diag(MemberLoc, diag::err_invalid_property_name)
1561       << MemberName << QualType(OPT, 0);
1562     return ExprError();
1563   }
1564 
1565   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1566 
1567   SourceRange BaseRange = Super? SourceRange(SuperLoc)
1568                                : BaseExpr->getSourceRange();
1569   if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
1570                           diag::err_property_not_found_forward_class,
1571                           MemberName, BaseRange))
1572     return ExprError();
1573 
1574   // Search for a declared property first.
1575   if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
1576     // Check whether we can reference this property.
1577     if (DiagnoseUseOfDecl(PD, MemberLoc))
1578       return ExprError();
1579     if (Super)
1580       return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
1581                                                      VK_LValue, OK_ObjCProperty,
1582                                                      MemberLoc,
1583                                                      SuperLoc, SuperType));
1584     else
1585       return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
1586                                                      VK_LValue, OK_ObjCProperty,
1587                                                      MemberLoc, BaseExpr));
1588   }
1589   // Check protocols on qualified interfaces.
1590   for (const auto *I : OPT->quals())
1591     if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
1592       // Check whether we can reference this property.
1593       if (DiagnoseUseOfDecl(PD, MemberLoc))
1594         return ExprError();
1595 
1596       if (Super)
1597         return Owned(new (Context) ObjCPropertyRefExpr(PD,
1598                                                        Context.PseudoObjectTy,
1599                                                        VK_LValue,
1600                                                        OK_ObjCProperty,
1601                                                        MemberLoc,
1602                                                        SuperLoc, SuperType));
1603       else
1604         return Owned(new (Context) ObjCPropertyRefExpr(PD,
1605                                                        Context.PseudoObjectTy,
1606                                                        VK_LValue,
1607                                                        OK_ObjCProperty,
1608                                                        MemberLoc,
1609                                                        BaseExpr));
1610     }
1611   // If that failed, look for an "implicit" property by seeing if the nullary
1612   // selector is implemented.
1613 
1614   // FIXME: The logic for looking up nullary and unary selectors should be
1615   // shared with the code in ActOnInstanceMessage.
1616 
1617   Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1618   ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1619 
1620   // May be founf in property's qualified list.
1621   if (!Getter)
1622     Getter = LookupMethodInQualifiedType(Sel, OPT, true);
1623 
1624   // If this reference is in an @implementation, check for 'private' methods.
1625   if (!Getter)
1626     Getter = IFace->lookupPrivateMethod(Sel);
1627 
1628   if (Getter) {
1629     // Check if we can reference this property.
1630     if (DiagnoseUseOfDecl(Getter, MemberLoc))
1631       return ExprError();
1632   }
1633   // If we found a getter then this may be a valid dot-reference, we
1634   // will look for the matching setter, in case it is needed.
1635   Selector SetterSel =
1636     SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1637                                            PP.getSelectorTable(), Member);
1638   ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1639 
1640   // May be founf in property's qualified list.
1641   if (!Setter)
1642     Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1643 
1644   if (!Setter) {
1645     // If this reference is in an @implementation, also check for 'private'
1646     // methods.
1647     Setter = IFace->lookupPrivateMethod(SetterSel);
1648   }
1649 
1650   if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1651     return ExprError();
1652 
1653   if (Getter || Setter) {
1654     if (Super)
1655       return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1656                                                      Context.PseudoObjectTy,
1657                                                      VK_LValue, OK_ObjCProperty,
1658                                                      MemberLoc,
1659                                                      SuperLoc, SuperType));
1660     else
1661       return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1662                                                      Context.PseudoObjectTy,
1663                                                      VK_LValue, OK_ObjCProperty,
1664                                                      MemberLoc, BaseExpr));
1665 
1666   }
1667 
1668   // Attempt to correct for typos in property names.
1669   DeclFilterCCC<ObjCPropertyDecl> Validator;
1670   if (TypoCorrection Corrected = CorrectTypo(
1671           DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
1672           NULL, Validator, IFace, false, OPT)) {
1673     diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1674                               << MemberName << QualType(OPT, 0));
1675     DeclarationName TypoResult = Corrected.getCorrection();
1676     return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1677                                      TypoResult, MemberLoc,
1678                                      SuperLoc, SuperType, Super);
1679   }
1680   ObjCInterfaceDecl *ClassDeclared;
1681   if (ObjCIvarDecl *Ivar =
1682       IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1683     QualType T = Ivar->getType();
1684     if (const ObjCObjectPointerType * OBJPT =
1685         T->getAsObjCInterfacePointerType()) {
1686       if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
1687                               diag::err_property_not_as_forward_class,
1688                               MemberName, BaseExpr))
1689         return ExprError();
1690     }
1691     Diag(MemberLoc,
1692          diag::err_ivar_access_using_property_syntax_suggest)
1693     << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1694     << FixItHint::CreateReplacement(OpLoc, "->");
1695     return ExprError();
1696   }
1697 
1698   Diag(MemberLoc, diag::err_property_not_found)
1699     << MemberName << QualType(OPT, 0);
1700   if (Setter)
1701     Diag(Setter->getLocation(), diag::note_getter_unavailable)
1702           << MemberName << BaseExpr->getSourceRange();
1703   return ExprError();
1704 }
1705 
1706 
1707 
1708 ExprResult Sema::
1709 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1710                           IdentifierInfo &propertyName,
1711                           SourceLocation receiverNameLoc,
1712                           SourceLocation propertyNameLoc) {
1713 
1714   IdentifierInfo *receiverNamePtr = &receiverName;
1715   ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1716                                                   receiverNameLoc);
1717 
1718   bool IsSuper = false;
1719   if (IFace == 0) {
1720     // If the "receiver" is 'super' in a method, handle it as an expression-like
1721     // property reference.
1722     if (receiverNamePtr->isStr("super")) {
1723       IsSuper = true;
1724 
1725       if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
1726         if (CurMethod->isInstanceMethod()) {
1727           ObjCInterfaceDecl *Super =
1728             CurMethod->getClassInterface()->getSuperClass();
1729           if (!Super) {
1730             // The current class does not have a superclass.
1731             Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1732             << CurMethod->getClassInterface()->getIdentifier();
1733             return ExprError();
1734           }
1735           QualType T = Context.getObjCInterfaceType(Super);
1736           T = Context.getObjCObjectPointerType(T);
1737 
1738           return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
1739                                            /*BaseExpr*/0,
1740                                            SourceLocation()/*OpLoc*/,
1741                                            &propertyName,
1742                                            propertyNameLoc,
1743                                            receiverNameLoc, T, true);
1744         }
1745 
1746         // Otherwise, if this is a class method, try dispatching to our
1747         // superclass.
1748         IFace = CurMethod->getClassInterface()->getSuperClass();
1749       }
1750     }
1751 
1752     if (IFace == 0) {
1753       Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1754                                                        << tok::l_paren;
1755       return ExprError();
1756     }
1757   }
1758 
1759   // Search for a declared property first.
1760   Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
1761   ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
1762 
1763   // If this reference is in an @implementation, check for 'private' methods.
1764   if (!Getter)
1765     if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1766       if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1767         if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
1768           Getter = ImpDecl->getClassMethod(Sel);
1769 
1770   if (Getter) {
1771     // FIXME: refactor/share with ActOnMemberReference().
1772     // Check if we can reference this property.
1773     if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1774       return ExprError();
1775   }
1776 
1777   // Look for the matching setter, in case it is needed.
1778   Selector SetterSel =
1779     SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1780                                            PP.getSelectorTable(),
1781                                            &propertyName);
1782 
1783   ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1784   if (!Setter) {
1785     // If this reference is in an @implementation, also check for 'private'
1786     // methods.
1787     if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1788       if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1789         if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
1790           Setter = ImpDecl->getClassMethod(SetterSel);
1791   }
1792   // Look through local category implementations associated with the class.
1793   if (!Setter)
1794     Setter = IFace->getCategoryClassMethod(SetterSel);
1795 
1796   if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1797     return ExprError();
1798 
1799   if (Getter || Setter) {
1800     if (IsSuper)
1801     return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1802                                                    Context.PseudoObjectTy,
1803                                                    VK_LValue, OK_ObjCProperty,
1804                                                    propertyNameLoc,
1805                                                    receiverNameLoc,
1806                                           Context.getObjCInterfaceType(IFace)));
1807 
1808     return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1809                                                    Context.PseudoObjectTy,
1810                                                    VK_LValue, OK_ObjCProperty,
1811                                                    propertyNameLoc,
1812                                                    receiverNameLoc, IFace));
1813   }
1814   return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1815                      << &propertyName << Context.getObjCInterfaceType(IFace));
1816 }
1817 
1818 namespace {
1819 
1820 class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1821  public:
1822   ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1823     // Determine whether "super" is acceptable in the current context.
1824     if (Method && Method->getClassInterface())
1825       WantObjCSuper = Method->getClassInterface()->getSuperClass();
1826   }
1827 
1828   bool ValidateCandidate(const TypoCorrection &candidate) override {
1829     return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1830         candidate.isKeyword("super");
1831   }
1832 };
1833 
1834 }
1835 
1836 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
1837                                                IdentifierInfo *Name,
1838                                                SourceLocation NameLoc,
1839                                                bool IsSuper,
1840                                                bool HasTrailingDot,
1841                                                ParsedType &ReceiverType) {
1842   ReceiverType = ParsedType();
1843 
1844   // If the identifier is "super" and there is no trailing dot, we're
1845   // messaging super. If the identifier is "super" and there is a
1846   // trailing dot, it's an instance message.
1847   if (IsSuper && S->isInObjcMethodScope())
1848     return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
1849 
1850   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1851   LookupName(Result, S);
1852 
1853   switch (Result.getResultKind()) {
1854   case LookupResult::NotFound:
1855     // Normal name lookup didn't find anything. If we're in an
1856     // Objective-C method, look for ivars. If we find one, we're done!
1857     // FIXME: This is a hack. Ivar lookup should be part of normal
1858     // lookup.
1859     if (ObjCMethodDecl *Method = getCurMethodDecl()) {
1860       if (!Method->getClassInterface()) {
1861         // Fall back: let the parser try to parse it as an instance message.
1862         return ObjCInstanceMessage;
1863       }
1864 
1865       ObjCInterfaceDecl *ClassDeclared;
1866       if (Method->getClassInterface()->lookupInstanceVariable(Name,
1867                                                               ClassDeclared))
1868         return ObjCInstanceMessage;
1869     }
1870 
1871     // Break out; we'll perform typo correction below.
1872     break;
1873 
1874   case LookupResult::NotFoundInCurrentInstantiation:
1875   case LookupResult::FoundOverloaded:
1876   case LookupResult::FoundUnresolvedValue:
1877   case LookupResult::Ambiguous:
1878     Result.suppressDiagnostics();
1879     return ObjCInstanceMessage;
1880 
1881   case LookupResult::Found: {
1882     // If the identifier is a class or not, and there is a trailing dot,
1883     // it's an instance message.
1884     if (HasTrailingDot)
1885       return ObjCInstanceMessage;
1886     // We found something. If it's a type, then we have a class
1887     // message. Otherwise, it's an instance message.
1888     NamedDecl *ND = Result.getFoundDecl();
1889     QualType T;
1890     if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1891       T = Context.getObjCInterfaceType(Class);
1892     else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
1893       T = Context.getTypeDeclType(Type);
1894       DiagnoseUseOfDecl(Type, NameLoc);
1895     }
1896     else
1897       return ObjCInstanceMessage;
1898 
1899     //  We have a class message, and T is the type we're
1900     //  messaging. Build source-location information for it.
1901     TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1902     ReceiverType = CreateParsedType(T, TSInfo);
1903     return ObjCClassMessage;
1904   }
1905   }
1906 
1907   ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
1908   if (TypoCorrection Corrected =
1909           CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
1910                       NULL, Validator, NULL, false, NULL, false)) {
1911     if (Corrected.isKeyword()) {
1912       // If we've found the keyword "super" (the only keyword that would be
1913       // returned by CorrectTypo), this is a send to super.
1914       diagnoseTypo(Corrected,
1915                    PDiag(diag::err_unknown_receiver_suggest) << Name);
1916       return ObjCSuperMessage;
1917     } else if (ObjCInterfaceDecl *Class =
1918                    Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1919       // If we found a declaration, correct when it refers to an Objective-C
1920       // class.
1921       diagnoseTypo(Corrected,
1922                    PDiag(diag::err_unknown_receiver_suggest) << Name);
1923       QualType T = Context.getObjCInterfaceType(Class);
1924       TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1925       ReceiverType = CreateParsedType(T, TSInfo);
1926       return ObjCClassMessage;
1927     }
1928   }
1929 
1930   // Fall back: let the parser try to parse it as an instance message.
1931   return ObjCInstanceMessage;
1932 }
1933 
1934 ExprResult Sema::ActOnSuperMessage(Scope *S,
1935                                    SourceLocation SuperLoc,
1936                                    Selector Sel,
1937                                    SourceLocation LBracLoc,
1938                                    ArrayRef<SourceLocation> SelectorLocs,
1939                                    SourceLocation RBracLoc,
1940                                    MultiExprArg Args) {
1941   // Determine whether we are inside a method or not.
1942   ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
1943   if (!Method) {
1944     Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1945     return ExprError();
1946   }
1947 
1948   ObjCInterfaceDecl *Class = Method->getClassInterface();
1949   if (!Class) {
1950     Diag(SuperLoc, diag::error_no_super_class_message)
1951       << Method->getDeclName();
1952     return ExprError();
1953   }
1954 
1955   ObjCInterfaceDecl *Super = Class->getSuperClass();
1956   if (!Super) {
1957     // The current class does not have a superclass.
1958     Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1959       << Class->getIdentifier();
1960     return ExprError();
1961   }
1962 
1963   // We are in a method whose class has a superclass, so 'super'
1964   // is acting as a keyword.
1965   if (Method->getSelector() == Sel)
1966     getCurFunction()->ObjCShouldCallSuper = false;
1967 
1968   if (Method->isInstanceMethod()) {
1969     // Since we are in an instance method, this is an instance
1970     // message to the superclass instance.
1971     QualType SuperTy = Context.getObjCInterfaceType(Super);
1972     SuperTy = Context.getObjCObjectPointerType(SuperTy);
1973     return BuildInstanceMessage(0, SuperTy, SuperLoc,
1974                                 Sel, /*Method=*/0,
1975                                 LBracLoc, SelectorLocs, RBracLoc, Args);
1976   }
1977 
1978   // Since we are in a class method, this is a class message to
1979   // the superclass.
1980   return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1981                            Context.getObjCInterfaceType(Super),
1982                            SuperLoc, Sel, /*Method=*/0,
1983                            LBracLoc, SelectorLocs, RBracLoc, Args);
1984 }
1985 
1986 
1987 ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1988                                            bool isSuperReceiver,
1989                                            SourceLocation Loc,
1990                                            Selector Sel,
1991                                            ObjCMethodDecl *Method,
1992                                            MultiExprArg Args) {
1993   TypeSourceInfo *receiverTypeInfo = 0;
1994   if (!ReceiverType.isNull())
1995     receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1996 
1997   return BuildClassMessage(receiverTypeInfo, ReceiverType,
1998                           /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1999                            Sel, Method, Loc, Loc, Loc, Args,
2000                            /*isImplicit=*/true);
2001 
2002 }
2003 
2004 static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2005                                unsigned DiagID,
2006                                bool (*refactor)(const ObjCMessageExpr *,
2007                                               const NSAPI &, edit::Commit &)) {
2008   SourceLocation MsgLoc = Msg->getExprLoc();
2009   if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
2010     return;
2011 
2012   SourceManager &SM = S.SourceMgr;
2013   edit::Commit ECommit(SM, S.LangOpts);
2014   if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2015     DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2016                         << Msg->getSelector() << Msg->getSourceRange();
2017     // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2018     if (!ECommit.isCommitable())
2019       return;
2020     for (edit::Commit::edit_iterator
2021            I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2022       const edit::Commit::Edit &Edit = *I;
2023       switch (Edit.Kind) {
2024       case edit::Commit::Act_Insert:
2025         Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2026                                                         Edit.Text,
2027                                                         Edit.BeforePrev));
2028         break;
2029       case edit::Commit::Act_InsertFromRange:
2030         Builder.AddFixItHint(
2031             FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2032                                                 Edit.getInsertFromRange(SM),
2033                                                 Edit.BeforePrev));
2034         break;
2035       case edit::Commit::Act_Remove:
2036         Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2037         break;
2038       }
2039     }
2040   }
2041 }
2042 
2043 static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2044   applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2045                      edit::rewriteObjCRedundantCallWithLiteral);
2046 }
2047 
2048 /// \brief Build an Objective-C class message expression.
2049 ///
2050 /// This routine takes care of both normal class messages and
2051 /// class messages to the superclass.
2052 ///
2053 /// \param ReceiverTypeInfo Type source information that describes the
2054 /// receiver of this message. This may be NULL, in which case we are
2055 /// sending to the superclass and \p SuperLoc must be a valid source
2056 /// location.
2057 
2058 /// \param ReceiverType The type of the object receiving the
2059 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2060 /// type as that refers to. For a superclass send, this is the type of
2061 /// the superclass.
2062 ///
2063 /// \param SuperLoc The location of the "super" keyword in a
2064 /// superclass message.
2065 ///
2066 /// \param Sel The selector to which the message is being sent.
2067 ///
2068 /// \param Method The method that this class message is invoking, if
2069 /// already known.
2070 ///
2071 /// \param LBracLoc The location of the opening square bracket ']'.
2072 ///
2073 /// \param RBracLoc The location of the closing square bracket ']'.
2074 ///
2075 /// \param ArgsIn The message arguments.
2076 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
2077                                    QualType ReceiverType,
2078                                    SourceLocation SuperLoc,
2079                                    Selector Sel,
2080                                    ObjCMethodDecl *Method,
2081                                    SourceLocation LBracLoc,
2082                                    ArrayRef<SourceLocation> SelectorLocs,
2083                                    SourceLocation RBracLoc,
2084                                    MultiExprArg ArgsIn,
2085                                    bool isImplicit) {
2086   SourceLocation Loc = SuperLoc.isValid()? SuperLoc
2087     : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
2088   if (LBracLoc.isInvalid()) {
2089     Diag(Loc, diag::err_missing_open_square_message_send)
2090       << FixItHint::CreateInsertion(Loc, "[");
2091     LBracLoc = Loc;
2092   }
2093   SourceLocation SelLoc;
2094   if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2095     SelLoc = SelectorLocs.front();
2096   else
2097     SelLoc = Loc;
2098 
2099   if (ReceiverType->isDependentType()) {
2100     // If the receiver type is dependent, we can't type-check anything
2101     // at this point. Build a dependent expression.
2102     unsigned NumArgs = ArgsIn.size();
2103     Expr **Args = ArgsIn.data();
2104     assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2105     return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
2106                                          VK_RValue, LBracLoc, ReceiverTypeInfo,
2107                                          Sel, SelectorLocs, /*Method=*/0,
2108                                          makeArrayRef(Args, NumArgs),RBracLoc,
2109                                          isImplicit));
2110   }
2111 
2112   // Find the class to which we are sending this message.
2113   ObjCInterfaceDecl *Class = 0;
2114   const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2115   if (!ClassType || !(Class = ClassType->getInterface())) {
2116     Diag(Loc, diag::err_invalid_receiver_class_message)
2117       << ReceiverType;
2118     return ExprError();
2119   }
2120   assert(Class && "We don't know which class we're messaging?");
2121   // objc++ diagnoses during typename annotation.
2122   if (!getLangOpts().CPlusPlus)
2123     (void)DiagnoseUseOfDecl(Class, SelLoc);
2124   // Find the method we are messaging.
2125   if (!Method) {
2126     SourceRange TypeRange
2127       = SuperLoc.isValid()? SourceRange(SuperLoc)
2128                           : ReceiverTypeInfo->getTypeLoc().getSourceRange();
2129     if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
2130                             (getLangOpts().ObjCAutoRefCount
2131                                ? diag::err_arc_receiver_forward_class
2132                                : diag::warn_receiver_forward_class),
2133                             TypeRange)) {
2134       // A forward class used in messaging is treated as a 'Class'
2135       Method = LookupFactoryMethodInGlobalPool(Sel,
2136                                                SourceRange(LBracLoc, RBracLoc));
2137       if (Method && !getLangOpts().ObjCAutoRefCount)
2138         Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2139           << Method->getDeclName();
2140     }
2141     if (!Method)
2142       Method = Class->lookupClassMethod(Sel);
2143 
2144     // If we have an implementation in scope, check "private" methods.
2145     if (!Method)
2146       Method = Class->lookupPrivateClassMethod(Sel);
2147 
2148     if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2149       return ExprError();
2150   }
2151 
2152   // Check the argument types and determine the result type.
2153   QualType ReturnType;
2154   ExprValueKind VK = VK_RValue;
2155 
2156   unsigned NumArgs = ArgsIn.size();
2157   Expr **Args = ArgsIn.data();
2158   if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2159                                 Sel, SelectorLocs,
2160                                 Method, true,
2161                                 SuperLoc.isValid(), LBracLoc, RBracLoc,
2162                                 ReturnType, VK))
2163     return ExprError();
2164 
2165   if (Method && !Method->getReturnType()->isVoidType() &&
2166       RequireCompleteType(LBracLoc, Method->getReturnType(),
2167                           diag::err_illegal_message_expr_incomplete_type))
2168     return ExprError();
2169 
2170   // Construct the appropriate ObjCMessageExpr.
2171   ObjCMessageExpr *Result;
2172   if (SuperLoc.isValid())
2173     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2174                                      SuperLoc, /*IsInstanceSuper=*/false,
2175                                      ReceiverType, Sel, SelectorLocs,
2176                                      Method, makeArrayRef(Args, NumArgs),
2177                                      RBracLoc, isImplicit);
2178   else {
2179     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2180                                      ReceiverTypeInfo, Sel, SelectorLocs,
2181                                      Method, makeArrayRef(Args, NumArgs),
2182                                      RBracLoc, isImplicit);
2183     if (!isImplicit)
2184       checkCocoaAPI(*this, Result);
2185   }
2186   return MaybeBindToTemporary(Result);
2187 }
2188 
2189 // ActOnClassMessage - used for both unary and keyword messages.
2190 // ArgExprs is optional - if it is present, the number of expressions
2191 // is obtained from Sel.getNumArgs().
2192 ExprResult Sema::ActOnClassMessage(Scope *S,
2193                                    ParsedType Receiver,
2194                                    Selector Sel,
2195                                    SourceLocation LBracLoc,
2196                                    ArrayRef<SourceLocation> SelectorLocs,
2197                                    SourceLocation RBracLoc,
2198                                    MultiExprArg Args) {
2199   TypeSourceInfo *ReceiverTypeInfo;
2200   QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2201   if (ReceiverType.isNull())
2202     return ExprError();
2203 
2204 
2205   if (!ReceiverTypeInfo)
2206     ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2207 
2208   return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
2209                            /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
2210                            LBracLoc, SelectorLocs, RBracLoc, Args);
2211 }
2212 
2213 ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2214                                               QualType ReceiverType,
2215                                               SourceLocation Loc,
2216                                               Selector Sel,
2217                                               ObjCMethodDecl *Method,
2218                                               MultiExprArg Args) {
2219   return BuildInstanceMessage(Receiver, ReceiverType,
2220                               /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2221                               Sel, Method, Loc, Loc, Loc, Args,
2222                               /*isImplicit=*/true);
2223 }
2224 
2225 /// \brief Build an Objective-C instance message expression.
2226 ///
2227 /// This routine takes care of both normal instance messages and
2228 /// instance messages to the superclass instance.
2229 ///
2230 /// \param Receiver The expression that computes the object that will
2231 /// receive this message. This may be empty, in which case we are
2232 /// sending to the superclass instance and \p SuperLoc must be a valid
2233 /// source location.
2234 ///
2235 /// \param ReceiverType The (static) type of the object receiving the
2236 /// message. When a \p Receiver expression is provided, this is the
2237 /// same type as that expression. For a superclass instance send, this
2238 /// is a pointer to the type of the superclass.
2239 ///
2240 /// \param SuperLoc The location of the "super" keyword in a
2241 /// superclass instance message.
2242 ///
2243 /// \param Sel The selector to which the message is being sent.
2244 ///
2245 /// \param Method The method that this instance message is invoking, if
2246 /// already known.
2247 ///
2248 /// \param LBracLoc The location of the opening square bracket ']'.
2249 ///
2250 /// \param RBracLoc The location of the closing square bracket ']'.
2251 ///
2252 /// \param ArgsIn The message arguments.
2253 ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
2254                                       QualType ReceiverType,
2255                                       SourceLocation SuperLoc,
2256                                       Selector Sel,
2257                                       ObjCMethodDecl *Method,
2258                                       SourceLocation LBracLoc,
2259                                       ArrayRef<SourceLocation> SelectorLocs,
2260                                       SourceLocation RBracLoc,
2261                                       MultiExprArg ArgsIn,
2262                                       bool isImplicit) {
2263   // The location of the receiver.
2264   SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
2265   SourceRange RecRange =
2266       SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2267   SourceLocation SelLoc;
2268   if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2269     SelLoc = SelectorLocs.front();
2270   else
2271     SelLoc = Loc;
2272 
2273   if (LBracLoc.isInvalid()) {
2274     Diag(Loc, diag::err_missing_open_square_message_send)
2275       << FixItHint::CreateInsertion(Loc, "[");
2276     LBracLoc = Loc;
2277   }
2278 
2279   // If we have a receiver expression, perform appropriate promotions
2280   // and determine receiver type.
2281   if (Receiver) {
2282     if (Receiver->hasPlaceholderType()) {
2283       ExprResult Result;
2284       if (Receiver->getType() == Context.UnknownAnyTy)
2285         Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2286       else
2287         Result = CheckPlaceholderExpr(Receiver);
2288       if (Result.isInvalid()) return ExprError();
2289       Receiver = Result.take();
2290     }
2291 
2292     if (Receiver->isTypeDependent()) {
2293       // If the receiver is type-dependent, we can't type-check anything
2294       // at this point. Build a dependent expression.
2295       unsigned NumArgs = ArgsIn.size();
2296       Expr **Args = ArgsIn.data();
2297       assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2298       return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
2299                                            VK_RValue, LBracLoc, Receiver, Sel,
2300                                            SelectorLocs, /*Method=*/0,
2301                                            makeArrayRef(Args, NumArgs),
2302                                            RBracLoc, isImplicit));
2303     }
2304 
2305     // If necessary, apply function/array conversion to the receiver.
2306     // C99 6.7.5.3p[7,8].
2307     ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2308     if (Result.isInvalid())
2309       return ExprError();
2310     Receiver = Result.take();
2311     ReceiverType = Receiver->getType();
2312 
2313     // If the receiver is an ObjC pointer, a block pointer, or an
2314     // __attribute__((NSObject)) pointer, we don't need to do any
2315     // special conversion in order to look up a receiver.
2316     if (ReceiverType->isObjCRetainableType()) {
2317       // do nothing
2318     } else if (!getLangOpts().ObjCAutoRefCount &&
2319                !Context.getObjCIdType().isNull() &&
2320                (ReceiverType->isPointerType() ||
2321                 ReceiverType->isIntegerType())) {
2322       // Implicitly convert integers and pointers to 'id' but emit a warning.
2323       // But not in ARC.
2324       Diag(Loc, diag::warn_bad_receiver_type)
2325         << ReceiverType
2326         << Receiver->getSourceRange();
2327       if (ReceiverType->isPointerType()) {
2328         Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2329                                      CK_CPointerToObjCPointerCast).take();
2330       } else {
2331         // TODO: specialized warning on null receivers?
2332         bool IsNull = Receiver->isNullPointerConstant(Context,
2333                                               Expr::NPC_ValueDependentIsNull);
2334         CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2335         Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2336                                      Kind).take();
2337       }
2338       ReceiverType = Receiver->getType();
2339     } else if (getLangOpts().CPlusPlus) {
2340       // The receiver must be a complete type.
2341       if (RequireCompleteType(Loc, Receiver->getType(),
2342                               diag::err_incomplete_receiver_type))
2343         return ExprError();
2344 
2345       ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2346       if (result.isUsable()) {
2347         Receiver = result.take();
2348         ReceiverType = Receiver->getType();
2349       }
2350     }
2351   }
2352 
2353   // There's a somewhat weird interaction here where we assume that we
2354   // won't actually have a method unless we also don't need to do some
2355   // of the more detailed type-checking on the receiver.
2356 
2357   if (!Method) {
2358     // Handle messages to id.
2359     bool receiverIsId = ReceiverType->isObjCIdType();
2360     if (receiverIsId || ReceiverType->isBlockPointerType() ||
2361         (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2362       Method = LookupInstanceMethodInGlobalPool(Sel,
2363                                                 SourceRange(LBracLoc, RBracLoc),
2364                                                 receiverIsId);
2365       if (!Method)
2366         Method = LookupFactoryMethodInGlobalPool(Sel,
2367                                                  SourceRange(LBracLoc,RBracLoc),
2368                                                  receiverIsId);
2369     } else if (ReceiverType->isObjCClassType() ||
2370                ReceiverType->isObjCQualifiedClassType()) {
2371       // Handle messages to Class.
2372       // We allow sending a message to a qualified Class ("Class<foo>"), which
2373       // is ok as long as one of the protocols implements the selector (if not, warn).
2374       if (const ObjCObjectPointerType *QClassTy
2375             = ReceiverType->getAsObjCQualifiedClassType()) {
2376         // Search protocols for class methods.
2377         Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2378         if (!Method) {
2379           Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2380           // warn if instance method found for a Class message.
2381           if (Method) {
2382             Diag(SelLoc, diag::warn_instance_method_on_class_found)
2383               << Method->getSelector() << Sel;
2384             Diag(Method->getLocation(), diag::note_method_declared_at)
2385               << Method->getDeclName();
2386           }
2387         }
2388       } else {
2389         if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2390           if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2391             // First check the public methods in the class interface.
2392             Method = ClassDecl->lookupClassMethod(Sel);
2393 
2394             if (!Method)
2395               Method = ClassDecl->lookupPrivateClassMethod(Sel);
2396           }
2397           if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2398             return ExprError();
2399         }
2400         if (!Method) {
2401           // If not messaging 'self', look for any factory method named 'Sel'.
2402           if (!Receiver || !isSelfExpr(Receiver)) {
2403             Method = LookupFactoryMethodInGlobalPool(Sel,
2404                                                 SourceRange(LBracLoc, RBracLoc),
2405                                                      true);
2406             if (!Method) {
2407               // If no class (factory) method was found, check if an _instance_
2408               // method of the same name exists in the root class only.
2409               Method = LookupInstanceMethodInGlobalPool(Sel,
2410                                                SourceRange(LBracLoc, RBracLoc),
2411                                                         true);
2412               if (Method)
2413                   if (const ObjCInterfaceDecl *ID =
2414                       dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2415                     if (ID->getSuperClass())
2416                       Diag(SelLoc, diag::warn_root_inst_method_not_found)
2417                       << Sel << SourceRange(LBracLoc, RBracLoc);
2418                   }
2419             }
2420           }
2421         }
2422       }
2423     } else {
2424       ObjCInterfaceDecl* ClassDecl = 0;
2425 
2426       // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2427       // long as one of the protocols implements the selector (if not, warn).
2428       // And as long as message is not deprecated/unavailable (warn if it is).
2429       if (const ObjCObjectPointerType *QIdTy
2430                                    = ReceiverType->getAsObjCQualifiedIdType()) {
2431         // Search protocols for instance methods.
2432         Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2433         if (!Method)
2434           Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
2435         if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2436           return ExprError();
2437       } else if (const ObjCObjectPointerType *OCIType
2438                    = ReceiverType->getAsObjCInterfacePointerType()) {
2439         // We allow sending a message to a pointer to an interface (an object).
2440         ClassDecl = OCIType->getInterfaceDecl();
2441 
2442         // Try to complete the type. Under ARC, this is a hard error from which
2443         // we don't try to recover.
2444         const ObjCInterfaceDecl *forwardClass = 0;
2445         if (RequireCompleteType(Loc, OCIType->getPointeeType(),
2446               getLangOpts().ObjCAutoRefCount
2447                 ? diag::err_arc_receiver_forward_instance
2448                 : diag::warn_receiver_forward_instance,
2449                                 Receiver? Receiver->getSourceRange()
2450                                         : SourceRange(SuperLoc))) {
2451           if (getLangOpts().ObjCAutoRefCount)
2452             return ExprError();
2453 
2454           forwardClass = OCIType->getInterfaceDecl();
2455           Diag(Receiver ? Receiver->getLocStart()
2456                         : SuperLoc, diag::note_receiver_is_id);
2457           Method = 0;
2458         } else {
2459           Method = ClassDecl->lookupInstanceMethod(Sel);
2460         }
2461 
2462         if (!Method)
2463           // Search protocol qualifiers.
2464           Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2465 
2466         if (!Method) {
2467           // If we have implementations in scope, check "private" methods.
2468           Method = ClassDecl->lookupPrivateMethod(Sel);
2469 
2470           if (!Method && getLangOpts().ObjCAutoRefCount) {
2471             Diag(SelLoc, diag::err_arc_may_not_respond)
2472               << OCIType->getPointeeType() << Sel << RecRange
2473               << SourceRange(SelectorLocs.front(), SelectorLocs.back());
2474             return ExprError();
2475           }
2476 
2477           if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
2478             // If we still haven't found a method, look in the global pool. This
2479             // behavior isn't very desirable, however we need it for GCC
2480             // compatibility. FIXME: should we deviate??
2481             if (OCIType->qual_empty()) {
2482               Method = LookupInstanceMethodInGlobalPool(Sel,
2483                                               SourceRange(LBracLoc, RBracLoc));
2484               if (Method && !forwardClass)
2485                 Diag(SelLoc, diag::warn_maynot_respond)
2486                   << OCIType->getInterfaceDecl()->getIdentifier()
2487                   << Sel << RecRange;
2488             }
2489           }
2490         }
2491         if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
2492           return ExprError();
2493       } else {
2494         // Reject other random receiver types (e.g. structs).
2495         Diag(Loc, diag::err_bad_receiver_type)
2496           << ReceiverType << Receiver->getSourceRange();
2497         return ExprError();
2498       }
2499     }
2500   }
2501 
2502   FunctionScopeInfo *DIFunctionScopeInfo =
2503     (Method && Method->getMethodFamily() == OMF_init)
2504       ? getEnclosingFunction() : 0;
2505 
2506   if (DIFunctionScopeInfo &&
2507       DIFunctionScopeInfo->ObjCIsDesignatedInit &&
2508       (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2509     bool isDesignatedInitChain = false;
2510     if (SuperLoc.isValid()) {
2511       if (const ObjCObjectPointerType *
2512             OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2513         if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
2514           // Either we know this is a designated initializer or we
2515           // conservatively assume it because we don't know for sure.
2516           if (!ID->declaresOrInheritsDesignatedInitializers() ||
2517               ID->isDesignatedInitializer(Sel)) {
2518             isDesignatedInitChain = true;
2519             DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
2520           }
2521         }
2522       }
2523     }
2524     if (!isDesignatedInitChain) {
2525       const ObjCMethodDecl *InitMethod = 0;
2526       bool isDesignated =
2527         getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2528       assert(isDesignated && InitMethod);
2529       (void)isDesignated;
2530       Diag(SelLoc, SuperLoc.isValid() ?
2531              diag::warn_objc_designated_init_non_designated_init_call :
2532              diag::warn_objc_designated_init_non_super_designated_init_call);
2533       Diag(InitMethod->getLocation(),
2534            diag::note_objc_designated_init_marked_here);
2535     }
2536   }
2537 
2538   if (DIFunctionScopeInfo &&
2539       DIFunctionScopeInfo->ObjCIsSecondaryInit &&
2540       (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2541     if (SuperLoc.isValid()) {
2542       Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2543     } else {
2544       DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
2545     }
2546   }
2547 
2548   // Check the message arguments.
2549   unsigned NumArgs = ArgsIn.size();
2550   Expr **Args = ArgsIn.data();
2551   QualType ReturnType;
2552   ExprValueKind VK = VK_RValue;
2553   bool ClassMessage = (ReceiverType->isObjCClassType() ||
2554                        ReceiverType->isObjCQualifiedClassType());
2555   if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2556                                 Sel, SelectorLocs, Method,
2557                                 ClassMessage, SuperLoc.isValid(),
2558                                 LBracLoc, RBracLoc, ReturnType, VK))
2559     return ExprError();
2560 
2561   if (Method && !Method->getReturnType()->isVoidType() &&
2562       RequireCompleteType(LBracLoc, Method->getReturnType(),
2563                           diag::err_illegal_message_expr_incomplete_type))
2564     return ExprError();
2565 
2566   // In ARC, forbid the user from sending messages to
2567   // retain/release/autorelease/dealloc/retainCount explicitly.
2568   if (getLangOpts().ObjCAutoRefCount) {
2569     ObjCMethodFamily family =
2570       (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2571     switch (family) {
2572     case OMF_init:
2573       if (Method)
2574         checkInitMethod(Method, ReceiverType);
2575 
2576     case OMF_None:
2577     case OMF_alloc:
2578     case OMF_copy:
2579     case OMF_finalize:
2580     case OMF_mutableCopy:
2581     case OMF_new:
2582     case OMF_self:
2583       break;
2584 
2585     case OMF_dealloc:
2586     case OMF_retain:
2587     case OMF_release:
2588     case OMF_autorelease:
2589     case OMF_retainCount:
2590       Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2591         << Sel << RecRange;
2592       break;
2593 
2594     case OMF_performSelector:
2595       if (Method && NumArgs >= 1) {
2596         if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2597           Selector ArgSel = SelExp->getSelector();
2598           ObjCMethodDecl *SelMethod =
2599             LookupInstanceMethodInGlobalPool(ArgSel,
2600                                              SelExp->getSourceRange());
2601           if (!SelMethod)
2602             SelMethod =
2603               LookupFactoryMethodInGlobalPool(ArgSel,
2604                                               SelExp->getSourceRange());
2605           if (SelMethod) {
2606             ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2607             switch (SelFamily) {
2608               case OMF_alloc:
2609               case OMF_copy:
2610               case OMF_mutableCopy:
2611               case OMF_new:
2612               case OMF_self:
2613               case OMF_init:
2614                 // Issue error, unless ns_returns_not_retained.
2615                 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2616                   // selector names a +1 method
2617                   Diag(SelLoc,
2618                        diag::err_arc_perform_selector_retains);
2619                   Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2620                     << SelMethod->getDeclName();
2621                 }
2622                 break;
2623               default:
2624                 // +0 call. OK. unless ns_returns_retained.
2625                 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2626                   // selector names a +1 method
2627                   Diag(SelLoc,
2628                        diag::err_arc_perform_selector_retains);
2629                   Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2630                     << SelMethod->getDeclName();
2631                 }
2632                 break;
2633             }
2634           }
2635         } else {
2636           // error (may leak).
2637           Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
2638           Diag(Args[0]->getExprLoc(), diag::note_used_here);
2639         }
2640       }
2641       break;
2642     }
2643   }
2644 
2645   // Construct the appropriate ObjCMessageExpr instance.
2646   ObjCMessageExpr *Result;
2647   if (SuperLoc.isValid())
2648     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2649                                      SuperLoc,  /*IsInstanceSuper=*/true,
2650                                      ReceiverType, Sel, SelectorLocs, Method,
2651                                      makeArrayRef(Args, NumArgs), RBracLoc,
2652                                      isImplicit);
2653   else {
2654     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2655                                      Receiver, Sel, SelectorLocs, Method,
2656                                      makeArrayRef(Args, NumArgs), RBracLoc,
2657                                      isImplicit);
2658     if (!isImplicit)
2659       checkCocoaAPI(*this, Result);
2660   }
2661 
2662   if (getLangOpts().ObjCAutoRefCount) {
2663     DiagnoseARCUseOfWeakReceiver(*this, Receiver);
2664 
2665     // In ARC, annotate delegate init calls.
2666     if (Result->getMethodFamily() == OMF_init &&
2667         (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2668       // Only consider init calls *directly* in init implementations,
2669       // not within blocks.
2670       ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2671       if (method && method->getMethodFamily() == OMF_init) {
2672         // The implicit assignment to self means we also don't want to
2673         // consume the result.
2674         Result->setDelegateInitCall(true);
2675         return Owned(Result);
2676       }
2677     }
2678 
2679     // In ARC, check for message sends which are likely to introduce
2680     // retain cycles.
2681     checkRetainCycles(Result);
2682 
2683     if (!isImplicit && Method) {
2684       if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2685         bool IsWeak =
2686           Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2687         if (!IsWeak && Sel.isUnarySelector())
2688           IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
2689 
2690         if (IsWeak) {
2691           DiagnosticsEngine::Level Level =
2692             Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
2693                                      LBracLoc);
2694           if (Level != DiagnosticsEngine::Ignored)
2695             getCurFunction()->recordUseOfWeak(Result, Prop);
2696 
2697         }
2698       }
2699     }
2700   }
2701 
2702   return MaybeBindToTemporary(Result);
2703 }
2704 
2705 static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2706   if (ObjCSelectorExpr *OSE =
2707       dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2708     Selector Sel = OSE->getSelector();
2709     SourceLocation Loc = OSE->getAtLoc();
2710     llvm::DenseMap<Selector, SourceLocation>::iterator Pos
2711     = S.ReferencedSelectors.find(Sel);
2712     if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
2713       S.ReferencedSelectors.erase(Pos);
2714   }
2715 }
2716 
2717 // ActOnInstanceMessage - used for both unary and keyword messages.
2718 // ArgExprs is optional - if it is present, the number of expressions
2719 // is obtained from Sel.getNumArgs().
2720 ExprResult Sema::ActOnInstanceMessage(Scope *S,
2721                                       Expr *Receiver,
2722                                       Selector Sel,
2723                                       SourceLocation LBracLoc,
2724                                       ArrayRef<SourceLocation> SelectorLocs,
2725                                       SourceLocation RBracLoc,
2726                                       MultiExprArg Args) {
2727   if (!Receiver)
2728     return ExprError();
2729 
2730   // A ParenListExpr can show up while doing error recovery with invalid code.
2731   if (isa<ParenListExpr>(Receiver)) {
2732     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
2733     if (Result.isInvalid()) return ExprError();
2734     Receiver = Result.take();
2735   }
2736 
2737   if (RespondsToSelectorSel.isNull()) {
2738     IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
2739     RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
2740   }
2741   if (Sel == RespondsToSelectorSel)
2742     RemoveSelectorFromWarningCache(*this, Args[0]);
2743 
2744   return BuildInstanceMessage(Receiver, Receiver->getType(),
2745                               /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
2746                               LBracLoc, SelectorLocs, RBracLoc, Args);
2747 }
2748 
2749 enum ARCConversionTypeClass {
2750   /// int, void, struct A
2751   ACTC_none,
2752 
2753   /// id, void (^)()
2754   ACTC_retainable,
2755 
2756   /// id*, id***, void (^*)(),
2757   ACTC_indirectRetainable,
2758 
2759   /// void* might be a normal C type, or it might a CF type.
2760   ACTC_voidPtr,
2761 
2762   /// struct A*
2763   ACTC_coreFoundation
2764 };
2765 static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2766   return (ACTC == ACTC_retainable ||
2767           ACTC == ACTC_coreFoundation ||
2768           ACTC == ACTC_voidPtr);
2769 }
2770 static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2771   return ACTC == ACTC_none ||
2772          ACTC == ACTC_voidPtr ||
2773          ACTC == ACTC_coreFoundation;
2774 }
2775 
2776 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
2777   bool isIndirect = false;
2778 
2779   // Ignore an outermost reference type.
2780   if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
2781     type = ref->getPointeeType();
2782     isIndirect = true;
2783   }
2784 
2785   // Drill through pointers and arrays recursively.
2786   while (true) {
2787     if (const PointerType *ptr = type->getAs<PointerType>()) {
2788       type = ptr->getPointeeType();
2789 
2790       // The first level of pointer may be the innermost pointer on a CF type.
2791       if (!isIndirect) {
2792         if (type->isVoidType()) return ACTC_voidPtr;
2793         if (type->isRecordType()) return ACTC_coreFoundation;
2794       }
2795     } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2796       type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2797     } else {
2798       break;
2799     }
2800     isIndirect = true;
2801   }
2802 
2803   if (isIndirect) {
2804     if (type->isObjCARCBridgableType())
2805       return ACTC_indirectRetainable;
2806     return ACTC_none;
2807   }
2808 
2809   if (type->isObjCARCBridgableType())
2810     return ACTC_retainable;
2811 
2812   return ACTC_none;
2813 }
2814 
2815 namespace {
2816   /// A result from the cast checker.
2817   enum ACCResult {
2818     /// Cannot be casted.
2819     ACC_invalid,
2820 
2821     /// Can be safely retained or not retained.
2822     ACC_bottom,
2823 
2824     /// Can be casted at +0.
2825     ACC_plusZero,
2826 
2827     /// Can be casted at +1.
2828     ACC_plusOne
2829   };
2830   ACCResult merge(ACCResult left, ACCResult right) {
2831     if (left == right) return left;
2832     if (left == ACC_bottom) return right;
2833     if (right == ACC_bottom) return left;
2834     return ACC_invalid;
2835   }
2836 
2837   /// A checker which white-lists certain expressions whose conversion
2838   /// to or from retainable type would otherwise be forbidden in ARC.
2839   class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2840     typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2841 
2842     ASTContext &Context;
2843     ARCConversionTypeClass SourceClass;
2844     ARCConversionTypeClass TargetClass;
2845     bool Diagnose;
2846 
2847     static bool isCFType(QualType type) {
2848       // Someday this can use ns_bridged.  For now, it has to do this.
2849       return type->isCARCBridgableType();
2850     }
2851 
2852   public:
2853     ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
2854                    ARCConversionTypeClass target, bool diagnose)
2855       : Context(Context), SourceClass(source), TargetClass(target),
2856         Diagnose(diagnose) {}
2857 
2858     using super::Visit;
2859     ACCResult Visit(Expr *e) {
2860       return super::Visit(e->IgnoreParens());
2861     }
2862 
2863     ACCResult VisitStmt(Stmt *s) {
2864       return ACC_invalid;
2865     }
2866 
2867     /// Null pointer constants can be casted however you please.
2868     ACCResult VisitExpr(Expr *e) {
2869       if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2870         return ACC_bottom;
2871       return ACC_invalid;
2872     }
2873 
2874     /// Objective-C string literals can be safely casted.
2875     ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2876       // If we're casting to any retainable type, go ahead.  Global
2877       // strings are immune to retains, so this is bottom.
2878       if (isAnyRetainable(TargetClass)) return ACC_bottom;
2879 
2880       return ACC_invalid;
2881     }
2882 
2883     /// Look through certain implicit and explicit casts.
2884     ACCResult VisitCastExpr(CastExpr *e) {
2885       switch (e->getCastKind()) {
2886         case CK_NullToPointer:
2887           return ACC_bottom;
2888 
2889         case CK_NoOp:
2890         case CK_LValueToRValue:
2891         case CK_BitCast:
2892         case CK_CPointerToObjCPointerCast:
2893         case CK_BlockPointerToObjCPointerCast:
2894         case CK_AnyPointerToBlockPointerCast:
2895           return Visit(e->getSubExpr());
2896 
2897         default:
2898           return ACC_invalid;
2899       }
2900     }
2901 
2902     /// Look through unary extension.
2903     ACCResult VisitUnaryExtension(UnaryOperator *e) {
2904       return Visit(e->getSubExpr());
2905     }
2906 
2907     /// Ignore the LHS of a comma operator.
2908     ACCResult VisitBinComma(BinaryOperator *e) {
2909       return Visit(e->getRHS());
2910     }
2911 
2912     /// Conditional operators are okay if both sides are okay.
2913     ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2914       ACCResult left = Visit(e->getTrueExpr());
2915       if (left == ACC_invalid) return ACC_invalid;
2916       return merge(left, Visit(e->getFalseExpr()));
2917     }
2918 
2919     /// Look through pseudo-objects.
2920     ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2921       // If we're getting here, we should always have a result.
2922       return Visit(e->getResultExpr());
2923     }
2924 
2925     /// Statement expressions are okay if their result expression is okay.
2926     ACCResult VisitStmtExpr(StmtExpr *e) {
2927       return Visit(e->getSubStmt()->body_back());
2928     }
2929 
2930     /// Some declaration references are okay.
2931     ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2932       // References to global constants from system headers are okay.
2933       // These are things like 'kCFStringTransformToLatin'.  They are
2934       // can also be assumed to be immune to retains.
2935       VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2936       if (isAnyRetainable(TargetClass) &&
2937           isAnyRetainable(SourceClass) &&
2938           var &&
2939           var->getStorageClass() == SC_Extern &&
2940           var->getType().isConstQualified() &&
2941           Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2942         return ACC_bottom;
2943       }
2944 
2945       // Nothing else.
2946       return ACC_invalid;
2947     }
2948 
2949     /// Some calls are okay.
2950     ACCResult VisitCallExpr(CallExpr *e) {
2951       if (FunctionDecl *fn = e->getDirectCallee())
2952         if (ACCResult result = checkCallToFunction(fn))
2953           return result;
2954 
2955       return super::VisitCallExpr(e);
2956     }
2957 
2958     ACCResult checkCallToFunction(FunctionDecl *fn) {
2959       // Require a CF*Ref return type.
2960       if (!isCFType(fn->getReturnType()))
2961         return ACC_invalid;
2962 
2963       if (!isAnyRetainable(TargetClass))
2964         return ACC_invalid;
2965 
2966       // Honor an explicit 'not retained' attribute.
2967       if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2968         return ACC_plusZero;
2969 
2970       // Honor an explicit 'retained' attribute, except that for
2971       // now we're not going to permit implicit handling of +1 results,
2972       // because it's a bit frightening.
2973       if (fn->hasAttr<CFReturnsRetainedAttr>())
2974         return Diagnose ? ACC_plusOne
2975                         : ACC_invalid; // ACC_plusOne if we start accepting this
2976 
2977       // Recognize this specific builtin function, which is used by CFSTR.
2978       unsigned builtinID = fn->getBuiltinID();
2979       if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2980         return ACC_bottom;
2981 
2982       // Otherwise, don't do anything implicit with an unaudited function.
2983       if (!fn->hasAttr<CFAuditedTransferAttr>())
2984         return ACC_invalid;
2985 
2986       // Otherwise, it's +0 unless it follows the create convention.
2987       if (ento::coreFoundation::followsCreateRule(fn))
2988         return Diagnose ? ACC_plusOne
2989                         : ACC_invalid; // ACC_plusOne if we start accepting this
2990 
2991       return ACC_plusZero;
2992     }
2993 
2994     ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
2995       return checkCallToMethod(e->getMethodDecl());
2996     }
2997 
2998     ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
2999       ObjCMethodDecl *method;
3000       if (e->isExplicitProperty())
3001         method = e->getExplicitProperty()->getGetterMethodDecl();
3002       else
3003         method = e->getImplicitPropertyGetter();
3004       return checkCallToMethod(method);
3005     }
3006 
3007     ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3008       if (!method) return ACC_invalid;
3009 
3010       // Check for message sends to functions returning CF types.  We
3011       // just obey the Cocoa conventions with these, even though the
3012       // return type is CF.
3013       if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
3014         return ACC_invalid;
3015 
3016       // If the method is explicitly marked not-retained, it's +0.
3017       if (method->hasAttr<CFReturnsNotRetainedAttr>())
3018         return ACC_plusZero;
3019 
3020       // If the method is explicitly marked as returning retained, or its
3021       // selector follows a +1 Cocoa convention, treat it as +1.
3022       if (method->hasAttr<CFReturnsRetainedAttr>())
3023         return ACC_plusOne;
3024 
3025       switch (method->getSelector().getMethodFamily()) {
3026       case OMF_alloc:
3027       case OMF_copy:
3028       case OMF_mutableCopy:
3029       case OMF_new:
3030         return ACC_plusOne;
3031 
3032       default:
3033         // Otherwise, treat it as +0.
3034         return ACC_plusZero;
3035       }
3036     }
3037   };
3038 }
3039 
3040 bool Sema::isKnownName(StringRef name) {
3041   if (name.empty())
3042     return false;
3043   LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
3044                  Sema::LookupOrdinaryName);
3045   return LookupName(R, TUScope, false);
3046 }
3047 
3048 static void addFixitForObjCARCConversion(Sema &S,
3049                                          DiagnosticBuilder &DiagB,
3050                                          Sema::CheckedConversionKind CCK,
3051                                          SourceLocation afterLParen,
3052                                          QualType castType,
3053                                          Expr *castExpr,
3054                                          Expr *realCast,
3055                                          const char *bridgeKeyword,
3056                                          const char *CFBridgeName) {
3057   // We handle C-style and implicit casts here.
3058   switch (CCK) {
3059   case Sema::CCK_ImplicitConversion:
3060   case Sema::CCK_CStyleCast:
3061   case Sema::CCK_OtherCast:
3062     break;
3063   case Sema::CCK_FunctionalCast:
3064     return;
3065   }
3066 
3067   if (CFBridgeName) {
3068     if (CCK == Sema::CCK_OtherCast) {
3069       if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3070         SourceRange range(NCE->getOperatorLoc(),
3071                           NCE->getAngleBrackets().getEnd());
3072         SmallString<32> BridgeCall;
3073 
3074         SourceManager &SM = S.getSourceManager();
3075         char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3076         if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3077           BridgeCall += ' ';
3078 
3079         BridgeCall += CFBridgeName;
3080         DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3081       }
3082       return;
3083     }
3084     Expr *castedE = castExpr;
3085     if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3086       castedE = CCE->getSubExpr();
3087     castedE = castedE->IgnoreImpCasts();
3088     SourceRange range = castedE->getSourceRange();
3089 
3090     SmallString<32> BridgeCall;
3091 
3092     SourceManager &SM = S.getSourceManager();
3093     char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3094     if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3095       BridgeCall += ' ';
3096 
3097     BridgeCall += CFBridgeName;
3098 
3099     if (isa<ParenExpr>(castedE)) {
3100       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3101                          BridgeCall));
3102     } else {
3103       BridgeCall += '(';
3104       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3105                                                     BridgeCall));
3106       DiagB.AddFixItHint(FixItHint::CreateInsertion(
3107                                        S.PP.getLocForEndOfToken(range.getEnd()),
3108                                        ")"));
3109     }
3110     return;
3111   }
3112 
3113   if (CCK == Sema::CCK_CStyleCast) {
3114     DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
3115   } else if (CCK == Sema::CCK_OtherCast) {
3116     if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3117       std::string castCode = "(";
3118       castCode += bridgeKeyword;
3119       castCode += castType.getAsString();
3120       castCode += ")";
3121       SourceRange Range(NCE->getOperatorLoc(),
3122                         NCE->getAngleBrackets().getEnd());
3123       DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3124     }
3125   } else {
3126     std::string castCode = "(";
3127     castCode += bridgeKeyword;
3128     castCode += castType.getAsString();
3129     castCode += ")";
3130     Expr *castedE = castExpr->IgnoreImpCasts();
3131     SourceRange range = castedE->getSourceRange();
3132     if (isa<ParenExpr>(castedE)) {
3133       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3134                          castCode));
3135     } else {
3136       castCode += "(";
3137       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3138                                                     castCode));
3139       DiagB.AddFixItHint(FixItHint::CreateInsertion(
3140                                        S.PP.getLocForEndOfToken(range.getEnd()),
3141                                        ")"));
3142     }
3143   }
3144 }
3145 
3146 template <typename T>
3147 static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3148   TypedefNameDecl *TDNDecl = TD->getDecl();
3149   QualType QT = TDNDecl->getUnderlyingType();
3150   if (QT->isPointerType()) {
3151     QT = QT->getPointeeType();
3152     if (const RecordType *RT = QT->getAs<RecordType>())
3153       if (RecordDecl *RD = RT->getDecl())
3154         return RD->getAttr<T>();
3155   }
3156   return 0;
3157 }
3158 
3159 static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3160                                                             TypedefNameDecl *&TDNDecl) {
3161   while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3162     TDNDecl = TD->getDecl();
3163     if (ObjCBridgeRelatedAttr *ObjCBAttr =
3164         getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3165       return ObjCBAttr;
3166     T = TDNDecl->getUnderlyingType();
3167   }
3168   return 0;
3169 }
3170 
3171 static void
3172 diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3173                           QualType castType, ARCConversionTypeClass castACTC,
3174                           Expr *castExpr, Expr *realCast,
3175                           ARCConversionTypeClass exprACTC,
3176                           Sema::CheckedConversionKind CCK) {
3177   SourceLocation loc =
3178     (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
3179 
3180   if (S.makeUnavailableInSystemHeader(loc,
3181                 "converts between Objective-C and C pointers in -fobjc-arc"))
3182     return;
3183 
3184   QualType castExprType = castExpr->getType();
3185   TypedefNameDecl *TDNDecl = 0;
3186   if ((castACTC == ACTC_coreFoundation &&  exprACTC == ACTC_retainable &&
3187        ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3188       (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
3189        ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
3190     return;
3191 
3192   unsigned srcKind = 0;
3193   switch (exprACTC) {
3194   case ACTC_none:
3195   case ACTC_coreFoundation:
3196   case ACTC_voidPtr:
3197     srcKind = (castExprType->isPointerType() ? 1 : 0);
3198     break;
3199   case ACTC_retainable:
3200     srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3201     break;
3202   case ACTC_indirectRetainable:
3203     srcKind = 4;
3204     break;
3205   }
3206 
3207   // Check whether this could be fixed with a bridge cast.
3208   SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3209   SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
3210 
3211   // Bridge from an ARC type to a CF type.
3212   if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
3213 
3214     S.Diag(loc, diag::err_arc_cast_requires_bridge)
3215       << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3216       << 2 // of C pointer type
3217       << castExprType
3218       << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3219       << castType
3220       << castRange
3221       << castExpr->getSourceRange();
3222     bool br = S.isKnownName("CFBridgingRelease");
3223     ACCResult CreateRule =
3224       ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3225     assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3226     if (CreateRule != ACC_plusOne)
3227     {
3228       DiagnosticBuilder DiagB =
3229         (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3230                               : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3231 
3232       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3233                                    castType, castExpr, realCast, "__bridge ", 0);
3234     }
3235     if (CreateRule != ACC_plusZero)
3236     {
3237       DiagnosticBuilder DiagB =
3238         (CCK == Sema::CCK_OtherCast && !br) ?
3239           S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3240           S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3241                  diag::note_arc_bridge_transfer)
3242             << castExprType << br;
3243 
3244       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3245                                    castType, castExpr, realCast, "__bridge_transfer ",
3246                                    br ? "CFBridgingRelease" : 0);
3247     }
3248 
3249     return;
3250   }
3251 
3252   // Bridge from a CF type to an ARC type.
3253   if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
3254     bool br = S.isKnownName("CFBridgingRetain");
3255     S.Diag(loc, diag::err_arc_cast_requires_bridge)
3256       << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3257       << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3258       << castExprType
3259       << 2 // to C pointer type
3260       << castType
3261       << castRange
3262       << castExpr->getSourceRange();
3263     ACCResult CreateRule =
3264       ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3265     assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3266     if (CreateRule != ACC_plusOne)
3267     {
3268       DiagnosticBuilder DiagB =
3269       (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3270                                : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3271       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3272                                    castType, castExpr, realCast, "__bridge ", 0);
3273     }
3274     if (CreateRule != ACC_plusZero)
3275     {
3276       DiagnosticBuilder DiagB =
3277         (CCK == Sema::CCK_OtherCast && !br) ?
3278           S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3279           S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3280                  diag::note_arc_bridge_retained)
3281             << castType << br;
3282 
3283       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3284                                    castType, castExpr, realCast, "__bridge_retained ",
3285                                    br ? "CFBridgingRetain" : 0);
3286     }
3287 
3288     return;
3289   }
3290 
3291   S.Diag(loc, diag::err_arc_mismatched_cast)
3292     << (CCK != Sema::CCK_ImplicitConversion)
3293     << srcKind << castExprType << castType
3294     << castRange << castExpr->getSourceRange();
3295 }
3296 
3297 template <typename TB>
3298 static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr) {
3299   QualType T = castExpr->getType();
3300   while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3301     TypedefNameDecl *TDNDecl = TD->getDecl();
3302     if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3303       if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3304         NamedDecl *Target = 0;
3305         // Check for an existing type with this name.
3306         LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3307                        Sema::LookupOrdinaryName);
3308         if (S.LookupName(R, S.TUScope)) {
3309           Target = R.getFoundDecl();
3310           if (Target && isa<ObjCInterfaceDecl>(Target)) {
3311             ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3312             if (const ObjCObjectPointerType *InterfacePointerType =
3313                   castType->getAsObjCInterfacePointerType()) {
3314               ObjCInterfaceDecl *CastClass
3315                 = InterfacePointerType->getObjectType()->getInterface();
3316               if ((CastClass == ExprClass) ||
3317                   (CastClass && ExprClass->isSuperClassOf(CastClass)))
3318                 return true;
3319               S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3320                 << T << Target->getName() << castType->getPointeeType();
3321               return true;
3322             } else if (castType->isObjCIdType() ||
3323                        (S.Context.ObjCObjectAdoptsQTypeProtocols(
3324                           castType, ExprClass)))
3325               // ok to cast to 'id'.
3326               // casting to id<p-list> is ok if bridge type adopts all of
3327               // p-list protocols.
3328               return true;
3329             else {
3330               S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3331                 << T << Target->getName() << castType;
3332               S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3333               S.Diag(Target->getLocStart(), diag::note_declared_at);
3334               return true;
3335            }
3336           }
3337         }
3338         S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
3339           << castExpr->getType() << Parm;
3340         S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3341         if (Target)
3342           S.Diag(Target->getLocStart(), diag::note_declared_at);
3343       }
3344       return true;
3345     }
3346     T = TDNDecl->getUnderlyingType();
3347   }
3348   return false;
3349 }
3350 
3351 template <typename TB>
3352 static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr) {
3353   QualType T = castType;
3354   while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3355     TypedefNameDecl *TDNDecl = TD->getDecl();
3356     if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3357       if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3358         NamedDecl *Target = 0;
3359         // Check for an existing type with this name.
3360         LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3361                        Sema::LookupOrdinaryName);
3362         if (S.LookupName(R, S.TUScope)) {
3363           Target = R.getFoundDecl();
3364           if (Target && isa<ObjCInterfaceDecl>(Target)) {
3365             ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3366             if (const ObjCObjectPointerType *InterfacePointerType =
3367                   castExpr->getType()->getAsObjCInterfacePointerType()) {
3368               ObjCInterfaceDecl *ExprClass
3369                 = InterfacePointerType->getObjectType()->getInterface();
3370               if ((CastClass == ExprClass) ||
3371                   (ExprClass && CastClass->isSuperClassOf(ExprClass)))
3372                 return true;
3373               S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3374                 << castExpr->getType()->getPointeeType() << T;
3375               S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3376               return true;
3377             } else if (castExpr->getType()->isObjCIdType() ||
3378                        (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3379                           castExpr->getType(), CastClass)))
3380               // ok to cast an 'id' expression to a CFtype.
3381               // ok to cast an 'id<plist>' expression to CFtype provided plist
3382               // adopts all of CFtype's ObjetiveC's class plist.
3383               return true;
3384             else {
3385               S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3386                 << castExpr->getType() << castType;
3387               S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3388               S.Diag(Target->getLocStart(), diag::note_declared_at);
3389               return true;
3390             }
3391           }
3392         }
3393         S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3394         << castExpr->getType() << castType;
3395         S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3396         if (Target)
3397           S.Diag(Target->getLocStart(), diag::note_declared_at);
3398       }
3399       return true;
3400     }
3401     T = TDNDecl->getUnderlyingType();
3402   }
3403   return false;
3404 }
3405 
3406 void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
3407   // warn in presence of __bridge casting to or from a toll free bridge cast.
3408   ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3409   ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3410   if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
3411     (void)CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr);
3412     (void)CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr);
3413   }
3414   else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
3415     (void)CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr);
3416     (void)CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr);
3417   }
3418 }
3419 
3420 
3421 bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3422                                             QualType DestType, QualType SrcType,
3423                                             ObjCInterfaceDecl *&RelatedClass,
3424                                             ObjCMethodDecl *&ClassMethod,
3425                                             ObjCMethodDecl *&InstanceMethod,
3426                                             TypedefNameDecl *&TDNDecl,
3427                                             bool CfToNs) {
3428   QualType T = CfToNs ? SrcType : DestType;
3429   ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3430   if (!ObjCBAttr)
3431     return false;
3432 
3433   IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3434   IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3435   IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3436   if (!RCId)
3437     return false;
3438   NamedDecl *Target = 0;
3439   // Check for an existing type with this name.
3440   LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3441                  Sema::LookupOrdinaryName);
3442   if (!LookupName(R, TUScope)) {
3443     Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
3444           << SrcType << DestType;
3445     Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3446     return false;
3447   }
3448   Target = R.getFoundDecl();
3449   if (Target && isa<ObjCInterfaceDecl>(Target))
3450     RelatedClass = cast<ObjCInterfaceDecl>(Target);
3451   else {
3452     Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3453           << SrcType << DestType;
3454     Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3455     if (Target)
3456       Diag(Target->getLocStart(), diag::note_declared_at);
3457     return false;
3458   }
3459 
3460   // Check for an existing class method with the given selector name.
3461   if (CfToNs && CMId) {
3462     Selector Sel = Context.Selectors.getUnarySelector(CMId);
3463     ClassMethod = RelatedClass->lookupMethod(Sel, false);
3464     if (!ClassMethod) {
3465       Diag(Loc, diag::err_objc_bridged_related_known_method)
3466             << SrcType << DestType << Sel << false;
3467       Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3468       return false;
3469     }
3470   }
3471 
3472   // Check for an existing instance method with the given selector name.
3473   if (!CfToNs && IMId) {
3474     Selector Sel = Context.Selectors.getNullarySelector(IMId);
3475     InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3476     if (!InstanceMethod) {
3477       Diag(Loc, diag::err_objc_bridged_related_known_method)
3478             << SrcType << DestType << Sel << true;
3479       Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3480       return false;
3481     }
3482   }
3483   return true;
3484 }
3485 
3486 bool
3487 Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
3488                                         QualType DestType, QualType SrcType,
3489                                         Expr *&SrcExpr) {
3490   ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3491   ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3492   bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3493   bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3494   if (!CfToNs && !NsToCf)
3495     return false;
3496 
3497   ObjCInterfaceDecl *RelatedClass;
3498   ObjCMethodDecl *ClassMethod = 0;
3499   ObjCMethodDecl *InstanceMethod = 0;
3500   TypedefNameDecl *TDNDecl = 0;
3501   if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
3502                                         ClassMethod, InstanceMethod, TDNDecl, CfToNs))
3503     return false;
3504 
3505   if (CfToNs) {
3506     // Implicit conversion from CF to ObjC object is needed.
3507     if (ClassMethod) {
3508       std::string ExpressionString = "[";
3509       ExpressionString += RelatedClass->getNameAsString();
3510       ExpressionString += " ";
3511       ExpressionString += ClassMethod->getSelector().getAsString();
3512       SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3513       // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
3514       Diag(Loc, diag::err_objc_bridged_related_known_method)
3515         << SrcType << DestType << ClassMethod->getSelector() << false
3516         << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3517         << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
3518       Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3519       Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3520 
3521       QualType receiverType =
3522         Context.getObjCInterfaceType(RelatedClass);
3523       // Argument.
3524       Expr *args[] = { SrcExpr };
3525       ExprResult msg = BuildClassMessageImplicit(receiverType, false,
3526                                       ClassMethod->getLocation(),
3527                                       ClassMethod->getSelector(), ClassMethod,
3528                                       MultiExprArg(args, 1));
3529       SrcExpr = msg.take();
3530       return true;
3531     }
3532   }
3533   else {
3534     // Implicit conversion from ObjC type to CF object is needed.
3535     if (InstanceMethod) {
3536       std::string ExpressionString;
3537       SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3538       if (InstanceMethod->isPropertyAccessor())
3539         if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
3540           // fixit: ObjectExpr.propertyname when it is  aproperty accessor.
3541           ExpressionString = ".";
3542           ExpressionString += PDecl->getNameAsString();
3543           Diag(Loc, diag::err_objc_bridged_related_known_method)
3544           << SrcType << DestType << InstanceMethod->getSelector() << true
3545           << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3546         }
3547       if (ExpressionString.empty()) {
3548         // Provide a fixit: [ObjectExpr InstanceMethod]
3549         ExpressionString = " ";
3550         ExpressionString += InstanceMethod->getSelector().getAsString();
3551         ExpressionString += "]";
3552 
3553         Diag(Loc, diag::err_objc_bridged_related_known_method)
3554         << SrcType << DestType << InstanceMethod->getSelector() << true
3555         << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3556         << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3557       }
3558       Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3559       Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3560 
3561       ExprResult msg =
3562         BuildInstanceMessageImplicit(SrcExpr, SrcType,
3563                                      InstanceMethod->getLocation(),
3564                                      InstanceMethod->getSelector(),
3565                                      InstanceMethod, None);
3566       SrcExpr = msg.take();
3567       return true;
3568     }
3569   }
3570   return false;
3571 }
3572 
3573 Sema::ARCConversionResult
3574 Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
3575                              Expr *&castExpr, CheckedConversionKind CCK,
3576                              bool DiagnoseCFAudited) {
3577   QualType castExprType = castExpr->getType();
3578 
3579   // For the purposes of the classification, we assume reference types
3580   // will bind to temporaries.
3581   QualType effCastType = castType;
3582   if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3583     effCastType = ref->getPointeeType();
3584 
3585   ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3586   ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
3587   if (exprACTC == castACTC) {
3588     // check for viablity and report error if casting an rvalue to a
3589     // life-time qualifier.
3590     if ((castACTC == ACTC_retainable) &&
3591         (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
3592         (castType != castExprType)) {
3593       const Type *DT = castType.getTypePtr();
3594       QualType QDT = castType;
3595       // We desugar some types but not others. We ignore those
3596       // that cannot happen in a cast; i.e. auto, and those which
3597       // should not be de-sugared; i.e typedef.
3598       if (const ParenType *PT = dyn_cast<ParenType>(DT))
3599         QDT = PT->desugar();
3600       else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3601         QDT = TP->desugar();
3602       else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3603         QDT = AT->desugar();
3604       if (QDT != castType &&
3605           QDT.getObjCLifetime() !=  Qualifiers::OCL_None) {
3606         SourceLocation loc =
3607           (castRange.isValid() ? castRange.getBegin()
3608                               : castExpr->getExprLoc());
3609         Diag(loc, diag::err_arc_nolifetime_behavior);
3610       }
3611     }
3612     return ACR_okay;
3613   }
3614 
3615   if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
3616 
3617   // Allow all of these types to be cast to integer types (but not
3618   // vice-versa).
3619   if (castACTC == ACTC_none && castType->isIntegralType(Context))
3620     return ACR_okay;
3621 
3622   // Allow casts between pointers to lifetime types (e.g., __strong id*)
3623   // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
3624   // must be explicit.
3625   if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
3626     return ACR_okay;
3627   if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
3628       CCK != CCK_ImplicitConversion)
3629     return ACR_okay;
3630 
3631   if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation &&
3632       (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast))
3633     if (CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr) ||
3634         CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr))
3635       return ACR_okay;
3636 
3637   if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3638       (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast))
3639     if (CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr) ||
3640         CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr))
3641       return ACR_okay;
3642 
3643 
3644   switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
3645   // For invalid casts, fall through.
3646   case ACC_invalid:
3647     break;
3648 
3649   // Do nothing for both bottom and +0.
3650   case ACC_bottom:
3651   case ACC_plusZero:
3652     return ACR_okay;
3653 
3654   // If the result is +1, consume it here.
3655   case ACC_plusOne:
3656     castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3657                                         CK_ARCConsumeObject, castExpr,
3658                                         0, VK_RValue);
3659     ExprNeedsCleanups = true;
3660     return ACR_okay;
3661   }
3662 
3663   // If this is a non-implicit cast from id or block type to a
3664   // CoreFoundation type, delay complaining in case the cast is used
3665   // in an acceptable context.
3666   if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3667       CCK != CCK_ImplicitConversion)
3668     return ACR_unbridged;
3669 
3670   // Do not issue bridge cast" diagnostic when implicit casting a cstring
3671   // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
3672   // suitable fix-it.
3673   if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
3674       ConversionToObjCStringLiteralCheck(castType, castExpr))
3675     return ACR_okay;
3676 
3677   // Do not issue "bridge cast" diagnostic when implicit casting
3678   // a retainable object to a CF type parameter belonging to an audited
3679   // CF API function. Let caller issue a normal type mismatched diagnostic
3680   // instead.
3681   if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
3682       castACTC != ACTC_coreFoundation)
3683     diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3684                               castExpr, castExpr, exprACTC, CCK);
3685   return ACR_okay;
3686 }
3687 
3688 /// Given that we saw an expression with the ARCUnbridgedCastTy
3689 /// placeholder type, complain bitterly.
3690 void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3691   // We expect the spurious ImplicitCastExpr to already have been stripped.
3692   assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3693   CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3694 
3695   SourceRange castRange;
3696   QualType castType;
3697   CheckedConversionKind CCK;
3698 
3699   if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3700     castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3701     castType = cast->getTypeAsWritten();
3702     CCK = CCK_CStyleCast;
3703   } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3704     castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3705     castType = cast->getTypeAsWritten();
3706     CCK = CCK_OtherCast;
3707   } else {
3708     castType = cast->getType();
3709     CCK = CCK_ImplicitConversion;
3710   }
3711 
3712   ARCConversionTypeClass castACTC =
3713     classifyTypeForARCConversion(castType.getNonReferenceType());
3714 
3715   Expr *castExpr = realCast->getSubExpr();
3716   assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3717 
3718   diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3719                             castExpr, realCast, ACTC_retainable, CCK);
3720 }
3721 
3722 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3723 /// type, remove the placeholder cast.
3724 Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3725   assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3726 
3727   if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3728     Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3729     return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3730   } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3731     assert(uo->getOpcode() == UO_Extension);
3732     Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3733     return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3734                                    sub->getValueKind(), sub->getObjectKind(),
3735                                        uo->getOperatorLoc());
3736   } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3737     assert(!gse->isResultDependent());
3738 
3739     unsigned n = gse->getNumAssocs();
3740     SmallVector<Expr*, 4> subExprs(n);
3741     SmallVector<TypeSourceInfo*, 4> subTypes(n);
3742     for (unsigned i = 0; i != n; ++i) {
3743       subTypes[i] = gse->getAssocTypeSourceInfo(i);
3744       Expr *sub = gse->getAssocExpr(i);
3745       if (i == gse->getResultIndex())
3746         sub = stripARCUnbridgedCast(sub);
3747       subExprs[i] = sub;
3748     }
3749 
3750     return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3751                                               gse->getControllingExpr(),
3752                                               subTypes, subExprs,
3753                                               gse->getDefaultLoc(),
3754                                               gse->getRParenLoc(),
3755                                        gse->containsUnexpandedParameterPack(),
3756                                               gse->getResultIndex());
3757   } else {
3758     assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3759     return cast<ImplicitCastExpr>(e)->getSubExpr();
3760   }
3761 }
3762 
3763 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3764                                                  QualType exprType) {
3765   QualType canCastType =
3766     Context.getCanonicalType(castType).getUnqualifiedType();
3767   QualType canExprType =
3768     Context.getCanonicalType(exprType).getUnqualifiedType();
3769   if (isa<ObjCObjectPointerType>(canCastType) &&
3770       castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3771       canExprType->isObjCObjectPointerType()) {
3772     if (const ObjCObjectPointerType *ObjT =
3773         canExprType->getAs<ObjCObjectPointerType>())
3774       if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
3775         return !ObjI->isArcWeakrefUnavailable();
3776   }
3777   return true;
3778 }
3779 
3780 /// Look for an ObjCReclaimReturnedObject cast and destroy it.
3781 static Expr *maybeUndoReclaimObject(Expr *e) {
3782   // For now, we just undo operands that are *immediately* reclaim
3783   // expressions, which prevents the vast majority of potential
3784   // problems here.  To catch them all, we'd need to rebuild arbitrary
3785   // value-propagating subexpressions --- we can't reliably rebuild
3786   // in-place because of expression sharing.
3787   if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
3788     if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
3789       return ice->getSubExpr();
3790 
3791   return e;
3792 }
3793 
3794 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3795                                       ObjCBridgeCastKind Kind,
3796                                       SourceLocation BridgeKeywordLoc,
3797                                       TypeSourceInfo *TSInfo,
3798                                       Expr *SubExpr) {
3799   ExprResult SubResult = UsualUnaryConversions(SubExpr);
3800   if (SubResult.isInvalid()) return ExprError();
3801   SubExpr = SubResult.take();
3802 
3803   QualType T = TSInfo->getType();
3804   QualType FromType = SubExpr->getType();
3805 
3806   CastKind CK;
3807 
3808   bool MustConsume = false;
3809   if (T->isDependentType() || SubExpr->isTypeDependent()) {
3810     // Okay: we'll build a dependent expression type.
3811     CK = CK_Dependent;
3812   } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3813     // Casting CF -> id
3814     CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3815                                   : CK_CPointerToObjCPointerCast);
3816     switch (Kind) {
3817     case OBC_Bridge:
3818       break;
3819 
3820     case OBC_BridgeRetained: {
3821       bool br = isKnownName("CFBridgingRelease");
3822       Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3823         << 2
3824         << FromType
3825         << (T->isBlockPointerType()? 1 : 0)
3826         << T
3827         << SubExpr->getSourceRange()
3828         << Kind;
3829       Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3830         << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3831       Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
3832         << FromType << br
3833         << FixItHint::CreateReplacement(BridgeKeywordLoc,
3834                                         br ? "CFBridgingRelease "
3835                                            : "__bridge_transfer ");
3836 
3837       Kind = OBC_Bridge;
3838       break;
3839     }
3840 
3841     case OBC_BridgeTransfer:
3842       // We must consume the Objective-C object produced by the cast.
3843       MustConsume = true;
3844       break;
3845     }
3846   } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3847     // Okay: id -> CF
3848     CK = CK_BitCast;
3849     switch (Kind) {
3850     case OBC_Bridge:
3851       // Reclaiming a value that's going to be __bridge-casted to CF
3852       // is very dangerous, so we don't do it.
3853       SubExpr = maybeUndoReclaimObject(SubExpr);
3854       break;
3855 
3856     case OBC_BridgeRetained:
3857       // Produce the object before casting it.
3858       SubExpr = ImplicitCastExpr::Create(Context, FromType,
3859                                          CK_ARCProduceObject,
3860                                          SubExpr, 0, VK_RValue);
3861       break;
3862 
3863     case OBC_BridgeTransfer: {
3864       bool br = isKnownName("CFBridgingRetain");
3865       Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3866         << (FromType->isBlockPointerType()? 1 : 0)
3867         << FromType
3868         << 2
3869         << T
3870         << SubExpr->getSourceRange()
3871         << Kind;
3872 
3873       Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3874         << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3875       Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
3876         << T << br
3877         << FixItHint::CreateReplacement(BridgeKeywordLoc,
3878                           br ? "CFBridgingRetain " : "__bridge_retained");
3879 
3880       Kind = OBC_Bridge;
3881       break;
3882     }
3883     }
3884   } else {
3885     Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3886       << FromType << T << Kind
3887       << SubExpr->getSourceRange()
3888       << TSInfo->getTypeLoc().getSourceRange();
3889     return ExprError();
3890   }
3891 
3892   Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
3893                                                    BridgeKeywordLoc,
3894                                                    TSInfo, SubExpr);
3895 
3896   if (MustConsume) {
3897     ExprNeedsCleanups = true;
3898     Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
3899                                       0, VK_RValue);
3900   }
3901 
3902   return Result;
3903 }
3904 
3905 ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
3906                                       SourceLocation LParenLoc,
3907                                       ObjCBridgeCastKind Kind,
3908                                       SourceLocation BridgeKeywordLoc,
3909                                       ParsedType Type,
3910                                       SourceLocation RParenLoc,
3911                                       Expr *SubExpr) {
3912   TypeSourceInfo *TSInfo = 0;
3913   QualType T = GetTypeFromParser(Type, &TSInfo);
3914   if (Kind == OBC_Bridge)
3915     CheckTollFreeBridgeCast(T, SubExpr);
3916   if (!TSInfo)
3917     TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3918   return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
3919                               SubExpr);
3920 }
3921