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