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