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