clang  5.0.0
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.
68  assert(CAT && "String literal not of constant array type!");
70  CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1),
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()) {
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)) {
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)) {
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.
128  if (Ty.isNull()) {
129  ObjCInterfaceDecl *NSStringIDecl =
132  SourceLocation(), NSIdent,
133  nullptr, nullptr, SourceLocation());
134  Ty = Context.getObjCInterfaceType(NSStringIDecl);
136  }
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) {
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 
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 =
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 =
664  &Context.Idents.get("bytes"),
666  /*TInfo=*/nullptr,
667  SC_None, nullptr);
668  Params.push_back(bytes);
669 
670  QualType ConstCharType = Context.CharTy.withConst();
671  ParmVarDecl *type =
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.
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"),
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 ||
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
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.
884  if (!DictionaryWithObjectsMethod) {
885  Selector Sel = NSAPIObj->getNSDictionarySelector(
887  ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
888  if (!Method && getLangOpts().DebuggerObjCLiteral) {
890  SourceLocation(), SourceLocation(), Sel,
891  IdT,
892  nullptr /*TypeSourceInfo */,
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"),
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 ||
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 =
960  llvm::makeArrayRef(
961  (ObjCProtocolDecl**) PQ,
962  1),
963  false);
964  QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
965  }
966  }
967  if (!QIDNSCopying.isNull())
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
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 
1081 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1082  SourceLocation EncodeLoc,
1083  SourceLocation LParenLoc,
1084  ParsedType ty,
1085  SourceLocation RParenLoc) {
1086  // FIXME: Preserve type source info ?
1087  TypeSourceInfo *TInfo;
1088  QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1089  if (!TInfo)
1090  TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
1091  getLocForEndOfToken(LParenLoc));
1092 
1093  return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
1094 }
1095 
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) {
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 &&
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  }
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 
1228  if (Ty.isNull())
1229  return true;
1231  return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
1232 }
1233 
1234 /// Try to capture an implicit reference to 'self'.
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 
1481  Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
1482  return;
1483 
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];
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 
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(
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 
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 =
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)
1873  OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
1874  else
1875  return new (Context)
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 
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)
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 
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)) {
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);
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)
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();
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.
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()) {
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].
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 
2701  if (result.isUsable()) {
2702  Receiver = result.get();
2703  ReceiverType = Receiver->getType();
2704  }
2705  }
2706  }
2707 
2708  // There's a somewhat weird interaction here where we assume that we
2709  // won't actually have a method unless we also don't need to do some
2710  // of the more detailed type-checking on the receiver.
2711 
2712  if (!Method) {
2713  // Handle messages to id and __kindof types (where we use the
2714  // global method pool).
2715  const ObjCObjectType *typeBound = nullptr;
2716  bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
2717  typeBound);
2718  if (receiverIsIdLike || ReceiverType->isBlockPointerType() ||
2719  (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2721  // If we have a type bound, further filter the methods.
2722  CollectMultipleMethodsInGlobalPool(Sel, Methods, true/*InstanceFirst*/,
2723  true/*CheckTheOther*/, typeBound);
2724  if (!Methods.empty()) {
2725  // We choose the first method as the initial candidate, then try to
2726  // select a better one.
2727  Method = Methods[0];
2728 
2729  if (ObjCMethodDecl *BestMethod =
2730  SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(), Methods))
2731  Method = BestMethod;
2732 
2733  if (!AreMultipleMethodsInGlobalPool(Sel, Method,
2734  SourceRange(LBracLoc, RBracLoc),
2735  receiverIsIdLike, Methods))
2736  DiagnoseUseOfDecl(Method, SelLoc);
2737  }
2738  } else if (ReceiverType->isObjCClassOrClassKindOfType() ||
2739  ReceiverType->isObjCQualifiedClassType()) {
2740  // Handle messages to Class.
2741  // We allow sending a message to a qualified Class ("Class<foo>"), which
2742  // is ok as long as one of the protocols implements the selector (if not,
2743  // warn).
2744  if (!ReceiverType->isObjCClassOrClassKindOfType()) {
2745  const ObjCObjectPointerType *QClassTy
2746  = ReceiverType->getAsObjCQualifiedClassType();
2747  // Search protocols for class methods.
2748  Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2749  if (!Method) {
2750  Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2751  // warn if instance method found for a Class message.
2752  if (Method && !isMethodDeclaredInRootProtocol(*this, Method)) {
2753  Diag(SelLoc, diag::warn_instance_method_on_class_found)
2754  << Method->getSelector() << Sel;
2755  Diag(Method->getLocation(), diag::note_method_declared_at)
2756  << Method->getDeclName();
2757  }
2758  }
2759  } else {
2760  if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2761  if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2762  // First check the public methods in the class interface.
2763  Method = ClassDecl->lookupClassMethod(Sel);
2764 
2765  if (!Method)
2766  Method = ClassDecl->lookupPrivateClassMethod(Sel);
2767  }
2768  if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2769  return ExprError();
2770  }
2771  if (!Method) {
2772  // If not messaging 'self', look for any factory method named 'Sel'.
2773  if (!Receiver || !isSelfExpr(Receiver)) {
2774  // If no class (factory) method was found, check if an _instance_
2775  // method of the same name exists in the root class only.
2778  false/*InstanceFirst*/,
2779  true/*CheckTheOther*/);
2780  if (!Methods.empty()) {
2781  // We choose the first method as the initial candidate, then try
2782  // to select a better one.
2783  Method = Methods[0];
2784 
2785  // If we find an instance method, emit waring.
2786  if (Method->isInstanceMethod()) {
2787  if (const ObjCInterfaceDecl *ID =
2788  dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2789  if (ID->getSuperClass())
2790  Diag(SelLoc, diag::warn_root_inst_method_not_found)
2791  << Sel << SourceRange(LBracLoc, RBracLoc);
2792  }
2793  }
2794 
2795  if (ObjCMethodDecl *BestMethod =
2796  SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2797  Methods))
2798  Method = BestMethod;
2799  }
2800  }
2801  }
2802  }
2803  } else {
2804  ObjCInterfaceDecl *ClassDecl = nullptr;
2805 
2806  // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2807  // long as one of the protocols implements the selector (if not, warn).
2808  // And as long as message is not deprecated/unavailable (warn if it is).
2809  if (const ObjCObjectPointerType *QIdTy
2810  = ReceiverType->getAsObjCQualifiedIdType()) {
2811  // Search protocols for instance methods.
2812  Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2813  if (!Method)
2814  Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
2815  if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2816  return ExprError();
2817  } else if (const ObjCObjectPointerType *OCIType
2818  = ReceiverType->getAsObjCInterfacePointerType()) {
2819  // We allow sending a message to a pointer to an interface (an object).
2820  ClassDecl = OCIType->getInterfaceDecl();
2821 
2822  // Try to complete the type. Under ARC, this is a hard error from which
2823  // we don't try to recover.
2824  // FIXME: In the non-ARC case, this will still be a hard error if the
2825  // definition is found in a module that's not visible.
2826  const ObjCInterfaceDecl *forwardClass = nullptr;
2827  if (RequireCompleteType(Loc, OCIType->getPointeeType(),
2828  getLangOpts().ObjCAutoRefCount
2829  ? diag::err_arc_receiver_forward_instance
2830  : diag::warn_receiver_forward_instance,
2831  Receiver? Receiver->getSourceRange()
2832  : SourceRange(SuperLoc))) {
2833  if (getLangOpts().ObjCAutoRefCount)
2834  return ExprError();
2835 
2836  forwardClass = OCIType->getInterfaceDecl();
2837  Diag(Receiver ? Receiver->getLocStart()
2838  : SuperLoc, diag::note_receiver_is_id);
2839  Method = nullptr;
2840  } else {
2841  Method = ClassDecl->lookupInstanceMethod(Sel);
2842  }
2843 
2844  if (!Method)
2845  // Search protocol qualifiers.
2846  Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2847 
2848  if (!Method) {
2849  // If we have implementations in scope, check "private" methods.
2850  Method = ClassDecl->lookupPrivateMethod(Sel);
2851 
2852  if (!Method && getLangOpts().ObjCAutoRefCount) {
2853  Diag(SelLoc, diag::err_arc_may_not_respond)
2854  << OCIType->getPointeeType() << Sel << RecRange
2855  << SourceRange(SelectorLocs.front(), SelectorLocs.back());
2856  return ExprError();
2857  }
2858 
2859  if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
2860  // If we still haven't found a method, look in the global pool. This
2861  // behavior isn't very desirable, however we need it for GCC
2862  // compatibility. FIXME: should we deviate??
2863  if (OCIType->qual_empty()) {
2866  true/*InstanceFirst*/,
2867  false/*CheckTheOther*/);
2868  if (!Methods.empty()) {
2869  // We choose the first method as the initial candidate, then try
2870  // to select a better one.
2871  Method = Methods[0];
2872 
2873  if (ObjCMethodDecl *BestMethod =
2874  SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2875  Methods))
2876  Method = BestMethod;
2877 
2878  AreMultipleMethodsInGlobalPool(Sel, Method,
2879  SourceRange(LBracLoc, RBracLoc),
2880  true/*receiverIdOrClass*/,
2881  Methods);
2882  }
2883  if (Method && !forwardClass)
2884  Diag(SelLoc, diag::warn_maynot_respond)
2885  << OCIType->getInterfaceDecl()->getIdentifier()
2886  << Sel << RecRange;
2887  }
2888  }
2889  }
2890  if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
2891  return ExprError();
2892  } else {
2893  // Reject other random receiver types (e.g. structs).
2894  Diag(Loc, diag::err_bad_receiver_type)
2895  << ReceiverType << Receiver->getSourceRange();
2896  return ExprError();
2897  }
2898  }
2899  }
2900 
2901  FunctionScopeInfo *DIFunctionScopeInfo =
2902  (Method && Method->getMethodFamily() == OMF_init)
2903  ? getEnclosingFunction() : nullptr;
2904 
2905  if (DIFunctionScopeInfo &&
2906  DIFunctionScopeInfo->ObjCIsDesignatedInit &&
2907  (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2908  bool isDesignatedInitChain = false;
2909  if (SuperLoc.isValid()) {
2910  if (const ObjCObjectPointerType *
2911  OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2912  if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
2913  // Either we know this is a designated initializer or we
2914  // conservatively assume it because we don't know for sure.
2915  if (!ID->declaresOrInheritsDesignatedInitializers() ||
2916  ID->isDesignatedInitializer(Sel)) {
2917  isDesignatedInitChain = true;
2918  DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
2919  }
2920  }
2921  }
2922  }
2923  if (!isDesignatedInitChain) {
2924  const ObjCMethodDecl *InitMethod = nullptr;
2925  bool isDesignated =
2927  assert(isDesignated && InitMethod);
2928  (void)isDesignated;
2929  Diag(SelLoc, SuperLoc.isValid() ?
2930  diag::warn_objc_designated_init_non_designated_init_call :
2931  diag::warn_objc_designated_init_non_super_designated_init_call);
2932  Diag(InitMethod->getLocation(),
2933  diag::note_objc_designated_init_marked_here);
2934  }
2935  }
2936 
2937  if (DIFunctionScopeInfo &&
2938  DIFunctionScopeInfo->ObjCIsSecondaryInit &&
2939  (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2940  if (SuperLoc.isValid()) {
2941  Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2942  } else {
2943  DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
2944  }
2945  }
2946 
2947  // Check the message arguments.
2948  unsigned NumArgs = ArgsIn.size();
2949  Expr **Args = ArgsIn.data();
2950  QualType ReturnType;
2951  ExprValueKind VK = VK_RValue;
2952  bool ClassMessage = (ReceiverType->isObjCClassType() ||
2953  ReceiverType->isObjCQualifiedClassType());
2954  if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2955  Sel, SelectorLocs, Method,
2956  ClassMessage, SuperLoc.isValid(),
2957  LBracLoc, RBracLoc, RecRange, ReturnType, VK))
2958  return ExprError();
2959 
2960  if (Method && !Method->getReturnType()->isVoidType() &&
2961  RequireCompleteType(LBracLoc, Method->getReturnType(),
2962  diag::err_illegal_message_expr_incomplete_type))
2963  return ExprError();
2964 
2965  // In ARC, forbid the user from sending messages to
2966  // retain/release/autorelease/dealloc/retainCount explicitly.
2967  if (getLangOpts().ObjCAutoRefCount) {
2968  ObjCMethodFamily family =
2969  (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2970  switch (family) {
2971  case OMF_init:
2972  if (Method)
2973  checkInitMethod(Method, ReceiverType);
2974 
2975  case OMF_None:
2976  case OMF_alloc:
2977  case OMF_copy:
2978  case OMF_finalize:
2979  case OMF_mutableCopy:
2980  case OMF_new:
2981  case OMF_self:
2982  case OMF_initialize:
2983  break;
2984 
2985  case OMF_dealloc:
2986  case OMF_retain:
2987  case OMF_release:
2988  case OMF_autorelease:
2989  case OMF_retainCount:
2990  Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2991  << Sel << RecRange;
2992  break;
2993 
2994  case OMF_performSelector:
2995  if (Method && NumArgs >= 1) {
2996  if (const auto *SelExp =
2997  dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens())) {
2998  Selector ArgSel = SelExp->getSelector();
2999  ObjCMethodDecl *SelMethod =
3001  SelExp->getSourceRange());
3002  if (!SelMethod)
3003  SelMethod =
3005  SelExp->getSourceRange());
3006  if (SelMethod) {
3007  ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
3008  switch (SelFamily) {
3009  case OMF_alloc:
3010  case OMF_copy:
3011  case OMF_mutableCopy:
3012  case OMF_new:
3013  case OMF_init:
3014  // Issue error, unless ns_returns_not_retained.
3015  if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
3016  // selector names a +1 method
3017  Diag(SelLoc,
3018  diag::err_arc_perform_selector_retains);
3019  Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3020  << SelMethod->getDeclName();
3021  }
3022  break;
3023  default:
3024  // +0 call. OK. unless ns_returns_retained.
3025  if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
3026  // selector names a +1 method
3027  Diag(SelLoc,
3028  diag::err_arc_perform_selector_retains);
3029  Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3030  << SelMethod->getDeclName();
3031  }
3032  break;
3033  }
3034  }
3035  } else {
3036  // error (may leak).
3037  Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
3038  Diag(Args[0]->getExprLoc(), diag::note_used_here);
3039  }
3040  }
3041  break;
3042  }
3043  }
3044 
3045  DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
3046 
3047  // Construct the appropriate ObjCMessageExpr instance.
3049  if (SuperLoc.isValid())
3050  Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
3051  SuperLoc, /*IsInstanceSuper=*/true,
3052  ReceiverType, Sel, SelectorLocs, Method,
3053  makeArrayRef(Args, NumArgs), RBracLoc,
3054  isImplicit);
3055  else {
3056  Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
3057  Receiver, Sel, SelectorLocs, Method,
3058  makeArrayRef(Args, NumArgs), RBracLoc,
3059  isImplicit);
3060  if (!isImplicit)
3061  checkCocoaAPI(*this, Result);
3062  }
3063  if (Method) {
3064  bool IsClassObjectCall = ClassMessage;
3065  // 'self' message receivers in class methods should be treated as message
3066  // sends to the class object in order for the semantic checks to be
3067  // performed correctly. Messages to 'super' already count as class messages,
3068  // so they don't need to be handled here.
3069  if (Receiver && isSelfExpr(Receiver)) {
3070  if (const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>()) {
3071  if (OPT->getObjectType()->isObjCClass()) {
3072  if (const auto *CurMeth = getCurMethodDecl()) {
3073  IsClassObjectCall = true;
3074  ReceiverType =
3075  Context.getObjCInterfaceType(CurMeth->getClassInterface());
3076  }
3077  }
3078  }
3079  }
3080  checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
3081  ReceiverType, IsClassObjectCall);
3082  }
3083 
3084  if (getLangOpts().ObjCAutoRefCount) {
3085  // In ARC, annotate delegate init calls.
3086  if (Result->getMethodFamily() == OMF_init &&
3087  (SuperLoc.isValid() || isSelfExpr(Receiver))) {
3088  // Only consider init calls *directly* in init implementations,
3089  // not within blocks.
3090  ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
3091  if (method && method->getMethodFamily() == OMF_init) {
3092  // The implicit assignment to self means we also don't want to
3093  // consume the result.
3094  Result->setDelegateInitCall(true);
3095  return Result;
3096  }
3097  }
3098 
3099  // In ARC, check for message sends which are likely to introduce
3100  // retain cycles.
3101  checkRetainCycles(Result);
3102  }
3103 
3104  if (getLangOpts().ObjCWeak) {
3105  if (!isImplicit && Method) {
3106  if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
3107  bool IsWeak =
3108  Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
3109  if (!IsWeak && Sel.isUnarySelector())
3110  IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
3111  if (IsWeak &&
3112  !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
3113  getCurFunction()->recordUseOfWeak(Result, Prop);
3114  }
3115  }
3116  }
3117 
3118  CheckObjCCircularContainer(Result);
3119 
3120  return MaybeBindToTemporary(Result);
3121 }
3122 
3124  if (ObjCSelectorExpr *OSE =
3125  dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
3126  Selector Sel = OSE->getSelector();
3127  SourceLocation Loc = OSE->getAtLoc();
3128  auto Pos = S.ReferencedSelectors.find(Sel);
3129  if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
3130  S.ReferencedSelectors.erase(Pos);
3131  }
3132 }
3133 
3134 // ActOnInstanceMessage - used for both unary and keyword messages.
3135 // ArgExprs is optional - if it is present, the number of expressions
3136 // is obtained from Sel.getNumArgs().
3138  Expr *Receiver,
3139  Selector Sel,
3140  SourceLocation LBracLoc,
3141  ArrayRef<SourceLocation> SelectorLocs,
3142  SourceLocation RBracLoc,
3143  MultiExprArg Args) {
3144  if (!Receiver)
3145  return ExprError();
3146 
3147  // A ParenListExpr can show up while doing error recovery with invalid code.
3148  if (isa<ParenListExpr>(Receiver)) {
3150  if (Result.isInvalid()) return ExprError();
3151  Receiver = Result.get();
3152  }
3153 
3154  if (RespondsToSelectorSel.isNull()) {
3155  IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
3157  }
3158  if (Sel == RespondsToSelectorSel)
3159  RemoveSelectorFromWarningCache(*this, Args[0]);
3160 
3161  return BuildInstanceMessage(Receiver, Receiver->getType(),
3162  /*SuperLoc=*/SourceLocation(), Sel,
3163  /*Method=*/nullptr, LBracLoc, SelectorLocs,
3164  RBracLoc, Args);
3165 }
3166 
3168  /// int, void, struct A
3170 
3171  /// id, void (^)()
3173 
3174  /// id*, id***, void (^*)(),
3176 
3177  /// void* might be a normal C type, or it might a CF type.
3179 
3180  /// struct A*
3182 };
3183 
3185  return (ACTC == ACTC_retainable ||
3186  ACTC == ACTC_coreFoundation ||
3187  ACTC == ACTC_voidPtr);
3188 }
3189 
3191  return ACTC == ACTC_none ||
3192  ACTC == ACTC_voidPtr ||
3193  ACTC == ACTC_coreFoundation;
3194 }
3195 
3197  bool isIndirect = false;
3198 
3199  // Ignore an outermost reference type.
3200  if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
3201  type = ref->getPointeeType();
3202  isIndirect = true;
3203  }
3204 
3205  // Drill through pointers and arrays recursively.
3206  while (true) {
3207  if (const PointerType *ptr = type->getAs<PointerType>()) {
3208  type = ptr->getPointeeType();
3209 
3210  // The first level of pointer may be the innermost pointer on a CF type.
3211  if (!isIndirect) {
3212  if (type->isVoidType()) return ACTC_voidPtr;
3213  if (type->isRecordType()) return ACTC_coreFoundation;
3214  }
3215  } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
3216  type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
3217  } else {
3218  break;
3219  }
3220  isIndirect = true;
3221  }
3222 
3223  if (isIndirect) {
3224  if (type->isObjCARCBridgableType())
3225  return ACTC_indirectRetainable;
3226  return ACTC_none;
3227  }
3228 
3229  if (type->isObjCARCBridgableType())
3230  return ACTC_retainable;
3231 
3232  return ACTC_none;
3233 }
3234 
3235 namespace {
3236  /// A result from the cast checker.
3237  enum ACCResult {
3238  /// Cannot be casted.
3239  ACC_invalid,
3240 
3241  /// Can be safely retained or not retained.
3242  ACC_bottom,
3243 
3244  /// Can be casted at +0.
3245  ACC_plusZero,
3246 
3247  /// Can be casted at +1.
3248  ACC_plusOne
3249  };
3250  ACCResult merge(ACCResult left, ACCResult right) {
3251  if (left == right) return left;
3252  if (left == ACC_bottom) return right;
3253  if (right == ACC_bottom) return left;
3254  return ACC_invalid;
3255  }
3256 
3257  /// A checker which white-lists certain expressions whose conversion
3258  /// to or from retainable type would otherwise be forbidden in ARC.
3259  class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
3261 
3263  ARCConversionTypeClass SourceClass;
3264  ARCConversionTypeClass TargetClass;
3265  bool Diagnose;
3266 
3267  static bool isCFType(QualType type) {
3268  // Someday this can use ns_bridged. For now, it has to do this.
3269  return type->isCARCBridgableType();
3270  }
3271 
3272  public:
3273  ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
3274  ARCConversionTypeClass target, bool diagnose)
3275  : Context(Context), SourceClass(source), TargetClass(target),
3276  Diagnose(diagnose) {}
3277 
3278  using super::Visit;
3279  ACCResult Visit(Expr *e) {
3280  return super::Visit(e->IgnoreParens());
3281  }
3282 
3283  ACCResult VisitStmt(Stmt *s) {
3284  return ACC_invalid;
3285  }
3286 
3287  /// Null pointer constants can be casted however you please.
3288  ACCResult VisitExpr(Expr *e) {
3290  return ACC_bottom;
3291  return ACC_invalid;
3292  }
3293 
3294  /// Objective-C string literals can be safely casted.
3295  ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3296  // If we're casting to any retainable type, go ahead. Global
3297  // strings are immune to retains, so this is bottom.
3298  if (isAnyRetainable(TargetClass)) return ACC_bottom;
3299 
3300  return ACC_invalid;
3301  }
3302 
3303  /// Look through certain implicit and explicit casts.
3304  ACCResult VisitCastExpr(CastExpr *e) {
3305  switch (e->getCastKind()) {
3306  case CK_NullToPointer:
3307  return ACC_bottom;
3308 
3309  case CK_NoOp:
3310  case CK_LValueToRValue:
3311  case CK_BitCast:
3312  case CK_CPointerToObjCPointerCast:
3313  case CK_BlockPointerToObjCPointerCast:
3314  case CK_AnyPointerToBlockPointerCast:
3315  return Visit(e->getSubExpr());
3316 
3317  default:
3318  return ACC_invalid;
3319  }
3320  }
3321 
3322  /// Look through unary extension.
3323  ACCResult VisitUnaryExtension(UnaryOperator *e) {
3324  return Visit(e->getSubExpr());
3325  }
3326 
3327  /// Ignore the LHS of a comma operator.
3328  ACCResult VisitBinComma(BinaryOperator *e) {
3329  return Visit(e->getRHS());
3330  }
3331 
3332  /// Conditional operators are okay if both sides are okay.
3333  ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3334  ACCResult left = Visit(e->getTrueExpr());
3335  if (left == ACC_invalid) return ACC_invalid;
3336  return merge(left, Visit(e->getFalseExpr()));
3337  }
3338 
3339  /// Look through pseudo-objects.
3340  ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3341  // If we're getting here, we should always have a result.
3342  return Visit(e->getResultExpr());
3343  }
3344 
3345  /// Statement expressions are okay if their result expression is okay.
3346  ACCResult VisitStmtExpr(StmtExpr *e) {
3347  return Visit(e->getSubStmt()->body_back());
3348  }
3349 
3350  /// Some declaration references are okay.
3351  ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
3352  VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
3353  // References to global constants are okay.
3354  if (isAnyRetainable(TargetClass) &&
3355  isAnyRetainable(SourceClass) &&
3356  var &&
3357  !var->hasDefinition(Context) &&
3358  var->getType().isConstQualified()) {
3359 
3360  // In system headers, they can also be assumed to be immune to retains.
3361  // These are things like 'kCFStringTransformToLatin'.
3363  return ACC_bottom;
3364 
3365  return ACC_plusZero;
3366  }
3367 
3368  // Nothing else.
3369  return ACC_invalid;
3370  }
3371 
3372  /// Some calls are okay.
3373  ACCResult VisitCallExpr(CallExpr *e) {
3374  if (FunctionDecl *fn = e->getDirectCallee())
3375  if (ACCResult result = checkCallToFunction(fn))
3376  return result;
3377 
3378  return super::VisitCallExpr(e);
3379  }
3380 
3381  ACCResult checkCallToFunction(FunctionDecl *fn) {
3382  // Require a CF*Ref return type.
3383  if (!isCFType(fn->getReturnType()))
3384  return ACC_invalid;
3385 
3386  if (!isAnyRetainable(TargetClass))
3387  return ACC_invalid;
3388 
3389  // Honor an explicit 'not retained' attribute.
3390  if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3391  return ACC_plusZero;
3392 
3393  // Honor an explicit 'retained' attribute, except that for
3394  // now we're not going to permit implicit handling of +1 results,
3395  // because it's a bit frightening.
3396  if (fn->hasAttr<CFReturnsRetainedAttr>())
3397  return Diagnose ? ACC_plusOne
3398  : ACC_invalid; // ACC_plusOne if we start accepting this
3399 
3400  // Recognize this specific builtin function, which is used by CFSTR.
3401  unsigned builtinID = fn->getBuiltinID();
3402  if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3403  return ACC_bottom;
3404 
3405  // Otherwise, don't do anything implicit with an unaudited function.
3406  if (!fn->hasAttr<CFAuditedTransferAttr>())
3407  return ACC_invalid;
3408 
3409  // Otherwise, it's +0 unless it follows the create convention.
3411  return Diagnose ? ACC_plusOne
3412  : ACC_invalid; // ACC_plusOne if we start accepting this
3413 
3414  return ACC_plusZero;
3415  }
3416 
3417  ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3418  return checkCallToMethod(e->getMethodDecl());
3419  }
3420 
3421  ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3422  ObjCMethodDecl *method;
3423  if (e->isExplicitProperty())
3424  method = e->getExplicitProperty()->getGetterMethodDecl();
3425  else
3426  method = e->getImplicitPropertyGetter();
3427  return checkCallToMethod(method);
3428  }
3429 
3430  ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3431  if (!method) return ACC_invalid;
3432 
3433  // Check for message sends to functions returning CF types. We
3434  // just obey the Cocoa conventions with these, even though the
3435  // return type is CF.
3436  if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
3437  return ACC_invalid;
3438 
3439  // If the method is explicitly marked not-retained, it's +0.
3440  if (method->hasAttr<CFReturnsNotRetainedAttr>())
3441  return ACC_plusZero;
3442 
3443  // If the method is explicitly marked as returning retained, or its
3444  // selector follows a +1 Cocoa convention, treat it as +1.
3445  if (method->hasAttr<CFReturnsRetainedAttr>())
3446  return ACC_plusOne;
3447 
3448  switch (method->getSelector().getMethodFamily()) {
3449  case OMF_alloc:
3450  case OMF_copy:
3451  case OMF_mutableCopy:
3452  case OMF_new:
3453  return ACC_plusOne;
3454 
3455  default:
3456  // Otherwise, treat it as +0.
3457  return ACC_plusZero;
3458  }
3459  }
3460  };
3461 } // end anonymous namespace
3462 
3463 bool Sema::isKnownName(StringRef name) {
3464  if (name.empty())
3465  return false;
3466  LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
3468  return LookupName(R, TUScope, false);
3469 }
3470 
3472  DiagnosticBuilder &DiagB,
3474  SourceLocation afterLParen,
3475  QualType castType,
3476  Expr *castExpr,
3477  Expr *realCast,
3478  const char *bridgeKeyword,
3479  const char *CFBridgeName) {
3480  // We handle C-style and implicit casts here.
3481  switch (CCK) {
3483  case Sema::CCK_CStyleCast:
3484  case Sema::CCK_OtherCast:
3485  break;
3487  return;
3488  }
3489 
3490  if (CFBridgeName) {
3491  if (CCK == Sema::CCK_OtherCast) {
3492  if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3493  SourceRange range(NCE->getOperatorLoc(),
3494  NCE->getAngleBrackets().getEnd());
3495  SmallString<32> BridgeCall;
3496 
3498  char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3499  if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3500  BridgeCall += ' ';
3501 
3502  BridgeCall += CFBridgeName;
3503  DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3504  }
3505  return;
3506  }
3507  Expr *castedE = castExpr;
3508  if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3509  castedE = CCE->getSubExpr();
3510  castedE = castedE->IgnoreImpCasts();
3511  SourceRange range = castedE->getSourceRange();
3512 
3513  SmallString<32> BridgeCall;
3514 
3516  char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3517  if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3518  BridgeCall += ' ';
3519 
3520  BridgeCall += CFBridgeName;
3521 
3522  if (isa<ParenExpr>(castedE)) {
3524  BridgeCall));
3525  } else {
3526  BridgeCall += '(';
3528  BridgeCall));
3530  S.getLocForEndOfToken(range.getEnd()),
3531  ")"));
3532  }
3533  return;
3534  }
3535 
3536  if (CCK == Sema::CCK_CStyleCast) {
3537  DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
3538  } else if (CCK == Sema::CCK_OtherCast) {
3539  if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3540  std::string castCode = "(";
3541  castCode += bridgeKeyword;
3542  castCode += castType.getAsString();
3543  castCode += ")";
3544  SourceRange Range(NCE->getOperatorLoc(),
3545  NCE->getAngleBrackets().getEnd());
3546  DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3547  }
3548  } else {
3549  std::string castCode = "(";
3550  castCode += bridgeKeyword;
3551  castCode += castType.getAsString();
3552  castCode += ")";
3553  Expr *castedE = castExpr->IgnoreImpCasts();
3554  SourceRange range = castedE->getSourceRange();
3555  if (isa<ParenExpr>(castedE)) {
3557  castCode));
3558  } else {
3559  castCode += "(";
3561  castCode));
3563  S.getLocForEndOfToken(range.getEnd()),
3564  ")"));
3565  }
3566  }
3567 }
3568 
3569 template <typename T>
3570 static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3571  TypedefNameDecl *TDNDecl = TD->getDecl();
3572  QualType QT = TDNDecl->getUnderlyingType();
3573  if (QT->isPointerType()) {
3574  QT = QT->getPointeeType();
3575  if (const RecordType *RT = QT->getAs<RecordType>())
3576  if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
3577  return RD->getAttr<T>();
3578  }
3579  return nullptr;
3580 }
3581 
3582 static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3583  TypedefNameDecl *&TDNDecl) {
3584  while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3585  TDNDecl = TD->getDecl();
3586  if (ObjCBridgeRelatedAttr *ObjCBAttr =
3587  getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3588  return ObjCBAttr;
3589  T = TDNDecl->getUnderlyingType();
3590  }
3591  return nullptr;
3592 }
3593 
3594 static void
3596  QualType castType, ARCConversionTypeClass castACTC,
3597  Expr *castExpr, Expr *realCast,
3598  ARCConversionTypeClass exprACTC,
3600  SourceLocation loc =
3601  (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
3602 
3604  UnavailableAttr::IR_ARCForbiddenConversion))
3605  return;
3606 
3607  QualType castExprType = castExpr->getType();
3608  // Defer emitting a diagnostic for bridge-related casts; that will be
3609  // handled by CheckObjCBridgeRelatedConversions.
3610  TypedefNameDecl *TDNDecl = nullptr;
3611  if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3612  ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3613  (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
3614  ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
3615  return;
3616 
3617  unsigned srcKind = 0;
3618  switch (exprACTC) {
3619  case ACTC_none:
3620  case ACTC_coreFoundation:
3621  case ACTC_voidPtr:
3622  srcKind = (castExprType->isPointerType() ? 1 : 0);
3623  break;
3624  case ACTC_retainable:
3625  srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3626  break;
3628  srcKind = 4;
3629  break;
3630  }
3631 
3632  // Check whether this could be fixed with a bridge cast.
3633  SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin());
3634  SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
3635 
3636  // Bridge from an ARC type to a CF type.
3637  if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
3638 
3639  S.Diag(loc, diag::err_arc_cast_requires_bridge)
3640  << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3641  << 2 // of C pointer type
3642  << castExprType
3643  << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3644  << castType
3645  << castRange
3646  << castExpr->getSourceRange();
3647  bool br = S.isKnownName("CFBridgingRelease");
3648  ACCResult CreateRule =
3649  ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3650  assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3651  if (CreateRule != ACC_plusOne)
3652  {
3653  DiagnosticBuilder DiagB =
3654  (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3655  : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3656 
3657  addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3658  castType, castExpr, realCast, "__bridge ",
3659  nullptr);
3660  }
3661  if (CreateRule != ACC_plusZero)
3662  {
3663  DiagnosticBuilder DiagB =
3664  (CCK == Sema::CCK_OtherCast && !br) ?
3665  S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3666  S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3667  diag::note_arc_bridge_transfer)
3668  << castExprType << br;
3669 
3670  addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3671  castType, castExpr, realCast, "__bridge_transfer ",
3672  br ? "CFBridgingRelease" : nullptr);
3673  }
3674 
3675  return;
3676  }
3677 
3678  // Bridge from a CF type to an ARC type.
3679  if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
3680  bool br = S.isKnownName("CFBridgingRetain");
3681  S.Diag(loc, diag::err_arc_cast_requires_bridge)
3682  << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3683  << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3684  << castExprType
3685  << 2 // to C pointer type
3686  << castType
3687  << castRange
3688  << castExpr->getSourceRange();
3689  ACCResult CreateRule =
3690  ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3691  assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3692  if (CreateRule != ACC_plusOne)
3693  {
3694  DiagnosticBuilder DiagB =
3695  (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3696  : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3697  addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3698  castType, castExpr, realCast, "__bridge ",
3699  nullptr);
3700  }
3701  if (CreateRule != ACC_plusZero)
3702  {
3703  DiagnosticBuilder DiagB =
3704  (CCK == Sema::CCK_OtherCast && !br) ?
3705  S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3706  S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3707  diag::note_arc_bridge_retained)
3708  << castType << br;
3709 
3710  addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3711  castType, castExpr, realCast, "__bridge_retained ",
3712  br ? "CFBridgingRetain" : nullptr);
3713  }
3714 
3715  return;
3716  }
3717 
3718  S.Diag(loc, diag::err_arc_mismatched_cast)
3719  << (CCK != Sema::CCK_ImplicitConversion)
3720  << srcKind << castExprType << castType
3721  << castRange << castExpr->getSourceRange();
3722 }
3723 
3724 template <typename TB>
3725 static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3726  bool &HadTheAttribute, bool warn) {
3727  QualType T = castExpr->getType();
3728  HadTheAttribute = false;
3729  while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3730  TypedefNameDecl *TDNDecl = TD->getDecl();
3731  if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3732  if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3733  HadTheAttribute = true;
3734  if (Parm->isStr("id"))
3735  return true;
3736 
3737  NamedDecl *Target = nullptr;
3738  // Check for an existing type with this name.
3741  if (S.LookupName(R, S.TUScope)) {
3742  Target = R.getFoundDecl();
3743  if (Target && isa<ObjCInterfaceDecl>(Target)) {
3744  ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3745  if (const ObjCObjectPointerType *InterfacePointerType =
3746  castType->getAsObjCInterfacePointerType()) {
3747  ObjCInterfaceDecl *CastClass
3748  = InterfacePointerType->getObjectType()->getInterface();
3749  if ((CastClass == ExprClass) ||
3750  (CastClass && CastClass->isSuperClassOf(ExprClass)))
3751  return true;
3752  if (warn)
3753  S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3754  << T << Target->getName() << castType->getPointeeType();
3755  return false;
3756  } else if (castType->isObjCIdType() ||
3758  castType, ExprClass)))
3759  // ok to cast to 'id'.
3760  // casting to id<p-list> is ok if bridge type adopts all of
3761  // p-list protocols.
3762  return true;
3763  else {
3764  if (warn) {
3765  S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3766  << T << Target->getName() << castType;
3767  S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3768  S.Diag(Target->getLocStart(), diag::note_declared_at);
3769  }
3770  return false;
3771  }
3772  }
3773  } else if (!castType->isObjCIdType()) {
3774  S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
3775  << castExpr->getType() << Parm;
3776  S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3777  if (Target)
3778  S.Diag(Target->getLocStart(), diag::note_declared_at);
3779  }
3780  return true;
3781  }
3782  return false;
3783  }
3784  T = TDNDecl->getUnderlyingType();
3785  }
3786  return true;
3787 }
3788 
3789 template <typename TB>
3790 static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3791  bool &HadTheAttribute, bool warn) {
3792  QualType T = castType;
3793  HadTheAttribute = false;
3794  while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3795  TypedefNameDecl *TDNDecl = TD->getDecl();
3796  if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3797  if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3798  HadTheAttribute = true;
3799  if (Parm->isStr("id"))
3800  return true;
3801 
3802  NamedDecl *Target = nullptr;
3803  // Check for an existing type with this name.
3806  if (S.LookupName(R, S.TUScope)) {
3807  Target = R.getFoundDecl();
3808  if (Target && isa<ObjCInterfaceDecl>(Target)) {
3809  ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3810  if (const ObjCObjectPointerType *InterfacePointerType =
3811  castExpr->getType()->getAsObjCInterfacePointerType()) {
3812  ObjCInterfaceDecl *ExprClass
3813  = InterfacePointerType->getObjectType()->getInterface();
3814  if ((CastClass == ExprClass) ||
3815  (ExprClass && CastClass->isSuperClassOf(ExprClass)))
3816  return true;
3817  if (warn) {
3818  S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3819  << castExpr->getType()->getPointeeType() << T;
3820  S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3821  }
3822  return false;
3823  } else if (castExpr->getType()->isObjCIdType() ||
3825  castExpr->getType(), CastClass)))
3826  // ok to cast an 'id' expression to a CFtype.
3827  // ok to cast an 'id<plist>' expression to CFtype provided plist
3828  // adopts all of CFtype's ObjetiveC's class plist.
3829  return true;
3830  else {
3831  if (warn) {
3832  S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3833  << castExpr->getType() << castType;
3834  S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3835  S.Diag(Target->getLocStart(), diag::note_declared_at);
3836  }
3837  return false;
3838  }
3839  }
3840  }
3841  S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3842  << castExpr->getType() << castType;
3843  S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3844  if (Target)
3845  S.Diag(Target->getLocStart(), diag::note_declared_at);
3846  return true;
3847  }
3848  return false;
3849  }
3850  T = TDNDecl->getUnderlyingType();
3851  }
3852  return true;
3853 }
3854 
3856  if (!getLangOpts().ObjC1)
3857  return;
3858  // warn in presence of __bridge casting to or from a toll free bridge cast.
3861  if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
3862  bool HasObjCBridgeAttr;
3863  bool ObjCBridgeAttrWillNotWarn =
3864  CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3865  false);
3866  if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3867  return;
3868  bool HasObjCBridgeMutableAttr;
3869  bool ObjCBridgeMutableAttrWillNotWarn =
3870  CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3871  HasObjCBridgeMutableAttr, false);
3872  if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3873  return;
3874 
3875  if (HasObjCBridgeAttr)
3876  CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3877  true);
3878  else if (HasObjCBridgeMutableAttr)
3879  CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3880  HasObjCBridgeMutableAttr, true);
3881  }
3882  else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
3883  bool HasObjCBridgeAttr;
3884  bool ObjCBridgeAttrWillNotWarn =
3885  CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3886  false);
3887  if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3888  return;
3889  bool HasObjCBridgeMutableAttr;
3890  bool ObjCBridgeMutableAttrWillNotWarn =
3891  CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3892  HasObjCBridgeMutableAttr, false);
3893  if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3894  return;
3895 
3896  if (HasObjCBridgeAttr)
3897  CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3898  true);
3899  else if (HasObjCBridgeMutableAttr)
3900  CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3901  HasObjCBridgeMutableAttr, true);
3902  }
3903 }
3904 
3906  QualType SrcType = castExpr->getType();
3907  if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3908  if (PRE->isExplicitProperty()) {
3909  if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3910  SrcType = PDecl->getType();
3911  }
3912  else if (PRE->isImplicitProperty()) {
3913  if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3914  SrcType = Getter->getReturnType();
3915  }
3916  }
3917 
3919  ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3920  if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3921  return;
3923  castType, SrcType, castExpr);
3924 }
3925 
3927  CastKind &Kind) {
3928  if (!getLangOpts().ObjC1)
3929  return false;
3930  ARCConversionTypeClass exprACTC =
3933  if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3934  (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3935  CheckTollFreeBridgeCast(castType, castExpr);
3936  Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3937  : CK_CPointerToObjCPointerCast;
3938  return true;
3939  }
3940  return false;
3941 }
3942 
3944  QualType DestType, QualType SrcType,
3945  ObjCInterfaceDecl *&RelatedClass,
3946  ObjCMethodDecl *&ClassMethod,
3947  ObjCMethodDecl *&InstanceMethod,
3948  TypedefNameDecl *&TDNDecl,
3949  bool CfToNs, bool Diagnose) {
3950  QualType T = CfToNs ? SrcType : DestType;
3951  ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3952  if (!ObjCBAttr)
3953  return false;
3954 
3955  IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3956  IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3957  IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3958  if (!RCId)
3959  return false;
3960  NamedDecl *Target = nullptr;
3961  // Check for an existing type with this name.
3962  LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3964  if (!LookupName(R, TUScope)) {
3965  if (Diagnose) {
3966  Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
3967  << SrcType << DestType;
3968  Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3969  }
3970  return false;
3971  }
3972  Target = R.getFoundDecl();
3973  if (Target && isa<ObjCInterfaceDecl>(Target))
3974  RelatedClass = cast<ObjCInterfaceDecl>(Target);
3975  else {
3976  if (Diagnose) {
3977  Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3978  << SrcType << DestType;
3979  Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3980  if (Target)
3981  Diag(Target->getLocStart(), diag::note_declared_at);
3982  }
3983  return false;
3984  }
3985 
3986  // Check for an existing class method with the given selector name.
3987  if (CfToNs && CMId) {
3989  ClassMethod = RelatedClass->lookupMethod(Sel, false);
3990  if (!ClassMethod) {
3991  if (Diagnose) {
3992  Diag(Loc, diag::err_objc_bridged_related_known_method)
3993  << SrcType << DestType << Sel << false;
3994  Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3995  }
3996  return false;
3997  }
3998  }
3999 
4000  // Check for an existing instance method with the given selector name.
4001  if (!CfToNs && IMId) {
4003  InstanceMethod = RelatedClass->lookupMethod(Sel, true);
4004  if (!InstanceMethod) {
4005  if (Diagnose) {
4006  Diag(Loc, diag::err_objc_bridged_related_known_method)
4007  << SrcType << DestType << Sel << true;
4008  Diag(TDNDecl->getLocStart(), diag::note_declared_at);
4009  }
4010  return false;
4011  }
4012  }
4013  return true;
4014 }
4015 
4016 bool
4018  QualType DestType, QualType SrcType,
4019  Expr *&SrcExpr, bool Diagnose) {
4021  ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
4022  bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
4023  bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
4024  if (!CfToNs && !NsToCf)
4025  return false;
4026 
4027  ObjCInterfaceDecl *RelatedClass;
4028  ObjCMethodDecl *ClassMethod = nullptr;
4029  ObjCMethodDecl *InstanceMethod = nullptr;
4030  TypedefNameDecl *TDNDecl = nullptr;
4031  if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
4032  ClassMethod, InstanceMethod, TDNDecl,
4033  CfToNs, Diagnose))
4034  return false;
4035 
4036  if (CfToNs) {
4037  // Implicit conversion from CF to ObjC object is needed.
4038  if (ClassMethod) {
4039  if (Diagnose) {
4040  std::string ExpressionString = "[";
4041  ExpressionString += RelatedClass->getNameAsString();
4042  ExpressionString += " ";
4043  ExpressionString += ClassMethod->getSelector().getAsString();
4044  SourceLocation SrcExprEndLoc = getLocForEndOfToken(SrcExpr->getLocEnd());
4045  // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
4046  Diag(Loc, diag::err_objc_bridged_related_known_method)
4047  << SrcType << DestType << ClassMethod->getSelector() << false
4048  << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
4049  << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
4050  Diag(RelatedClass->getLocStart(), diag::note_declared_at);
4051  Diag(TDNDecl->getLocStart(), diag::note_declared_at);
4052 
4053  QualType receiverType = Context.getObjCInterfaceType(RelatedClass);
4054  // Argument.
4055  Expr *args[] = { SrcExpr };
4056  ExprResult msg = BuildClassMessageImplicit(receiverType, false,
4057  ClassMethod->getLocation(),
4058  ClassMethod->getSelector(), ClassMethod,
4059  MultiExprArg(args, 1));
4060  SrcExpr = msg.get();
4061  }
4062  return true;
4063  }
4064  }
4065  else {
4066  // Implicit conversion from ObjC type to CF object is needed.
4067  if (InstanceMethod) {
4068  if (Diagnose) {
4069  std::string ExpressionString;
4070  SourceLocation SrcExprEndLoc =
4071  getLocForEndOfToken(SrcExpr->getLocEnd());
4072  if (InstanceMethod->isPropertyAccessor())
4073  if (const ObjCPropertyDecl *PDecl =
4074  InstanceMethod->findPropertyDecl()) {
4075  // fixit: ObjectExpr.propertyname when it is aproperty accessor.
4076  ExpressionString = ".";
4077  ExpressionString += PDecl->getNameAsString();
4078  Diag(Loc, diag::err_objc_bridged_related_known_method)
4079  << SrcType << DestType << InstanceMethod->getSelector() << true
4080  << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4081  }
4082  if (ExpressionString.empty()) {
4083  // Provide a fixit: [ObjectExpr InstanceMethod]
4084  ExpressionString = " ";
4085  ExpressionString += InstanceMethod->getSelector().getAsString();
4086  ExpressionString += "]";
4087 
4088  Diag(Loc, diag::err_objc_bridged_related_known_method)
4089  << SrcType << DestType << InstanceMethod->getSelector() << true
4090  << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
4091  << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4092  }
4093  Diag(RelatedClass->getLocStart(), diag::note_declared_at);
4094  Diag(TDNDecl->getLocStart(), diag::note_declared_at);
4095 
4096  ExprResult msg =
4097  BuildInstanceMessageImplicit(SrcExpr, SrcType,
4098  InstanceMethod->getLocation(),
4099  InstanceMethod->getSelector(),
4100  InstanceMethod, None);
4101  SrcExpr = msg.get();
4102  }
4103  return true;
4104  }
4105  }
4106  return false;
4107 }
4108 
4112  bool Diagnose, bool DiagnoseCFAudited,
4113  BinaryOperatorKind Opc) {
4114  QualType castExprType = castExpr->getType();
4115 
4116  // For the purposes of the classification, we assume reference types
4117  // will bind to temporaries.
4118  QualType effCastType = castType;
4119  if (const ReferenceType *ref = castType->getAs<ReferenceType>())
4120  effCastType = ref->getPointeeType();
4121 
4122  ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
4123  ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
4124  if (exprACTC == castACTC) {
4125  // Check for viability and report error if casting an rvalue to a
4126  // life-time qualifier.
4127  if (castACTC == ACTC_retainable &&
4128  (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
4129  castType != castExprType) {
4130  const Type *DT = castType.getTypePtr();
4131  QualType QDT = castType;
4132  // We desugar some types but not others. We ignore those
4133  // that cannot happen in a cast; i.e. auto, and those which
4134  // should not be de-sugared; i.e typedef.
4135  if (const ParenType *PT = dyn_cast<ParenType>(DT))
4136  QDT = PT->desugar();
4137  else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
4138  QDT = TP->desugar();
4139  else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
4140  QDT = AT->desugar();
4141  if (QDT != castType &&
4143  if (Diagnose) {
4144  SourceLocation loc = (castRange.isValid() ? castRange.getBegin()
4145  : castExpr->getExprLoc());
4146  Diag(loc, diag::err_arc_nolifetime_behavior);
4147  }
4148  return ACR_error;
4149  }
4150  }
4151  return ACR_okay;
4152  }
4153 
4154  // The life-time qualifier cast check above is all we need for ObjCWeak.
4155  // ObjCAutoRefCount has more restrictions on what is legal.
4156  if (!getLangOpts().ObjCAutoRefCount)
4157  return ACR_okay;
4158 
4159  if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
4160 
4161  // Allow all of these types to be cast to integer types (but not
4162  // vice-versa).
4163  if (castACTC == ACTC_none && castType->isIntegralType(Context))
4164  return ACR_okay;
4165 
4166  // Allow casts between pointers to lifetime types (e.g., __strong id*)
4167  // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
4168  // must be explicit.
4169  if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
4170  return ACR_okay;
4171  if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
4172  CCK != CCK_ImplicitConversion)
4173  return ACR_okay;
4174 
4175  switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
4176  // For invalid casts, fall through.
4177  case ACC_invalid:
4178  break;
4179 
4180  // Do nothing for both bottom and +0.
4181  case ACC_bottom:
4182  case ACC_plusZero:
4183  return ACR_okay;
4184 
4185  // If the result is +1, consume it here.
4186  case ACC_plusOne:
4187  castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
4188  CK_ARCConsumeObject, castExpr,
4189  nullptr, VK_RValue);
4191  return ACR_okay;
4192  }
4193 
4194  // If this is a non-implicit cast from id or block type to a
4195  // CoreFoundation type, delay complaining in case the cast is used
4196  // in an acceptable context.
4197  if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
4198  CCK != CCK_ImplicitConversion)
4199  return ACR_unbridged;
4200 
4201  // Issue a diagnostic about a missing @-sign when implicit casting a cstring
4202  // to 'NSString *', instead of falling through to report a "bridge cast"
4203  // diagnostic.
4204  if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
4205  ConversionToObjCStringLiteralCheck(castType, castExpr, Diagnose))
4206  return ACR_error;
4207 
4208  // Do not issue "bridge cast" diagnostic when implicit casting
4209  // a retainable object to a CF type parameter belonging to an audited
4210  // CF API function. Let caller issue a normal type mismatched diagnostic
4211  // instead.
4212  if ((!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
4213  castACTC != ACTC_coreFoundation) &&
4214  !(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
4215  (Opc == BO_NE || Opc == BO_EQ))) {
4216  if (Diagnose)
4217  diagnoseObjCARCConversion(*this, castRange, castType, castACTC, castExpr,
4218  castExpr, exprACTC, CCK);
4219  return ACR_error;
4220  }
4221  return ACR_okay;
4222 }
4223 
4224 /// Given that we saw an expression with the ARCUnbridgedCastTy
4225 /// placeholder type, complain bitterly.
4227  // We expect the spurious ImplicitCastExpr to already have been stripped.
4228  assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4229  CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
4230 
4231  SourceRange castRange;
4232  QualType castType;
4234 
4235  if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
4236  castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
4237  castType = cast->getTypeAsWritten();
4238  CCK = CCK_CStyleCast;
4239  } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
4240  castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
4241  castType = cast->getTypeAsWritten();
4242  CCK = CCK_OtherCast;
4243  } else {
4244  llvm_unreachable("Unexpected ImplicitCastExpr");
4245  }
4246 
4247  ARCConversionTypeClass castACTC =
4249 
4250  Expr *castExpr = realCast->getSubExpr();
4251  assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
4252 
4253  diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
4254  castExpr, realCast, ACTC_retainable, CCK);
4255 }
4256 
4257 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
4258 /// type, remove the placeholder cast.
4260  assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4261 
4262  if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
4263  Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
4264  return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
4265  } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
4266  assert(uo->getOpcode() == UO_Extension);
4267  Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
4268  return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
4269  sub->getValueKind(), sub->getObjectKind(),
4270  uo->getOperatorLoc());
4271  } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
4272  assert(!gse->isResultDependent());
4273 
4274  unsigned n = gse->getNumAssocs();
4275  SmallVector<Expr*, 4> subExprs(n);
4276  SmallVector<TypeSourceInfo*, 4> subTypes(n);
4277  for (unsigned i = 0; i != n; ++i) {
4278  subTypes[i] = gse->getAssocTypeSourceInfo(i);
4279  Expr *sub = gse->getAssocExpr(i);
4280  if (i == gse->getResultIndex())
4281  sub = stripARCUnbridgedCast(sub);
4282  subExprs[i] = sub;
4283  }
4284 
4285  return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
4286  gse->getControllingExpr(),
4287  subTypes, subExprs,
4288  gse->getDefaultLoc(),
4289  gse->getRParenLoc(),
4290  gse->containsUnexpandedParameterPack(),
4291  gse->getResultIndex());
4292  } else {
4293  assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
4294  return cast<ImplicitCastExpr>(e)->getSubExpr();
4295  }
4296 }
4297 
4299  QualType exprType) {
4300  QualType canCastType =
4302  QualType canExprType =
4304  if (isa<ObjCObjectPointerType>(canCastType) &&
4305  castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
4306  canExprType->isObjCObjectPointerType()) {
4307  if (const ObjCObjectPointerType *ObjT =
4308  canExprType->getAs<ObjCObjectPointerType>())
4309  if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4310  return !ObjI->isArcWeakrefUnavailable();
4311  }
4312  return true;
4313 }
4314 
4315 /// Look for an ObjCReclaimReturnedObject cast and destroy it.
4317  // For now, we just undo operands that are *immediately* reclaim
4318  // expressions, which prevents the vast majority of potential
4319  // problems here. To catch them all, we'd need to rebuild arbitrary
4320  // value-propagating subexpressions --- we can't reliably rebuild
4321  // in-place because of expression sharing.
4322  if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4323  if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
4324  return ice->getSubExpr();
4325 
4326  return e;
4327 }
4328 
4331  SourceLocation BridgeKeywordLoc,
4332  TypeSourceInfo *TSInfo,
4333  Expr *SubExpr) {
4334  ExprResult SubResult = UsualUnaryConversions(SubExpr);
4335  if (SubResult.isInvalid()) return ExprError();
4336  SubExpr = SubResult.get();
4337 
4338  QualType T = TSInfo->getType();
4339  QualType FromType = SubExpr->getType();
4340 
4341  CastKind CK;
4342 
4343  bool MustConsume = false;
4344  if (T->isDependentType() || SubExpr->isTypeDependent()) {
4345  // Okay: we'll build a dependent expression type.
4346  CK = CK_Dependent;
4347  } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
4348  // Casting CF -> id
4349  CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4350  : CK_CPointerToObjCPointerCast);
4351  switch (Kind) {
4352  case OBC_Bridge:
4353  break;
4354 
4355  case OBC_BridgeRetained: {
4356  bool br = isKnownName("CFBridgingRelease");
4357  Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4358  << 2
4359  << FromType
4360  << (T->isBlockPointerType()? 1 : 0)
4361  << T
4362  << SubExpr->getSourceRange()
4363  << Kind;
4364  Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4365  << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4366  Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
4367  << FromType << br
4368  << FixItHint::CreateReplacement(BridgeKeywordLoc,
4369  br ? "CFBridgingRelease "
4370  : "__bridge_transfer ");
4371 
4372  Kind = OBC_Bridge;
4373  break;
4374  }
4375 
4376  case OBC_BridgeTransfer:
4377  // We must consume the Objective-C object produced by the cast.
4378  MustConsume = true;
4379  break;
4380  }
4381  } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4382  // Okay: id -> CF
4383  CK = CK_BitCast;
4384  switch (Kind) {
4385  case OBC_Bridge:
4386  // Reclaiming a value that's going to be __bridge-casted to CF
4387  // is very dangerous, so we don't do it.
4388  SubExpr = maybeUndoReclaimObject(SubExpr);
4389  break;
4390 
4391  case OBC_BridgeRetained:
4392  // Produce the object before casting it.
4393  SubExpr = ImplicitCastExpr::Create(Context, FromType,
4394  CK_ARCProduceObject,
4395  SubExpr, nullptr, VK_RValue);
4396  break;
4397 
4398  case OBC_BridgeTransfer: {
4399  bool br = isKnownName("CFBridgingRetain");
4400  Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4401  << (FromType->isBlockPointerType()? 1 : 0)
4402  << FromType
4403  << 2
4404  << T
4405  << SubExpr->getSourceRange()
4406  << Kind;
4407 
4408  Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4409  << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4410  Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
4411  << T << br
4412  << FixItHint::CreateReplacement(BridgeKeywordLoc,
4413  br ? "CFBridgingRetain " : "__bridge_retained");
4414 
4415  Kind = OBC_Bridge;
4416  break;
4417  }
4418  }
4419  } else {
4420  Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4421  << FromType << T << Kind
4422  << SubExpr->getSourceRange()
4423  << TSInfo->getTypeLoc().getSourceRange();
4424  return ExprError();
4425  }
4426 
4427  Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
4428  BridgeKeywordLoc,
4429  TSInfo, SubExpr);
4430 
4431  if (MustConsume) {
4433  Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
4434  nullptr, VK_RValue);
4435  }
4436 
4437  return Result;
4438 }
4439 
4441  SourceLocation LParenLoc,
4443  SourceLocation BridgeKeywordLoc,
4444  ParsedType Type,
4445  SourceLocation RParenLoc,
4446  Expr *SubExpr) {
4447  TypeSourceInfo *TSInfo = nullptr;
4448  QualType T = GetTypeFromParser(Type, &TSInfo);
4449  if (Kind == OBC_Bridge)
4450  CheckTollFreeBridgeCast(T, SubExpr);
4451  if (!TSInfo)
4452  TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4453  return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
4454  SubExpr);
4455 }
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...
void setMethodParams(ASTContext &C, ArrayRef< ParmVarDecl * > Params, ArrayRef< SourceLocation > SelLocs=llvm::None)
Sets the method's parameters and selector source locations.
Definition: DeclObjC.cpp:828
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1457
tokloc_iterator tokloc_begin() const
Definition: Expr.h:1639
Defines the clang::ASTContext interface.
ObjCMethodDecl * lookupPrivateClassMethod(const Selector &Sel)
Definition: DeclObjC.h:1780
SourceLocation getEnd() const
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.h:5177
CastKind getCastKind() const
Definition: Expr.h:2749
ObjCStringFormatFamily
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1618
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:5437
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 'self'.
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:237
Smart pointer class that efficiently represents Objective-C method names.
SelectorTable & getSelectorTable()
Definition: Preprocessor.h:735
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2224
CanQualType VoidPtrTy
Definition: ASTContext.h:978
A (possibly-)qualified type.
Definition: Type.h:616
ImplementationControl getImplementationControl() const
Definition: DeclObjC.h:465
Simple class containing the result of Sema::CorrectTypo.
bool isInvalid() const
Definition: Ownership.h:159
ObjCMethodFamily getMethodFamily() const
Definition: ExprObjC.h:1270
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:9130
ObjCMethodDecl * getCategoryClassMethod(Selector Sel) const
Definition: DeclObjC.cpp:1641
void* might be a normal C type, or it might a CF type.
DeclContext * getFunctionLevelDeclContext()
Definition: Sema.cpp:1017
void getOverriddenMethods(SmallVectorImpl< const ObjCMethodDecl * > &Overridden) const
Return overridden methods for the given Method.
Definition: DeclObjC.cpp:1232
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:2954
CompoundStmt * getSubStmt()
Definition: Expr.h:3480
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:232
CanQualType Char32Ty
Definition: ASTContext.h:970
const LangOptions & getLangOpts() const
Definition: Sema.h:1166
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false)
Perform unqualified name lookup starting from a given scope.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
ObjCMessageKind
Describes the kind of message expression indicated by a message send that starts with an identifier...
Definition: Sema.h:8033
Stmt - This represents one statement.
Definition: Stmt.h:60
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:281
static void diagnoseObjCARCConversion(Sema &S, SourceRange castRange, QualType castType, ARCConversionTypeClass castACTC, Expr *castExpr, Expr *realCast, ARCConversionTypeClass exprACTC, Sema::CheckedConversionKind CCK)
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.
ObjCMethodDecl * LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance)
LookupMethodInType - Look up a method in an ObjCObjectType.
static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr, bool &HadTheAttribute, bool warn)
tokloc_iterator tokloc_end() const
Definition: Expr.h:1640
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:779
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:469
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
bool isRecordType() const
Definition: Type.h:5769
static InitializedEntity InitializeParameter(ASTContext &Context, const ParmVarDecl *Parm)
Create the initialization entity for a parameter.
QualType getUnderlyingType() const
Definition: Decl.h:2727
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1243
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:81
ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, ArrayRef< Expr * > Strings)
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer...
static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S, SourceLocation AtLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, ObjCMethodDecl *Method, ObjCMethodList &MethList)
StringRef P
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:784
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:1074
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition: SemaExpr.cpp:716
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1662
std::string getAsString() const
Definition: Type.h:942
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:15469
PtrTy get() const
Definition: Ownership.h:163
IdentifierInfo * getAsIdentifierInfo() const
getAsIdentifierInfo - Retrieve the IdentifierInfo * stored in this declaration name, or NULL if this declaration name isn't a simple identifier.
ObjCStringFormatFamily getStringFormatFamily() const
The base class of the type hierarchy.
Definition: Type.h:1303
bool isObjCQualifiedClassType() const
Definition: Type.h:5803
static void RemoveSelectorFromWarningCache(Sema &S, Expr *Arg)
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2497
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
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:392
A container of type source information.
Definition: Decl.h:62
SourceLocation getLocStart() const LLVM_READONLY
Definition: Expr.h:1642
bool isBlockPointerType() const
Definition: Type.h:5718
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
const ObjCObjectPointerType * getAsObjCQualifiedClassType() const
Definition: Type.cpp:1508
const ObjCPropertyDecl * findPropertyDecl(bool CheckOverrides=true) const
Returns the property associated with this method's selector.
Definition: DeclObjC.cpp:1249
void setDelegateInitCall(bool isDelegate)
Definition: ExprObjC.h:1308
ObjCMethodDecl * getMethod(Selector Sel, bool isInstance, bool AllowHidden=false) const
Definition: DeclObjC.cpp:68
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:137
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:758
bool isExplicitProperty() const
Definition: ExprObjC.h:631
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:25
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:495
DiagnosticsEngine & Diags
Definition: Sema.h:307
ObjCMethodDecl * tryCaptureObjCSelf(SourceLocation Loc)
Try to capture an implicit reference to 'self'.
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclObjC.h:291
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:113
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:1100
static StringRef bytes(const std::vector< T, Allocator > &v)
Definition: ASTWriter.cpp:100
unsigned param_size() const
Definition: DeclObjC.h:348
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
Definition: SemaExpr.cpp:14137
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1434
bool isObjCRetainableType() const
Definition: Type.cpp:3751
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:3209
bool isUnionType() const
Definition: Type.cpp:390
bool isVoidType() const
Definition: Type.h:5906
QualType withConst() const
Retrieves a version of this type with const applied.
Expr * IgnoreImpCasts() LLVM_READONLY
IgnoreImpCasts - Skip past any implicit casts which might surround this expression.
Definition: Expr.h:2847
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3354
The message is a class message, and the identifier is a type name.
Definition: Sema.h:8040
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6...
Definition: SemaExpr.cpp:667
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:812
unsigned getIndexTypeCVRQualifiers() const
Definition: Type.h:2538
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:59
An element in an Objective-C dictionary literal.
Definition: ExprObjC.h:212
bool hasAttr() const
Definition: DeclBase.h:521
Represents a class type in Objective C.
Definition: Type.h:4969
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:9126
ObjCMethodFamily
A family of Objective-C methods.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
static ObjCArrayLiteral * Create(const ASTContext &C, ArrayRef< Expr * > Elements, QualType T, ObjCMethodDecl *Method, SourceRange SR)
Definition: ExprObjC.cpp:38
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
bool isCommitable() const
Definition: Commit.h:65
QualType getReturnType() const
Definition: Decl.h:2106
void diagnoseARCUnbridgedCast(Expr *e)
Given that we saw an expression with the ARCUnbridgedCastTy placeholder type, complain bitterly...
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 PerformContextuallyConvertToObjCPointer(Expr *From)
PerformContextuallyConvertToObjCPointer - Perform a contextual conversion of the expression From to a...
ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
Definition: SemaExpr.cpp:15654
static ObjCBridgeRelatedAttr * ObjCBridgeRelatedAttrFromType(QualType T, TypedefNameDecl *&TDNDecl)
Expr * getSubExpr()
Definition: Expr.h:2753
bool isNull() const
Determine whether this is the empty selector.
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:1295
void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr)
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2128
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:513
bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl)
ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's protocol list adopt all protocols in Q...
ObjCMethodDecl * LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false)
LookupFactoryMethodInGlobalPool - Returns the method and warns if there are multiple signatures...
Definition: Sema.h:3543
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:106
Values of this type can be null.
QualType getObjCNSStringType() const
Definition: ASTContext.h:1519
bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall)
Check whether the given method, which must be in the 'init' family, is a valid member of that family...
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
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
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
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME)
This is not an AltiVec-style cast or or C++ direct-initialization, so turn the ParenListExpr into a s...
Definition: SemaExpr.cpp:6108
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:1042
ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number)
BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the numeric literal expression...
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:931
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.
GlobalMethodPool MethodPool
Method Pool - allows efficient lookup when typechecking messages to "id".
Definition: Sema.h:1096
TypeDecl - Represents a declaration of a type.
Definition: Decl.h:2642
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2967
Selector getSelector() const
Definition: ExprObjC.cpp:306
CanQualType PseudoObjectTy
Definition: ASTContext.h:981
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface...
Definition: Type.h:5199
CheckedConversionKind
The kind of conversion being performed.
Definition: Sema.h:9122
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
bool isDesignatedInitializerForTheInterface(const ObjCMethodDecl **InitMethod=nullptr) const
Returns true if the method selector resolves to a designated initializer in the class's interface...
Definition: DeclObjC.cpp:781
const ObjCObjectType * getAsObjCInterfaceType() const
Definition: Type.cpp:1518
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
Definition: Expr.cpp:2399
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 ObjCMethodDecl * SelectorsForTypoCorrection(Selector Sel, QualType ObjectType=QualType())
void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr)
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2701
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:1985
Preprocessor & PP
Definition: Sema.h:304
ObjCInterfaceDecl * NSNumberDecl
The declaration of the Objective-C NSNumber class.
Definition: Sema.h:815
ExprResult BuildObjCDictionaryLiteral(SourceRange SR, MutableArrayRef< ObjCDictionaryElement > Elements)
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:633
Represents an ObjC class declaration.
Definition: DeclObjC.h:1108
bool CollectMultipleMethodsInGlobalPool(Selector Sel, SmallVectorImpl< ObjCMethodDecl * > &Methods, bool InstanceFirst, bool CheckTheOther, const ObjCObjectType *TypeBound=nullptr)
Returns instance or factory methods in global method pool for given selector.
Bridging via __bridge_transfer, which transfers ownership of an Objective-C pointer into ARC...
bool isExtVectorType() const
Definition: Type.h:5781
ObjCMethodDecl * getMethod() const
SourceLocation OrigLoc
Definition: Commit.h:36
detail::InMemoryDirectory::const_iterator I
ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType)
Type-check an expression that's being passed to an __unknown_anytype parameter.
Definition: SemaExpr.cpp:15473
QualType getType() const
Definition: Decl.h:589
bool isInvalid() const
const LangOptions & LangOpts
Definition: Sema.h:303
edit_iterator edit_begin() const
Definition: Commit.h:110
ObjCMethodDecl * lookupPrivateMethod(const Selector &Sel, bool Instance=true) const
Lookup a method in the classes implementation hierarchy.
Definition: DeclObjC.cpp:720
bool isKnownName(StringRef name)
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type...
Definition: Type.h:6091
static bool isAnyRetainable(ARCConversionTypeClass ACTC)
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:3245
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:269
RecordDecl * getMostRecentDecl()
Definition: Decl.h:3399
Expr * getFalseExpr() const
Definition: Expr.h:3288
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
void EmitRelatedResultTypeNoteForReturn(QualType destType)
Given that we had incompatible pointer types in a return statement, check whether we're in a method w...
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:953
Optional< ArrayRef< QualType > > getObjCSubstitutions(const DeclContext *dc) const
Retrieve the set of substitutions required when accessing a member of the Objective-C receiver type t...
Definition: Type.cpp:1303
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:239
A functional-style cast.
Definition: Sema.h:9128
int, void, struct A
SourceLocation getLocStart() const LLVM_READONLY
Definition: Decl.h:2666
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1028
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...
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:1698
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Stmt.cpp:270
ObjCPropertyDecl * FindPropertyDeclaration(const IdentifierInfo *PropertyId, ObjCPropertyQueryKind QueryKind) const
FindPropertyDeclaration - Finds declaration of the property given its name in 'PropertyId' and return...
Definition: DeclObjC.cpp:213
void recordUseOfWeak(const ExprT *E, bool IsRead=true)
Record that a weak object was accessed.
Definition: ScopeInfo.h:951
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
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.
ASTContext * Context
NSClassIdKindKind
Definition: NSAPI.h:30
sema::FunctionScopeInfo * getEnclosingFunction() const
Definition: Sema.h:1297
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:414
bool isUnarySelector() const
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl...
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:132
const ObjCMethodDecl * getMethodDecl() const
Definition: ExprObjC.h:1251
Expr - This represents one expression.
Definition: Expr.h:105
StringRef getName() const
Return the actual identifier string.
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:103
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)
unsigned getNumArgs() const
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:3941
bool isObjCClassType() const
Definition: Type.h:5813
The message is an instance message.
Definition: Sema.h:8037
static bool isAnyCLike(ARCConversionTypeClass ACTC)
static ARCConversionTypeClass classifyTypeForARCConversion(QualType type)
static QualType stripObjCInstanceType(ASTContext &Context, QualType T)
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:956
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:503
Defines the clang::Preprocessor interface.
ObjCMethodDecl * getImplicitPropertyGetter() const
Definition: ExprObjC.h:638
ObjCMethodDecl * lookupInstanceMethod(Selector Sel) const
Lookup an instance method for a given selector.
Definition: DeclObjC.h:1766
ObjCMethodDecl * lookupClassMethod(Selector Sel) const
Lookup a class method for a given selector.
Definition: DeclObjC.h:1771
DeclContext * getDeclContext()
Definition: DeclBase.h:416
ObjCSelectorExpr used for @selector in Objective-C.
Definition: ExprObjC.h:397
Decl * getNonClosureAncestor()
Find the nearest non-closure ancestor of this context, i.e.
Definition: DeclBase.cpp:944
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:408
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:15541
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
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:821
bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:7107
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:910
Defines the clang::TypeLoc interface and its subclasses.
bool isObjCIdType() const
Definition: Type.h:5808
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:699
static Optional< NullabilityKind > stripOuterNullability(QualType &T)
Strip off the top-level nullability annotation on the given type, if it's there.
Definition: Type.cpp:3663
Expr * getSubExpr() const
Definition: Expr.h:1741
ObjCIvarDecl * lookupInstanceVariable(IdentifierInfo *IVarName, ObjCInterfaceDecl *&ClassDeclared)
Definition: DeclObjC.cpp:600
bool hasRelatedResultType() const
Determine whether this method has a result type that is related to the message receiver's type...
Definition: DeclObjC.h:276
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:1797
bool isInstanceMethod() const
Definition: DeclObjC.h:416
ObjCMessageKind getObjCMessageKind(Scope *S, IdentifierInfo *Name, SourceLocation NameLoc, bool IsSuper, bool HasTrailingDot, ParsedType &ReceiverType)
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:1724
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:860
UnaryOperator - This represents the unary-expression's (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1714
CharSourceRange getInsertFromRange(SourceManager &SM) const
Definition: Commit.cpp:31
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:258
bool rewriteObjCRedundantCallWithLiteral(const ObjCMessageExpr *Msg, const NSAPI &NS, Commit &commit)
ValueDecl * getDecl()
Definition: Expr.h:1038
bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, CastKind &Kind)
The result type of a method or function.
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration.
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:2904
QualType getObjCConstantStringInterface() const
Definition: ASTContext.h:1515
const SourceManager & SM
Definition: Format.cpp:1293
Expr * getTrueExpr() const
Definition: Expr.h:3283
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1463
edit_iterator edit_end() const
Definition: Commit.h:111
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
void AddFixItHint(const FixItHint &Hint) const
Definition: Diagnostic.h:1080
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:371
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
There is no lifetime qualification on this type.
Definition: Type.h:135
static bool isMethodDeclaredInRootProtocol(Sema &S, const ObjCMethodDecl *M)
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:222
ARCConversionResult
Definition: Sema.h:9546
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor...
SelectorTable & Selectors
Definition: ASTContext.h:514
Kind
bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT, ObjCInterfaceDecl *IDecl)
QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in QT's qualified-id protocol list adopt...
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:4938
Encodes a location in the source.
Sugar for parentheses used when specifying types.
Definition: Type.h:2193
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:5489
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:3810
Represents typeof(type), a GCC extension.
Definition: Type.h:3643
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:5165
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle...
bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr, bool Diagnose=true)
Definition: SemaExpr.cpp:12836
bool isValid() const
Return true if this is a valid SourceLocation object.
const std::string ID
ExprResult ActOnClassMessage(Scope *S, ParsedType Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef< SourceLocation > SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args)
ARCConversionTypeClass
bool isValid() const
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 makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason)
makeUnavailableInSystemHeader - There is an error in the current context.
Definition: Sema.cpp:316
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:733
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
bool isVariadic() const
Definition: DeclObjC.h:418
SmallVectorImpl< Edit >::const_iterator edit_iterator
Definition: Commit.h:109
QualType withConst() const
Definition: Type.h:782
bool isObjCClassOrClassKindOfType() const
Whether the type is Objective-C 'Class' or a __kindof type of an Class type, e.g., __kindof Class <NSCopying>.
Definition: Type.cpp:495
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:178
ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements)
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:537
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
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1663
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2235
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:54
The message is sent to 'super'.
Definition: Sema.h:8035
Specifies that a value-dependent expression should be considered to never be a null pointer constant...
Definition: Expr.h:703
bool isPropertyAccessor() const
Definition: DeclObjC.h:423
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)
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
std::string getAsString() const
Derive the full selector name (e.g.
TypedefNameDecl * getDecl() const
Definition: Type.h:3593
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2804
ObjCProtocolDecl * LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, RedeclarationKind Redecl=NotForRedeclaration)
Find the protocol with the given name, if any.
SourceLocation getBegin() const
QualType getReturnType() const
Definition: DeclObjC.h:330
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6105
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:166
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.
No entity found met the criteria.
Definition: Lookup.h:36
QualType getAttributedType(AttributedType::Kind attrKind, QualType modifiedType, QualType equivalentType)
bool isAscii() const
Definition: Expr.h:1597
bool ObjCIsDesignatedInit
True when this is a method marked as a designated initializer.
Definition: ScopeInfo.h:125
bool isVectorType() const
Definition: Type.h:5778
qual_range quals() const
Definition: Type.h:4874
bool ObjCShouldCallSuper
A flag that is set when parsing a method that must call super's implementation, such as -dealloc...
Definition: ScopeInfo.h:122
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...
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:2823
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:1293
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:3464
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
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:732
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:262
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:70
static Expr * maybeUndoReclaimObject(Expr *e)
Look for an ObjCReclaimReturnedObject cast and destroy it.
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:1605
QualType getPointeeType() const
Definition: Type.h:2238
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:1734
Represents a C11 generic selection.
Definition: Expr.h:4653
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we're in ARC.
Definition: SemaExpr.cpp:5606
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
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
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:2682
QualType getType() const
Definition: Expr.h:127
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition: Expr.h:4993
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T-> getSizeExpr()))
CanQualType CharTy
Definition: ASTContext.h:965
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:8280
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:982
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2435
CharSourceRange getFileRange(SourceManager &SM) const
Definition: Commit.cpp:26
bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R, bool receiverIdOrClass, SmallVectorImpl< ObjCMethodDecl * > &Methods)
ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1215
ObjCMethodDecl * NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]
The Objective-C NSNumber methods used to create NSNumber literals.
Definition: Sema.h:827
StringRef Name
Definition: USRFinder.cpp:123
static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx)
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:259
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:2126
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_RValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:401
static void addFixitForObjCARCConversion(Sema &S, DiagnosticBuilder &DiagB, Sema::CheckedConversionKind CCK, SourceLocation afterLParen, QualType castType, Expr *castExpr, Expr *realCast, const char *bridgeKeyword, const char *CFBridgeName)
bool isInvalidDecl() const
Definition: DeclBase.h:532
bool ObjCIsSecondaryInit
True when this is an initializer method not marked as a designated initializer within a class that ha...
Definition: ScopeInfo.h:134
bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics...
Definition: SemaExpr.cpp:203
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:116
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1466
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
DeclarationName - The name of a declaration.
QualType getObjCProtoType() const
Retrieve the type of the Objective-C Protocol class.
Definition: ASTContext.h:1770
static void checkFoundationAPI(Sema &S, SourceLocation Loc, const ObjCMethodDecl *Method, ArrayRef< Expr * > Args, QualType ReceiverType, bool IsClassObjectCall)
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
bool hasDefinition() const
Determine whether this protocol has a definition.
Definition: DeclObjC.h:2103
U cast(CodeGen::Address addr)
Definition: Address.h:109
id*, id***, void (^*)(),
StringRef getString() const
Definition: Expr.h:1554
Selector getSelector() const
Definition: DeclObjC.h:328
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
detail::InMemoryDirectory::const_iterator E
ObjCMethodFamily getMethodFamily() const
Derive the conventional family of this method.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2087
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:2870
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.
DeclClass * getCorrectionDeclAs() const
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Definition: Expr.cpp:2486
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:5235
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:5662
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:5220
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:134
ObjCMethodDecl * LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false)
LookupInstanceMethodInGlobalPool - Returns the method and warns if there are multiple signatures...
Definition: Sema.h:3535
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:45
bool isKeyword() const
bool isInObjcMethodScope() const
isInObjcMethodScope - Return true if this scope is, or is contained in, an Objective-C method body...
Definition: Scope.h:342
ObjCMethodDecl * getGetterMethodDecl() const
Definition: DeclObjC.h:875
ObjCMethodDecl * lookupMethod(Selector Sel, bool isInstance, bool shallowCategoryLookup=false, bool followSuper=true, const ObjCCategoryDecl *C=nullptr) const
lookupMethod - This method returns an instance/class method by looking in the class, its categories, and its super classes (using a linear search).
Definition: DeclObjC.cpp:662
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3784
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...
SourceManager & getSourceManager() const
Definition: Sema.h:1171
CanQualType UnknownAnyTy
Definition: ASTContext.h:979
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:6042
id, void (^)()
ObjCLiteralKind
Definition: Sema.h:2646
CanQualType UnsignedLongTy
Definition: ASTContext.h:972
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface...
Definition: Type.h:5275
ObjCEncodeExpr, used for @encode in Objective-C.
Definition: ExprObjC.h:355
Selector getSelector(unsigned NumArgs, IdentifierInfo **IIV)
Can create any sort of selector.
CanQualType DependentTy
Definition: ASTContext.h:979
ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr)
BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the '@' prefixed parenthesized expression...
ExprResult HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, Expr *BaseExpr, SourceLocation OpLoc, DeclarationName MemberName, SourceLocation MemberLoc, SourceLocation SuperLoc, QualType SuperType, bool Super)
HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an objective C interface...
Expr * IgnoreParenLValueCasts() LLVM_READONLY
Ignore parentheses and lvalue casts.
Definition: Expr.cpp:2446
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2360
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:90
bool isInvalid() const
void setExprNeedsCleanups(bool SideEffects)
Definition: CleanupInfo.h:29
ObjCPropertyDecl * getExplicitProperty() const
Definition: ExprObjC.h:633
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2468
bool isUsable() const
Definition: Ownership.h:160
void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition: SemaExpr.cpp:315
SourceManager & getSourceManager()
Definition: ASTContext.h:616
static bool isIdentifierBodyChar(char c, const LangOptions &LangOpts)
Returns true if the given character could appear in an identifier.
Definition: Lexer.cpp:1031
static NSAPI::NSClassIdKindKind ClassKindFromLiteralKind(Sema::ObjCLiteralKind LiteralKind)
Maps ObjCLiteralKind to NSClassIdKindKind.
An implicit conversion.
Definition: Sema.h:9124
ObjCInterfaceDecl * getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection=false)
Look for an Objective-C class in the translation unit.
Definition: SemaDecl.cpp:1800
Reading or writing from this object requires a barrier call.
Definition: Type.h:149
No particular method family.
const internal::VariadicDynCastAllOfMatcher< Stmt, CastExpr > castExpr
Matches any cast nodes of Clang's AST.
Definition: ASTMatchers.h:2063
void setObjCNSStringType(QualType T)
Definition: ASTContext.h:1523
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:3838
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but will create a trap if the resul...
Definition: SemaExpr.cpp:859
Describes the sequence of initializations required to initialize a given object or reference with a s...
bool isCARCBridgableType() const
Determine whether the given type T is a "bridgeable" C type.
Definition: Type.cpp:3784
BoundNodesTreeBuilder *const Builder
ExprResult ActOnInstanceMessage(Scope *S, Expr *Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef< SourceLocation > SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args)
bool isObjCObjectPointerType() const
Definition: Type.h:5784
bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, const ObjCMethodDecl *PrevMethod, MethodMatchStrategy strategy=MMS_strict)
MatchTwoMethodDeclarations - Checks if two methods' type match and returns true, or false...
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:505
The parameter type of a method or function.
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1866
CanQualType Char16Ty
Definition: ASTContext.h:969
ArraySizeModifier getSizeModifier() const
Definition: Type.h:2532
static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr, bool &HadTheAttribute, bool warn)
Selector RespondsToSelectorSel
will hold 'respondsToSelector:'
Definition: Sema.h:857
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:317
qual_range quals() const
Definition: Type.h:5342
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:127
static T * getObjCBridgeAttr(const TypedefType *TD)
LookupResultKind getResultKind() const
Definition: Lookup.h:307
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:245
ExprResult BuildInstanceMessageImplicit(Expr *Receiver, QualType ReceiverType, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args)
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1506
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2206
Expr * getRHS() const
Definition: Expr.h:3013
a linked list of methods with the same selector name but different signatures.
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:314
ExprResult ExprError()
Definition: Ownership.h:268
QualType getMessageSendResultType(QualType ReceiverType, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage)
Determine the result of a message send expression based on the type of the receiver, the method expected to receive the message, and the form of the message send.
QualType getSendResultType() const
Determine the type of an expression that sends a message to this function.
Definition: DeclObjC.cpp:1108
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type...
Abstract class common to all of the C++ "named"/"keyword" casts.
Definition: ExprCXX.h:218
TranslationUnitDecl - The top declaration context.
Definition: Decl.h:80
static bool ValidateObjCLiteralInterfaceDecl(Sema &S, ObjCInterfaceDecl *Decl, SourceLocation Loc, Sema::ObjCLiteralKind LiteralKind)
Validates ObjCInterfaceDecl availability.
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:953
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...
QualType getElementType() const
Definition: Type.h:2531
SourceManager & SourceMgr
Definition: Sema.h:308
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:568
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:110
bool isObjCARCBridgableType() const
Determine whether the given type T is a "bridgable" Objective-C type, which is either an Objective-C ...
Definition: Type.cpp:3779
A trivial tuple used to represent a source range.
SourceLocation getLocation() const
Definition: DeclBase.h:407
ASTContext & Context
Definition: Sema.h:305
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, std::unique_ptr< CorrectionCandidateCallback > CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc, ObjCMethodDecl *Method, SourceLocation LParenLoc, SourceLocation RParenLoc, bool WarnMultipleSelectors)
NamedDecl - This represents a decl with a name.
Definition: Decl.h:213
ObjCMethodList * getNext() const
ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod)
Build an ObjC subscript pseudo-object expression, given that that's supported by the runtime...
CanQualType BoolTy
Definition: ASTContext.h:964
static ObjCMethodDecl * getNSNumberFactoryMethod(Sema &S, SourceLocation Loc, QualType NumberType, bool isLiteral=false, SourceRange R=SourceRange())
Retrieve the NSNumber factory method that should be used to create an Objective-C literal for the giv...
bool isObjCIdOrObjectKindOfType(const ASTContext &ctx, const ObjCObjectType *&bound) const
Whether the type is Objective-C 'id' or a __kindof type of an object type, e.g., __kindof NSView * or...
Definition: Type.cpp:469
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2078
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:5548
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:683
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:1904
Describes an entity that is being initialized.
const ObjCObjectPointerType * getAsObjCInterfacePointerType() const
Definition: Type.cpp:1525
SourceLocation getLocStart() const LLVM_READONLY
Definition: Stmt.cpp:257
void setType(QualType newType)
Definition: Decl.h:590
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
Definition: Type.cpp:3526
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration...
Definition: DeclObjC.h:2396
This class handles loading and caching of source files into memory.
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2553
const ObjCObjectType * getSuperClassType() const
Retrieve the superclass type.
Definition: DeclObjC.h:1487
static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg)
const NamedDecl * Result
Definition: USRFinder.cpp:70
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:5928
const ObjCObjectPointerType * getAsObjCQualifiedIdType() const
Definition: Type.cpp:1498
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2368
bool isPointerType() const
Definition: Type.h:5712