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