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