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