SemaExprObjC.cpp revision a1b852f8e1bee5ed3604ee483803cef39ce57a20
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
14#include "clang/Sema/SemaInternal.h"
15#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Scope.h"
17#include "clang/Sema/ScopeInfo.h"
18#include "clang/Sema/Initialization.h"
19#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/ExprObjC.h"
23#include "clang/AST/StmtVisitor.h"
24#include "clang/AST/TypeLoc.h"
25#include "llvm/ADT/SmallString.h"
26#include "clang/Lex/Preprocessor.h"
27
28using namespace clang;
29using namespace sema;
30using llvm::makeArrayRef;
31
32ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
33                                        Expr **strings,
34                                        unsigned NumStrings) {
35  StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
36
37  // Most ObjC strings are formed out of a single piece.  However, we *can*
38  // have strings formed out of multiple @ strings with multiple pptokens in
39  // each one, e.g. @"foo" "bar" @"baz" "qux"   which need to be turned into one
40  // StringLiteral for ObjCStringLiteral to hold onto.
41  StringLiteral *S = Strings[0];
42
43  // If we have a multi-part string, merge it all together.
44  if (NumStrings != 1) {
45    // Concatenate objc strings.
46    llvm::SmallString<128> StrBuf;
47    SmallVector<SourceLocation, 8> StrLocs;
48
49    for (unsigned i = 0; i != NumStrings; ++i) {
50      S = Strings[i];
51
52      // ObjC strings can't be wide or UTF.
53      if (!S->isAscii()) {
54        Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
55          << S->getSourceRange();
56        return true;
57      }
58
59      // Append the string.
60      StrBuf += S->getString();
61
62      // Get the locations of the string tokens.
63      StrLocs.append(S->tokloc_begin(), S->tokloc_end());
64    }
65
66    // Create the aggregate string with the appropriate content and location
67    // information.
68    S = StringLiteral::Create(Context, StrBuf,
69                              StringLiteral::Ascii, /*Pascal=*/false,
70                              Context.getPointerType(Context.CharTy),
71                              &StrLocs[0], StrLocs.size());
72  }
73
74  // Verify that this composite string is acceptable for ObjC strings.
75  if (CheckObjCString(S))
76    return true;
77
78  // Initialize the constant string interface lazily. This assumes
79  // the NSString interface is seen in this translation unit. Note: We
80  // don't use NSConstantString, since the runtime team considers this
81  // interface private (even though it appears in the header files).
82  QualType Ty = Context.getObjCConstantStringInterface();
83  if (!Ty.isNull()) {
84    Ty = Context.getObjCObjectPointerType(Ty);
85  } else if (getLangOptions().NoConstantCFStrings) {
86    IdentifierInfo *NSIdent=0;
87    std::string StringClass(getLangOptions().ObjCConstantStringClass);
88
89    if (StringClass.empty())
90      NSIdent = &Context.Idents.get("NSConstantString");
91    else
92      NSIdent = &Context.Idents.get(StringClass);
93
94    NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
95                                     LookupOrdinaryName);
96    if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
97      Context.setObjCConstantStringInterface(StrIF);
98      Ty = Context.getObjCConstantStringInterface();
99      Ty = Context.getObjCObjectPointerType(Ty);
100    } else {
101      // If there is no NSConstantString interface defined then treat this
102      // as error and recover from it.
103      Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
104        << S->getSourceRange();
105      Ty = Context.getObjCIdType();
106    }
107  } else {
108    IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
109    NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
110                                     LookupOrdinaryName);
111    if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
112      Context.setObjCConstantStringInterface(StrIF);
113      Ty = Context.getObjCConstantStringInterface();
114      Ty = Context.getObjCObjectPointerType(Ty);
115    } else {
116      // If there is no NSString interface defined then treat constant
117      // strings as untyped objects and let the runtime figure it out later.
118      Ty = Context.getObjCIdType();
119    }
120  }
121
122  return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
123}
124
125ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
126                                      TypeSourceInfo *EncodedTypeInfo,
127                                      SourceLocation RParenLoc) {
128  QualType EncodedType = EncodedTypeInfo->getType();
129  QualType StrTy;
130  if (EncodedType->isDependentType())
131    StrTy = Context.DependentTy;
132  else {
133    if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
134        !EncodedType->isVoidType()) // void is handled too.
135      if (RequireCompleteType(AtLoc, EncodedType,
136                         PDiag(diag::err_incomplete_type_objc_at_encode)
137                             << EncodedTypeInfo->getTypeLoc().getSourceRange()))
138        return ExprError();
139
140    std::string Str;
141    Context.getObjCEncodingForType(EncodedType, Str);
142
143    // The type of @encode is the same as the type of the corresponding string,
144    // which is an array type.
145    StrTy = Context.CharTy;
146    // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
147    if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
148      StrTy.addConst();
149    StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
150                                         ArrayType::Normal, 0);
151  }
152
153  return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
154}
155
156ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
157                                           SourceLocation EncodeLoc,
158                                           SourceLocation LParenLoc,
159                                           ParsedType ty,
160                                           SourceLocation RParenLoc) {
161  // FIXME: Preserve type source info ?
162  TypeSourceInfo *TInfo;
163  QualType EncodedType = GetTypeFromParser(ty, &TInfo);
164  if (!TInfo)
165    TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
166                                             PP.getLocForEndOfToken(LParenLoc));
167
168  return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
169}
170
171ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
172                                             SourceLocation AtLoc,
173                                             SourceLocation SelLoc,
174                                             SourceLocation LParenLoc,
175                                             SourceLocation RParenLoc) {
176  ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
177                             SourceRange(LParenLoc, RParenLoc), false, false);
178  if (!Method)
179    Method = LookupFactoryMethodInGlobalPool(Sel,
180                                          SourceRange(LParenLoc, RParenLoc));
181  if (!Method)
182    Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
183
184  if (!Method ||
185      Method->getImplementationControl() != ObjCMethodDecl::Optional) {
186    llvm::DenseMap<Selector, SourceLocation>::iterator Pos
187      = ReferencedSelectors.find(Sel);
188    if (Pos == ReferencedSelectors.end())
189      ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
190  }
191
192  // In ARC, forbid the user from using @selector for
193  // retain/release/autorelease/dealloc/retainCount.
194  if (getLangOptions().ObjCAutoRefCount) {
195    switch (Sel.getMethodFamily()) {
196    case OMF_retain:
197    case OMF_release:
198    case OMF_autorelease:
199    case OMF_retainCount:
200    case OMF_dealloc:
201      Diag(AtLoc, diag::err_arc_illegal_selector) <<
202        Sel << SourceRange(LParenLoc, RParenLoc);
203      break;
204
205    case OMF_None:
206    case OMF_alloc:
207    case OMF_copy:
208    case OMF_finalize:
209    case OMF_init:
210    case OMF_mutableCopy:
211    case OMF_new:
212    case OMF_self:
213    case OMF_performSelector:
214      break;
215    }
216  }
217  QualType Ty = Context.getObjCSelType();
218  return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
219}
220
221ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
222                                             SourceLocation AtLoc,
223                                             SourceLocation ProtoLoc,
224                                             SourceLocation LParenLoc,
225                                             SourceLocation RParenLoc) {
226  ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
227  if (!PDecl) {
228    Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
229    return true;
230  }
231
232  QualType Ty = Context.getObjCProtoType();
233  if (Ty.isNull())
234    return true;
235  Ty = Context.getObjCObjectPointerType(Ty);
236  return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
237}
238
239/// Try to capture an implicit reference to 'self'.
240ObjCMethodDecl *Sema::tryCaptureObjCSelf() {
241  // Ignore block scopes: we can capture through them.
242  DeclContext *DC = CurContext;
243  while (true) {
244    if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
245    else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
246    else break;
247  }
248
249  // If we're not in an ObjC method, error out.  Note that, unlike the
250  // C++ case, we don't require an instance method --- class methods
251  // still have a 'self', and we really do still need to capture it!
252  ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
253  if (!method)
254    return 0;
255
256  ImplicitParamDecl *self = method->getSelfDecl();
257  assert(self && "capturing 'self' in non-definition?");
258
259  // Mark that we're closing on 'this' in all the block scopes, if applicable.
260  for (unsigned idx = FunctionScopes.size() - 1;
261       isa<BlockScopeInfo>(FunctionScopes[idx]);
262       --idx) {
263    BlockScopeInfo *blockScope = cast<BlockScopeInfo>(FunctionScopes[idx]);
264    unsigned &captureIndex = blockScope->CaptureMap[self];
265    if (captureIndex) break;
266
267    bool nested = isa<BlockScopeInfo>(FunctionScopes[idx-1]);
268    blockScope->Captures.push_back(
269              BlockDecl::Capture(self, /*byref*/ false, nested, /*copy*/ 0));
270    captureIndex = blockScope->Captures.size(); // +1
271  }
272
273  return method;
274}
275
276static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
277  if (T == Context.getObjCInstanceType())
278    return Context.getObjCIdType();
279
280  return T;
281}
282
283QualType Sema::getMessageSendResultType(QualType ReceiverType,
284                                        ObjCMethodDecl *Method,
285                                    bool isClassMessage, bool isSuperMessage) {
286  assert(Method && "Must have a method");
287  if (!Method->hasRelatedResultType())
288    return Method->getSendResultType();
289
290  // If a method has a related return type:
291  //   - if the method found is an instance method, but the message send
292  //     was a class message send, T is the declared return type of the method
293  //     found
294  if (Method->isInstanceMethod() && isClassMessage)
295    return stripObjCInstanceType(Context, Method->getSendResultType());
296
297  //   - if the receiver is super, T is a pointer to the class of the
298  //     enclosing method definition
299  if (isSuperMessage) {
300    if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
301      if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
302        return Context.getObjCObjectPointerType(
303                                        Context.getObjCInterfaceType(Class));
304  }
305
306  //   - if the receiver is the name of a class U, T is a pointer to U
307  if (ReceiverType->getAs<ObjCInterfaceType>() ||
308      ReceiverType->isObjCQualifiedInterfaceType())
309    return Context.getObjCObjectPointerType(ReceiverType);
310  //   - if the receiver is of type Class or qualified Class type,
311  //     T is the declared return type of the method.
312  if (ReceiverType->isObjCClassType() ||
313      ReceiverType->isObjCQualifiedClassType())
314    return stripObjCInstanceType(Context, Method->getSendResultType());
315
316  //   - if the receiver is id, qualified id, Class, or qualified Class, T
317  //     is the receiver type, otherwise
318  //   - T is the type of the receiver expression.
319  return ReceiverType;
320}
321
322void Sema::EmitRelatedResultTypeNote(const Expr *E) {
323  E = E->IgnoreParenImpCasts();
324  const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
325  if (!MsgSend)
326    return;
327
328  const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
329  if (!Method)
330    return;
331
332  if (!Method->hasRelatedResultType())
333    return;
334
335  if (Context.hasSameUnqualifiedType(Method->getResultType()
336                                                        .getNonReferenceType(),
337                                     MsgSend->getType()))
338    return;
339
340  if (!Context.hasSameUnqualifiedType(Method->getResultType(),
341                                      Context.getObjCInstanceType()))
342    return;
343
344  Diag(Method->getLocation(), diag::note_related_result_type_inferred)
345    << Method->isInstanceMethod() << Method->getSelector()
346    << MsgSend->getType();
347}
348
349bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
350                                     Expr **Args, unsigned NumArgs,
351                                     Selector Sel, ObjCMethodDecl *Method,
352                                     bool isClassMessage, bool isSuperMessage,
353                                     SourceLocation lbrac, SourceLocation rbrac,
354                                     QualType &ReturnType, ExprValueKind &VK) {
355  if (!Method) {
356    // Apply default argument promotion as for (C99 6.5.2.2p6).
357    for (unsigned i = 0; i != NumArgs; i++) {
358      if (Args[i]->isTypeDependent())
359        continue;
360
361      ExprResult Result = DefaultArgumentPromotion(Args[i]);
362      if (Result.isInvalid())
363        return true;
364      Args[i] = Result.take();
365    }
366
367    unsigned DiagID;
368    if (getLangOptions().ObjCAutoRefCount)
369      DiagID = diag::err_arc_method_not_found;
370    else
371      DiagID = isClassMessage ? diag::warn_class_method_not_found
372                              : diag::warn_inst_method_not_found;
373    if (!getLangOptions().DebuggerSupport)
374      Diag(lbrac, DiagID)
375        << Sel << isClassMessage << SourceRange(lbrac, rbrac);
376
377    // In debuggers, we want to use __unknown_anytype for these
378    // results so that clients can cast them.
379    if (getLangOptions().DebuggerSupport) {
380      ReturnType = Context.UnknownAnyTy;
381    } else {
382      ReturnType = Context.getObjCIdType();
383    }
384    VK = VK_RValue;
385    return false;
386  }
387
388  ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
389                                        isSuperMessage);
390  VK = Expr::getValueKindForType(Method->getResultType());
391
392  unsigned NumNamedArgs = Sel.getNumArgs();
393  // Method might have more arguments than selector indicates. This is due
394  // to addition of c-style arguments in method.
395  if (Method->param_size() > Sel.getNumArgs())
396    NumNamedArgs = Method->param_size();
397  // FIXME. This need be cleaned up.
398  if (NumArgs < NumNamedArgs) {
399    Diag(lbrac, diag::err_typecheck_call_too_few_args)
400      << 2 << NumNamedArgs << NumArgs;
401    return false;
402  }
403
404  bool IsError = false;
405  for (unsigned i = 0; i < NumNamedArgs; i++) {
406    // We can't do any type-checking on a type-dependent argument.
407    if (Args[i]->isTypeDependent())
408      continue;
409
410    Expr *argExpr = Args[i];
411
412    ParmVarDecl *param = Method->param_begin()[i];
413    assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
414
415    // Strip the unbridged-cast placeholder expression off unless it's
416    // a consumed argument.
417    if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
418        !param->hasAttr<CFConsumedAttr>())
419      argExpr = stripARCUnbridgedCast(argExpr);
420
421    if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
422                            param->getType(),
423                            PDiag(diag::err_call_incomplete_argument)
424                              << argExpr->getSourceRange()))
425      return true;
426
427    InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
428                                                                      param);
429    ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
430    if (ArgE.isInvalid())
431      IsError = true;
432    else
433      Args[i] = ArgE.takeAs<Expr>();
434  }
435
436  // Promote additional arguments to variadic methods.
437  if (Method->isVariadic()) {
438    for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
439      if (Args[i]->isTypeDependent())
440        continue;
441
442      ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
443      IsError |= Arg.isInvalid();
444      Args[i] = Arg.take();
445    }
446  } else {
447    // Check for extra arguments to non-variadic methods.
448    if (NumArgs != NumNamedArgs) {
449      Diag(Args[NumNamedArgs]->getLocStart(),
450           diag::err_typecheck_call_too_many_args)
451        << 2 /*method*/ << NumNamedArgs << NumArgs
452        << Method->getSourceRange()
453        << SourceRange(Args[NumNamedArgs]->getLocStart(),
454                       Args[NumArgs-1]->getLocEnd());
455    }
456  }
457  // diagnose nonnull arguments.
458  for (specific_attr_iterator<NonNullAttr>
459       i = Method->specific_attr_begin<NonNullAttr>(),
460       e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
461    CheckNonNullArguments(*i, Args, lbrac);
462  }
463
464  DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
465  return IsError;
466}
467
468bool Sema::isSelfExpr(Expr *receiver) {
469  // 'self' is objc 'self' in an objc method only.
470  DeclContext *DC = CurContext;
471  while (isa<BlockDecl>(DC))
472    DC = DC->getParent();
473  if (DC && !isa<ObjCMethodDecl>(DC))
474    return false;
475  receiver = receiver->IgnoreParenLValueCasts();
476  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
477    if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
478      return true;
479  return false;
480}
481
482// Helper method for ActOnClassMethod/ActOnInstanceMethod.
483// Will search "local" class/category implementations for a method decl.
484// If failed, then we search in class's root for an instance method.
485// Returns 0 if no method is found.
486ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
487                                          ObjCInterfaceDecl *ClassDecl) {
488  ObjCMethodDecl *Method = 0;
489  // lookup in class and all superclasses
490  while (ClassDecl && !Method) {
491    if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
492      Method = ImpDecl->getClassMethod(Sel);
493
494    // Look through local category implementations associated with the class.
495    if (!Method)
496      Method = ClassDecl->getCategoryClassMethod(Sel);
497
498    // Before we give up, check if the selector is an instance method.
499    // But only in the root. This matches gcc's behaviour and what the
500    // runtime expects.
501    if (!Method && !ClassDecl->getSuperClass()) {
502      Method = ClassDecl->lookupInstanceMethod(Sel);
503      // Look through local category implementations associated
504      // with the root class.
505      if (!Method)
506        Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
507    }
508
509    ClassDecl = ClassDecl->getSuperClass();
510  }
511  return Method;
512}
513
514ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
515                                              ObjCInterfaceDecl *ClassDecl) {
516  ObjCMethodDecl *Method = 0;
517  while (ClassDecl && !Method) {
518    // If we have implementations in scope, check "private" methods.
519    if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
520      Method = ImpDecl->getInstanceMethod(Sel);
521
522    // Look through local category implementations associated with the class.
523    if (!Method)
524      Method = ClassDecl->getCategoryInstanceMethod(Sel);
525    ClassDecl = ClassDecl->getSuperClass();
526  }
527  return Method;
528}
529
530/// LookupMethodInType - Look up a method in an ObjCObjectType.
531ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
532                                               bool isInstance) {
533  const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
534  if (ObjCInterfaceDecl *iface = objType->getInterface()) {
535    // Look it up in the main interface (and categories, etc.)
536    if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
537      return method;
538
539    // Okay, look for "private" methods declared in any
540    // @implementations we've seen.
541    if (isInstance) {
542      if (ObjCMethodDecl *method = LookupPrivateInstanceMethod(sel, iface))
543        return method;
544    } else {
545      if (ObjCMethodDecl *method = LookupPrivateClassMethod(sel, iface))
546        return method;
547    }
548  }
549
550  // Check qualifiers.
551  for (ObjCObjectType::qual_iterator
552         i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i)
553    if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance))
554      return method;
555
556  return 0;
557}
558
559/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
560/// list of a qualified objective pointer type.
561ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
562                                              const ObjCObjectPointerType *OPT,
563                                              bool Instance)
564{
565  ObjCMethodDecl *MD = 0;
566  for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
567       E = OPT->qual_end(); I != E; ++I) {
568    ObjCProtocolDecl *PROTO = (*I);
569    if ((MD = PROTO->lookupMethod(Sel, Instance))) {
570      return MD;
571    }
572  }
573  return 0;
574}
575
576/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
577/// objective C interface.  This is a property reference expression.
578ExprResult Sema::
579HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
580                          Expr *BaseExpr, SourceLocation OpLoc,
581                          DeclarationName MemberName,
582                          SourceLocation MemberLoc,
583                          SourceLocation SuperLoc, QualType SuperType,
584                          bool Super) {
585  const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
586  ObjCInterfaceDecl *IFace = IFaceT->getDecl();
587
588  if (MemberName.getNameKind() != DeclarationName::Identifier) {
589    Diag(MemberLoc, diag::err_invalid_property_name)
590      << MemberName << QualType(OPT, 0);
591    return ExprError();
592  }
593
594  IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
595
596  if (IFace->isForwardDecl()) {
597    Diag(MemberLoc, diag::err_property_not_found_forward_class)
598         << MemberName << QualType(OPT, 0);
599    Diag(IFace->getLocation(), diag::note_forward_class);
600    return ExprError();
601  }
602  // Search for a declared property first.
603  if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
604    // Check whether we can reference this property.
605    if (DiagnoseUseOfDecl(PD, MemberLoc))
606      return ExprError();
607
608    if (Super)
609      return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
610                                                     VK_LValue, OK_ObjCProperty,
611                                                     MemberLoc,
612                                                     SuperLoc, SuperType));
613    else
614      return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
615                                                     VK_LValue, OK_ObjCProperty,
616                                                     MemberLoc, BaseExpr));
617  }
618  // Check protocols on qualified interfaces.
619  for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
620       E = OPT->qual_end(); I != E; ++I)
621    if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
622      // Check whether we can reference this property.
623      if (DiagnoseUseOfDecl(PD, MemberLoc))
624        return ExprError();
625
626      if (Super)
627        return Owned(new (Context) ObjCPropertyRefExpr(PD,
628                                                       Context.PseudoObjectTy,
629                                                       VK_LValue,
630                                                       OK_ObjCProperty,
631                                                       MemberLoc,
632                                                       SuperLoc, SuperType));
633      else
634        return Owned(new (Context) ObjCPropertyRefExpr(PD,
635                                                       Context.PseudoObjectTy,
636                                                       VK_LValue,
637                                                       OK_ObjCProperty,
638                                                       MemberLoc,
639                                                       BaseExpr));
640    }
641  // If that failed, look for an "implicit" property by seeing if the nullary
642  // selector is implemented.
643
644  // FIXME: The logic for looking up nullary and unary selectors should be
645  // shared with the code in ActOnInstanceMessage.
646
647  Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
648  ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
649
650  // May be founf in property's qualified list.
651  if (!Getter)
652    Getter = LookupMethodInQualifiedType(Sel, OPT, true);
653
654  // If this reference is in an @implementation, check for 'private' methods.
655  if (!Getter)
656    Getter = IFace->lookupPrivateMethod(Sel);
657
658  // Look through local category implementations associated with the class.
659  if (!Getter)
660    Getter = IFace->getCategoryInstanceMethod(Sel);
661  if (Getter) {
662    // Check if we can reference this property.
663    if (DiagnoseUseOfDecl(Getter, MemberLoc))
664      return ExprError();
665  }
666  // If we found a getter then this may be a valid dot-reference, we
667  // will look for the matching setter, in case it is needed.
668  Selector SetterSel =
669    SelectorTable::constructSetterName(PP.getIdentifierTable(),
670                                       PP.getSelectorTable(), Member);
671  ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
672
673  // May be founf in property's qualified list.
674  if (!Setter)
675    Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
676
677  if (!Setter) {
678    // If this reference is in an @implementation, also check for 'private'
679    // methods.
680    Setter = IFace->lookupPrivateMethod(SetterSel);
681  }
682  // Look through local category implementations associated with the class.
683  if (!Setter)
684    Setter = IFace->getCategoryInstanceMethod(SetterSel);
685
686  if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
687    return ExprError();
688
689  if (Getter || Setter) {
690    if (Super)
691      return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
692                                                     Context.PseudoObjectTy,
693                                                     VK_LValue, OK_ObjCProperty,
694                                                     MemberLoc,
695                                                     SuperLoc, SuperType));
696    else
697      return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
698                                                     Context.PseudoObjectTy,
699                                                     VK_LValue, OK_ObjCProperty,
700                                                     MemberLoc, BaseExpr));
701
702  }
703
704  // Attempt to correct for typos in property names.
705  TypoCorrection Corrected = CorrectTypo(
706      DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
707      NULL, IFace, false, CTC_NoKeywords, OPT);
708  if (ObjCPropertyDecl *Property =
709      Corrected.getCorrectionDeclAs<ObjCPropertyDecl>()) {
710    DeclarationName TypoResult = Corrected.getCorrection();
711    Diag(MemberLoc, diag::err_property_not_found_suggest)
712      << MemberName << QualType(OPT, 0) << TypoResult
713      << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
714    Diag(Property->getLocation(), diag::note_previous_decl)
715      << Property->getDeclName();
716    return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
717                                     TypoResult, MemberLoc,
718                                     SuperLoc, SuperType, Super);
719  }
720  ObjCInterfaceDecl *ClassDeclared;
721  if (ObjCIvarDecl *Ivar =
722      IFace->lookupInstanceVariable(Member, ClassDeclared)) {
723    QualType T = Ivar->getType();
724    if (const ObjCObjectPointerType * OBJPT =
725        T->getAsObjCInterfacePointerType()) {
726      const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
727      if (ObjCInterfaceDecl *IFace = IFaceT->getDecl())
728        if (IFace->isForwardDecl()) {
729          Diag(MemberLoc, diag::err_property_not_as_forward_class)
730          << MemberName << IFace;
731          Diag(IFace->getLocation(), diag::note_forward_class);
732          return ExprError();
733        }
734    }
735    Diag(MemberLoc,
736         diag::err_ivar_access_using_property_syntax_suggest)
737    << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
738    << FixItHint::CreateReplacement(OpLoc, "->");
739    return ExprError();
740  }
741
742  Diag(MemberLoc, diag::err_property_not_found)
743    << MemberName << QualType(OPT, 0);
744  if (Setter)
745    Diag(Setter->getLocation(), diag::note_getter_unavailable)
746          << MemberName << BaseExpr->getSourceRange();
747  return ExprError();
748}
749
750
751
752ExprResult Sema::
753ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
754                          IdentifierInfo &propertyName,
755                          SourceLocation receiverNameLoc,
756                          SourceLocation propertyNameLoc) {
757
758  IdentifierInfo *receiverNamePtr = &receiverName;
759  ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
760                                                  receiverNameLoc);
761
762  bool IsSuper = false;
763  if (IFace == 0) {
764    // If the "receiver" is 'super' in a method, handle it as an expression-like
765    // property reference.
766    if (receiverNamePtr->isStr("super")) {
767      IsSuper = true;
768
769      if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf()) {
770        if (CurMethod->isInstanceMethod()) {
771          QualType T =
772            Context.getObjCInterfaceType(CurMethod->getClassInterface());
773          T = Context.getObjCObjectPointerType(T);
774
775          return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
776                                           /*BaseExpr*/0,
777                                           SourceLocation()/*OpLoc*/,
778                                           &propertyName,
779                                           propertyNameLoc,
780                                           receiverNameLoc, T, true);
781        }
782
783        // Otherwise, if this is a class method, try dispatching to our
784        // superclass.
785        IFace = CurMethod->getClassInterface()->getSuperClass();
786      }
787    }
788
789    if (IFace == 0) {
790      Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
791      return ExprError();
792    }
793  }
794
795  // Search for a declared property first.
796  Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
797  ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
798
799  // If this reference is in an @implementation, check for 'private' methods.
800  if (!Getter)
801    if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
802      if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
803        if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
804          Getter = ImpDecl->getClassMethod(Sel);
805
806  if (Getter) {
807    // FIXME: refactor/share with ActOnMemberReference().
808    // Check if we can reference this property.
809    if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
810      return ExprError();
811  }
812
813  // Look for the matching setter, in case it is needed.
814  Selector SetterSel =
815    SelectorTable::constructSetterName(PP.getIdentifierTable(),
816                                       PP.getSelectorTable(), &propertyName);
817
818  ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
819  if (!Setter) {
820    // If this reference is in an @implementation, also check for 'private'
821    // methods.
822    if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
823      if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
824        if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
825          Setter = ImpDecl->getClassMethod(SetterSel);
826  }
827  // Look through local category implementations associated with the class.
828  if (!Setter)
829    Setter = IFace->getCategoryClassMethod(SetterSel);
830
831  if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
832    return ExprError();
833
834  if (Getter || Setter) {
835    if (IsSuper)
836    return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
837                                                   Context.PseudoObjectTy,
838                                                   VK_LValue, OK_ObjCProperty,
839                                                   propertyNameLoc,
840                                                   receiverNameLoc,
841                                          Context.getObjCInterfaceType(IFace)));
842
843    return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
844                                                   Context.PseudoObjectTy,
845                                                   VK_LValue, OK_ObjCProperty,
846                                                   propertyNameLoc,
847                                                   receiverNameLoc, IFace));
848  }
849  return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
850                     << &propertyName << Context.getObjCInterfaceType(IFace));
851}
852
853Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
854                                               IdentifierInfo *Name,
855                                               SourceLocation NameLoc,
856                                               bool IsSuper,
857                                               bool HasTrailingDot,
858                                               ParsedType &ReceiverType) {
859  ReceiverType = ParsedType();
860
861  // If the identifier is "super" and there is no trailing dot, we're
862  // messaging super. If the identifier is "super" and there is a
863  // trailing dot, it's an instance message.
864  if (IsSuper && S->isInObjcMethodScope())
865    return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
866
867  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
868  LookupName(Result, S);
869
870  switch (Result.getResultKind()) {
871  case LookupResult::NotFound:
872    // Normal name lookup didn't find anything. If we're in an
873    // Objective-C method, look for ivars. If we find one, we're done!
874    // FIXME: This is a hack. Ivar lookup should be part of normal
875    // lookup.
876    if (ObjCMethodDecl *Method = getCurMethodDecl()) {
877      ObjCInterfaceDecl *ClassDeclared;
878      if (Method->getClassInterface()->lookupInstanceVariable(Name,
879                                                              ClassDeclared))
880        return ObjCInstanceMessage;
881    }
882
883    // Break out; we'll perform typo correction below.
884    break;
885
886  case LookupResult::NotFoundInCurrentInstantiation:
887  case LookupResult::FoundOverloaded:
888  case LookupResult::FoundUnresolvedValue:
889  case LookupResult::Ambiguous:
890    Result.suppressDiagnostics();
891    return ObjCInstanceMessage;
892
893  case LookupResult::Found: {
894    // If the identifier is a class or not, and there is a trailing dot,
895    // it's an instance message.
896    if (HasTrailingDot)
897      return ObjCInstanceMessage;
898    // We found something. If it's a type, then we have a class
899    // message. Otherwise, it's an instance message.
900    NamedDecl *ND = Result.getFoundDecl();
901    QualType T;
902    if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
903      T = Context.getObjCInterfaceType(Class);
904    else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
905      T = Context.getTypeDeclType(Type);
906    else
907      return ObjCInstanceMessage;
908
909    //  We have a class message, and T is the type we're
910    //  messaging. Build source-location information for it.
911    TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
912    ReceiverType = CreateParsedType(T, TSInfo);
913    return ObjCClassMessage;
914  }
915  }
916
917  // Determine our typo-correction context.
918  CorrectTypoContext CTC = CTC_Expression;
919  if (ObjCMethodDecl *Method = getCurMethodDecl())
920    if (Method->getClassInterface() &&
921        Method->getClassInterface()->getSuperClass())
922      CTC = CTC_ObjCMessageReceiver;
923
924  if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
925                                             Result.getLookupKind(), S, NULL,
926                                             NULL, false, CTC)) {
927    if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
928      // If we found a declaration, correct when it refers to an Objective-C
929      // class.
930      if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
931        Diag(NameLoc, diag::err_unknown_receiver_suggest)
932          << Name << Corrected.getCorrection()
933          << FixItHint::CreateReplacement(SourceRange(NameLoc),
934                                          ND->getNameAsString());
935        Diag(ND->getLocation(), diag::note_previous_decl)
936          << Corrected.getCorrection();
937
938        QualType T = Context.getObjCInterfaceType(Class);
939        TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
940        ReceiverType = CreateParsedType(T, TSInfo);
941        return ObjCClassMessage;
942      }
943    } else if (Corrected.isKeyword() &&
944               Corrected.getCorrectionAsIdentifierInfo()->isStr("super")) {
945      // If we've found the keyword "super", this is a send to super.
946      Diag(NameLoc, diag::err_unknown_receiver_suggest)
947        << Name << Corrected.getCorrection()
948        << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
949      return ObjCSuperMessage;
950    }
951  }
952
953  // Fall back: let the parser try to parse it as an instance message.
954  return ObjCInstanceMessage;
955}
956
957ExprResult Sema::ActOnSuperMessage(Scope *S,
958                                   SourceLocation SuperLoc,
959                                   Selector Sel,
960                                   SourceLocation LBracLoc,
961                                   ArrayRef<SourceLocation> SelectorLocs,
962                                   SourceLocation RBracLoc,
963                                   MultiExprArg Args) {
964  // Determine whether we are inside a method or not.
965  ObjCMethodDecl *Method = tryCaptureObjCSelf();
966  if (!Method) {
967    Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
968    return ExprError();
969  }
970
971  ObjCInterfaceDecl *Class = Method->getClassInterface();
972  if (!Class) {
973    Diag(SuperLoc, diag::error_no_super_class_message)
974      << Method->getDeclName();
975    return ExprError();
976  }
977
978  ObjCInterfaceDecl *Super = Class->getSuperClass();
979  if (!Super) {
980    // The current class does not have a superclass.
981    Diag(SuperLoc, diag::error_root_class_cannot_use_super)
982      << Class->getIdentifier();
983    return ExprError();
984  }
985
986  // We are in a method whose class has a superclass, so 'super'
987  // is acting as a keyword.
988  if (Method->isInstanceMethod()) {
989    if (Sel.getMethodFamily() == OMF_dealloc)
990      ObjCShouldCallSuperDealloc = false;
991    if (Sel.getMethodFamily() == OMF_finalize)
992      ObjCShouldCallSuperFinalize = false;
993
994    // Since we are in an instance method, this is an instance
995    // message to the superclass instance.
996    QualType SuperTy = Context.getObjCInterfaceType(Super);
997    SuperTy = Context.getObjCObjectPointerType(SuperTy);
998    return BuildInstanceMessage(0, SuperTy, SuperLoc,
999                                Sel, /*Method=*/0,
1000                                LBracLoc, SelectorLocs, RBracLoc, move(Args));
1001  }
1002
1003  // Since we are in a class method, this is a class message to
1004  // the superclass.
1005  return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1006                           Context.getObjCInterfaceType(Super),
1007                           SuperLoc, Sel, /*Method=*/0,
1008                           LBracLoc, SelectorLocs, RBracLoc, move(Args));
1009}
1010
1011/// \brief Build an Objective-C class message expression.
1012///
1013/// This routine takes care of both normal class messages and
1014/// class messages to the superclass.
1015///
1016/// \param ReceiverTypeInfo Type source information that describes the
1017/// receiver of this message. This may be NULL, in which case we are
1018/// sending to the superclass and \p SuperLoc must be a valid source
1019/// location.
1020
1021/// \param ReceiverType The type of the object receiving the
1022/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1023/// type as that refers to. For a superclass send, this is the type of
1024/// the superclass.
1025///
1026/// \param SuperLoc The location of the "super" keyword in a
1027/// superclass message.
1028///
1029/// \param Sel The selector to which the message is being sent.
1030///
1031/// \param Method The method that this class message is invoking, if
1032/// already known.
1033///
1034/// \param LBracLoc The location of the opening square bracket ']'.
1035///
1036/// \param RBrac The location of the closing square bracket ']'.
1037///
1038/// \param Args The message arguments.
1039ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
1040                                   QualType ReceiverType,
1041                                   SourceLocation SuperLoc,
1042                                   Selector Sel,
1043                                   ObjCMethodDecl *Method,
1044                                   SourceLocation LBracLoc,
1045                                   ArrayRef<SourceLocation> SelectorLocs,
1046                                   SourceLocation RBracLoc,
1047                                   MultiExprArg ArgsIn) {
1048  SourceLocation Loc = SuperLoc.isValid()? SuperLoc
1049    : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
1050  if (LBracLoc.isInvalid()) {
1051    Diag(Loc, diag::err_missing_open_square_message_send)
1052      << FixItHint::CreateInsertion(Loc, "[");
1053    LBracLoc = Loc;
1054  }
1055
1056  if (ReceiverType->isDependentType()) {
1057    // If the receiver type is dependent, we can't type-check anything
1058    // at this point. Build a dependent expression.
1059    unsigned NumArgs = ArgsIn.size();
1060    Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1061    assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1062    return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1063                                         VK_RValue, LBracLoc, ReceiverTypeInfo,
1064                                         Sel, SelectorLocs, /*Method=*/0,
1065                                         makeArrayRef(Args, NumArgs),RBracLoc));
1066  }
1067
1068  // Find the class to which we are sending this message.
1069  ObjCInterfaceDecl *Class = 0;
1070  const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1071  if (!ClassType || !(Class = ClassType->getInterface())) {
1072    Diag(Loc, diag::err_invalid_receiver_class_message)
1073      << ReceiverType;
1074    return ExprError();
1075  }
1076  assert(Class && "We don't know which class we're messaging?");
1077  // objc++ diagnoses during typename annotation.
1078  if (!getLangOptions().CPlusPlus)
1079    (void)DiagnoseUseOfDecl(Class, Loc);
1080  // Find the method we are messaging.
1081  if (!Method) {
1082    if (Class->isForwardDecl()) {
1083      if (getLangOptions().ObjCAutoRefCount) {
1084        Diag(Loc, diag::err_arc_receiver_forward_class) << ReceiverType;
1085      } else {
1086        Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
1087      }
1088
1089      // A forward class used in messaging is treated as a 'Class'
1090      Method = LookupFactoryMethodInGlobalPool(Sel,
1091                                               SourceRange(LBracLoc, RBracLoc));
1092      if (Method && !getLangOptions().ObjCAutoRefCount)
1093        Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1094          << Method->getDeclName();
1095    }
1096    if (!Method)
1097      Method = Class->lookupClassMethod(Sel);
1098
1099    // If we have an implementation in scope, check "private" methods.
1100    if (!Method)
1101      Method = LookupPrivateClassMethod(Sel, Class);
1102
1103    if (Method && DiagnoseUseOfDecl(Method, Loc))
1104      return ExprError();
1105  }
1106
1107  // Check the argument types and determine the result type.
1108  QualType ReturnType;
1109  ExprValueKind VK = VK_RValue;
1110
1111  unsigned NumArgs = ArgsIn.size();
1112  Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1113  if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1114                                SuperLoc.isValid(), LBracLoc, RBracLoc,
1115                                ReturnType, VK))
1116    return ExprError();
1117
1118  if (Method && !Method->getResultType()->isVoidType() &&
1119      RequireCompleteType(LBracLoc, Method->getResultType(),
1120                          diag::err_illegal_message_expr_incomplete_type))
1121    return ExprError();
1122
1123  // Construct the appropriate ObjCMessageExpr.
1124  Expr *Result;
1125  if (SuperLoc.isValid())
1126    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1127                                     SuperLoc, /*IsInstanceSuper=*/false,
1128                                     ReceiverType, Sel, SelectorLocs,
1129                                     Method, makeArrayRef(Args, NumArgs),
1130                                     RBracLoc);
1131  else
1132    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1133                                     ReceiverTypeInfo, Sel, SelectorLocs,
1134                                     Method, makeArrayRef(Args, NumArgs),
1135                                     RBracLoc);
1136  return MaybeBindToTemporary(Result);
1137}
1138
1139// ActOnClassMessage - used for both unary and keyword messages.
1140// ArgExprs is optional - if it is present, the number of expressions
1141// is obtained from Sel.getNumArgs().
1142ExprResult Sema::ActOnClassMessage(Scope *S,
1143                                   ParsedType Receiver,
1144                                   Selector Sel,
1145                                   SourceLocation LBracLoc,
1146                                   ArrayRef<SourceLocation> SelectorLocs,
1147                                   SourceLocation RBracLoc,
1148                                   MultiExprArg Args) {
1149  TypeSourceInfo *ReceiverTypeInfo;
1150  QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1151  if (ReceiverType.isNull())
1152    return ExprError();
1153
1154
1155  if (!ReceiverTypeInfo)
1156    ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1157
1158  return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
1159                           /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
1160                           LBracLoc, SelectorLocs, RBracLoc, move(Args));
1161}
1162
1163/// \brief Build an Objective-C instance message expression.
1164///
1165/// This routine takes care of both normal instance messages and
1166/// instance messages to the superclass instance.
1167///
1168/// \param Receiver The expression that computes the object that will
1169/// receive this message. This may be empty, in which case we are
1170/// sending to the superclass instance and \p SuperLoc must be a valid
1171/// source location.
1172///
1173/// \param ReceiverType The (static) type of the object receiving the
1174/// message. When a \p Receiver expression is provided, this is the
1175/// same type as that expression. For a superclass instance send, this
1176/// is a pointer to the type of the superclass.
1177///
1178/// \param SuperLoc The location of the "super" keyword in a
1179/// superclass instance message.
1180///
1181/// \param Sel The selector to which the message is being sent.
1182///
1183/// \param Method The method that this instance message is invoking, if
1184/// already known.
1185///
1186/// \param LBracLoc The location of the opening square bracket ']'.
1187///
1188/// \param RBrac The location of the closing square bracket ']'.
1189///
1190/// \param Args The message arguments.
1191ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
1192                                      QualType ReceiverType,
1193                                      SourceLocation SuperLoc,
1194                                      Selector Sel,
1195                                      ObjCMethodDecl *Method,
1196                                      SourceLocation LBracLoc,
1197                                      ArrayRef<SourceLocation> SelectorLocs,
1198                                      SourceLocation RBracLoc,
1199                                      MultiExprArg ArgsIn) {
1200  // The location of the receiver.
1201  SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1202
1203  if (LBracLoc.isInvalid()) {
1204    Diag(Loc, diag::err_missing_open_square_message_send)
1205      << FixItHint::CreateInsertion(Loc, "[");
1206    LBracLoc = Loc;
1207  }
1208
1209  // If we have a receiver expression, perform appropriate promotions
1210  // and determine receiver type.
1211  if (Receiver) {
1212    if (Receiver->hasPlaceholderType()) {
1213      ExprResult result = CheckPlaceholderExpr(Receiver);
1214      if (result.isInvalid()) return ExprError();
1215      Receiver = result.take();
1216    }
1217
1218    if (Receiver->isTypeDependent()) {
1219      // If the receiver is type-dependent, we can't type-check anything
1220      // at this point. Build a dependent expression.
1221      unsigned NumArgs = ArgsIn.size();
1222      Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1223      assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1224      return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
1225                                           VK_RValue, LBracLoc, Receiver, Sel,
1226                                           SelectorLocs, /*Method=*/0,
1227                                           makeArrayRef(Args, NumArgs),
1228                                           RBracLoc));
1229    }
1230
1231    // If necessary, apply function/array conversion to the receiver.
1232    // C99 6.7.5.3p[7,8].
1233    ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1234    if (Result.isInvalid())
1235      return ExprError();
1236    Receiver = Result.take();
1237    ReceiverType = Receiver->getType();
1238  }
1239
1240  if (!Method) {
1241    // Handle messages to id.
1242    bool receiverIsId = ReceiverType->isObjCIdType();
1243    if (receiverIsId || ReceiverType->isBlockPointerType() ||
1244        (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1245      Method = LookupInstanceMethodInGlobalPool(Sel,
1246                                                SourceRange(LBracLoc, RBracLoc),
1247                                                receiverIsId);
1248      if (!Method)
1249        Method = LookupFactoryMethodInGlobalPool(Sel,
1250                                                 SourceRange(LBracLoc, RBracLoc),
1251                                                 receiverIsId);
1252    } else if (ReceiverType->isObjCClassType() ||
1253               ReceiverType->isObjCQualifiedClassType()) {
1254      // Handle messages to Class.
1255      // We allow sending a message to a qualified Class ("Class<foo>"), which
1256      // is ok as long as one of the protocols implements the selector (if not, warn).
1257      if (const ObjCObjectPointerType *QClassTy
1258            = ReceiverType->getAsObjCQualifiedClassType()) {
1259        // Search protocols for class methods.
1260        Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1261        if (!Method) {
1262          Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1263          // warn if instance method found for a Class message.
1264          if (Method) {
1265            Diag(Loc, diag::warn_instance_method_on_class_found)
1266              << Method->getSelector() << Sel;
1267            Diag(Method->getLocation(), diag::note_method_declared_at);
1268          }
1269        }
1270      } else {
1271        if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1272          if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1273            // First check the public methods in the class interface.
1274            Method = ClassDecl->lookupClassMethod(Sel);
1275
1276            if (!Method)
1277              Method = LookupPrivateClassMethod(Sel, ClassDecl);
1278          }
1279          if (Method && DiagnoseUseOfDecl(Method, Loc))
1280            return ExprError();
1281        }
1282        if (!Method) {
1283          // If not messaging 'self', look for any factory method named 'Sel'.
1284          if (!Receiver || !isSelfExpr(Receiver)) {
1285            Method = LookupFactoryMethodInGlobalPool(Sel,
1286                                                SourceRange(LBracLoc, RBracLoc),
1287                                                     true);
1288            if (!Method) {
1289              // If no class (factory) method was found, check if an _instance_
1290              // method of the same name exists in the root class only.
1291              Method = LookupInstanceMethodInGlobalPool(Sel,
1292                                               SourceRange(LBracLoc, RBracLoc),
1293                                                        true);
1294              if (Method)
1295                  if (const ObjCInterfaceDecl *ID =
1296                      dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1297                    if (ID->getSuperClass())
1298                      Diag(Loc, diag::warn_root_inst_method_not_found)
1299                      << Sel << SourceRange(LBracLoc, RBracLoc);
1300                  }
1301            }
1302          }
1303        }
1304      }
1305    } else {
1306      ObjCInterfaceDecl* ClassDecl = 0;
1307
1308      // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1309      // long as one of the protocols implements the selector (if not, warn).
1310      if (const ObjCObjectPointerType *QIdTy
1311                                   = ReceiverType->getAsObjCQualifiedIdType()) {
1312        // Search protocols for instance methods.
1313        Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
1314        if (!Method)
1315          Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
1316      } else if (const ObjCObjectPointerType *OCIType
1317                   = ReceiverType->getAsObjCInterfacePointerType()) {
1318        // We allow sending a message to a pointer to an interface (an object).
1319        ClassDecl = OCIType->getInterfaceDecl();
1320
1321        if (ClassDecl->isForwardDecl() && getLangOptions().ObjCAutoRefCount) {
1322          Diag(Loc, diag::err_arc_receiver_forward_instance)
1323            << OCIType->getPointeeType()
1324            << (Receiver ? Receiver->getSourceRange() : SourceRange(SuperLoc));
1325          return ExprError();
1326        }
1327
1328        // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
1329        // faster than the following method (which can do *many* linear searches).
1330        // The idea is to add class info to MethodPool.
1331        Method = ClassDecl->lookupInstanceMethod(Sel);
1332
1333        if (!Method)
1334          // Search protocol qualifiers.
1335          Method = LookupMethodInQualifiedType(Sel, OCIType, true);
1336
1337        const ObjCInterfaceDecl *forwardClass = 0;
1338        if (!Method) {
1339          // If we have implementations in scope, check "private" methods.
1340          Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1341
1342          if (!Method && getLangOptions().ObjCAutoRefCount) {
1343            Diag(Loc, diag::err_arc_may_not_respond)
1344              << OCIType->getPointeeType() << Sel;
1345            return ExprError();
1346          }
1347
1348          if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
1349            // If we still haven't found a method, look in the global pool. This
1350            // behavior isn't very desirable, however we need it for GCC
1351            // compatibility. FIXME: should we deviate??
1352            if (OCIType->qual_empty()) {
1353              Method = LookupInstanceMethodInGlobalPool(Sel,
1354                                                 SourceRange(LBracLoc, RBracLoc));
1355              if (OCIType->getInterfaceDecl()->isForwardDecl())
1356                forwardClass = OCIType->getInterfaceDecl();
1357              if (Method && !forwardClass)
1358                Diag(Loc, diag::warn_maynot_respond)
1359                  << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1360            }
1361          }
1362        }
1363        if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
1364          return ExprError();
1365      } else if (!getLangOptions().ObjCAutoRefCount &&
1366                 !Context.getObjCIdType().isNull() &&
1367                 (ReceiverType->isPointerType() ||
1368                  ReceiverType->isIntegerType())) {
1369        // Implicitly convert integers and pointers to 'id' but emit a warning.
1370        // But not in ARC.
1371        Diag(Loc, diag::warn_bad_receiver_type)
1372          << ReceiverType
1373          << Receiver->getSourceRange();
1374        if (ReceiverType->isPointerType())
1375          Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1376                            CK_CPointerToObjCPointerCast).take();
1377        else {
1378          // TODO: specialized warning on null receivers?
1379          bool IsNull = Receiver->isNullPointerConstant(Context,
1380                                              Expr::NPC_ValueDependentIsNull);
1381          Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1382                            IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
1383        }
1384        ReceiverType = Receiver->getType();
1385      } else {
1386        ExprResult ReceiverRes;
1387        if (getLangOptions().CPlusPlus)
1388          ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
1389        if (ReceiverRes.isUsable()) {
1390          Receiver = ReceiverRes.take();
1391          return BuildInstanceMessage(Receiver,
1392                                      ReceiverType,
1393                                      SuperLoc,
1394                                      Sel,
1395                                      Method,
1396                                      LBracLoc,
1397                                      SelectorLocs,
1398                                      RBracLoc,
1399                                      move(ArgsIn));
1400        } else {
1401          // Reject other random receiver types (e.g. structs).
1402          Diag(Loc, diag::err_bad_receiver_type)
1403            << ReceiverType << Receiver->getSourceRange();
1404          return ExprError();
1405        }
1406      }
1407    }
1408  }
1409
1410  // Check the message arguments.
1411  unsigned NumArgs = ArgsIn.size();
1412  Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1413  QualType ReturnType;
1414  ExprValueKind VK = VK_RValue;
1415  bool ClassMessage = (ReceiverType->isObjCClassType() ||
1416                       ReceiverType->isObjCQualifiedClassType());
1417  if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
1418                                ClassMessage, SuperLoc.isValid(),
1419                                LBracLoc, RBracLoc, ReturnType, VK))
1420    return ExprError();
1421
1422  if (Method && !Method->getResultType()->isVoidType() &&
1423      RequireCompleteType(LBracLoc, Method->getResultType(),
1424                          diag::err_illegal_message_expr_incomplete_type))
1425    return ExprError();
1426
1427  SourceLocation SelLoc = SelectorLocs.front();
1428
1429  // In ARC, forbid the user from sending messages to
1430  // retain/release/autorelease/dealloc/retainCount explicitly.
1431  if (getLangOptions().ObjCAutoRefCount) {
1432    ObjCMethodFamily family =
1433      (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
1434    switch (family) {
1435    case OMF_init:
1436      if (Method)
1437        checkInitMethod(Method, ReceiverType);
1438
1439    case OMF_None:
1440    case OMF_alloc:
1441    case OMF_copy:
1442    case OMF_finalize:
1443    case OMF_mutableCopy:
1444    case OMF_new:
1445    case OMF_self:
1446      break;
1447
1448    case OMF_dealloc:
1449    case OMF_retain:
1450    case OMF_release:
1451    case OMF_autorelease:
1452    case OMF_retainCount:
1453      Diag(Loc, diag::err_arc_illegal_explicit_message)
1454        << Sel << SelLoc;
1455      break;
1456
1457    case OMF_performSelector:
1458      if (Method && NumArgs >= 1) {
1459        if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
1460          Selector ArgSel = SelExp->getSelector();
1461          ObjCMethodDecl *SelMethod =
1462            LookupInstanceMethodInGlobalPool(ArgSel,
1463                                             SelExp->getSourceRange());
1464          if (!SelMethod)
1465            SelMethod =
1466              LookupFactoryMethodInGlobalPool(ArgSel,
1467                                              SelExp->getSourceRange());
1468          if (SelMethod) {
1469            ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
1470            switch (SelFamily) {
1471              case OMF_alloc:
1472              case OMF_copy:
1473              case OMF_mutableCopy:
1474              case OMF_new:
1475              case OMF_self:
1476              case OMF_init:
1477                // Issue error, unless ns_returns_not_retained.
1478                if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
1479                  // selector names a +1 method
1480                  Diag(SelLoc,
1481                       diag::err_arc_perform_selector_retains);
1482                  Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1483                }
1484                break;
1485              default:
1486                // +0 call. OK. unless ns_returns_retained.
1487                if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
1488                  // selector names a +1 method
1489                  Diag(SelLoc,
1490                       diag::err_arc_perform_selector_retains);
1491                  Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1492                }
1493                break;
1494            }
1495          }
1496        } else {
1497          // error (may leak).
1498          Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
1499          Diag(Args[0]->getExprLoc(), diag::note_used_here);
1500        }
1501      }
1502      break;
1503    }
1504  }
1505
1506  // Construct the appropriate ObjCMessageExpr instance.
1507  ObjCMessageExpr *Result;
1508  if (SuperLoc.isValid())
1509    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1510                                     SuperLoc,  /*IsInstanceSuper=*/true,
1511                                     ReceiverType, Sel, SelectorLocs, Method,
1512                                     makeArrayRef(Args, NumArgs), RBracLoc);
1513  else
1514    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1515                                     Receiver, Sel, SelectorLocs, Method,
1516                                     makeArrayRef(Args, NumArgs), RBracLoc);
1517
1518  if (getLangOptions().ObjCAutoRefCount) {
1519    // In ARC, annotate delegate init calls.
1520    if (Result->getMethodFamily() == OMF_init &&
1521        (SuperLoc.isValid() || isSelfExpr(Receiver))) {
1522      // Only consider init calls *directly* in init implementations,
1523      // not within blocks.
1524      ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
1525      if (method && method->getMethodFamily() == OMF_init) {
1526        // The implicit assignment to self means we also don't want to
1527        // consume the result.
1528        Result->setDelegateInitCall(true);
1529        return Owned(Result);
1530      }
1531    }
1532
1533    // In ARC, check for message sends which are likely to introduce
1534    // retain cycles.
1535    checkRetainCycles(Result);
1536  }
1537
1538  return MaybeBindToTemporary(Result);
1539}
1540
1541// ActOnInstanceMessage - used for both unary and keyword messages.
1542// ArgExprs is optional - if it is present, the number of expressions
1543// is obtained from Sel.getNumArgs().
1544ExprResult Sema::ActOnInstanceMessage(Scope *S,
1545                                      Expr *Receiver,
1546                                      Selector Sel,
1547                                      SourceLocation LBracLoc,
1548                                      ArrayRef<SourceLocation> SelectorLocs,
1549                                      SourceLocation RBracLoc,
1550                                      MultiExprArg Args) {
1551  if (!Receiver)
1552    return ExprError();
1553
1554  return BuildInstanceMessage(Receiver, Receiver->getType(),
1555                              /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
1556                              LBracLoc, SelectorLocs, RBracLoc, move(Args));
1557}
1558
1559enum ARCConversionTypeClass {
1560  /// int, void, struct A
1561  ACTC_none,
1562
1563  /// id, void (^)()
1564  ACTC_retainable,
1565
1566  /// id*, id***, void (^*)(),
1567  ACTC_indirectRetainable,
1568
1569  /// void* might be a normal C type, or it might a CF type.
1570  ACTC_voidPtr,
1571
1572  /// struct A*
1573  ACTC_coreFoundation
1574};
1575static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
1576  return (ACTC == ACTC_retainable ||
1577          ACTC == ACTC_coreFoundation ||
1578          ACTC == ACTC_voidPtr);
1579}
1580static bool isAnyCLike(ARCConversionTypeClass ACTC) {
1581  return ACTC == ACTC_none ||
1582         ACTC == ACTC_voidPtr ||
1583         ACTC == ACTC_coreFoundation;
1584}
1585
1586static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
1587  bool isIndirect = false;
1588
1589  // Ignore an outermost reference type.
1590  if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
1591    type = ref->getPointeeType();
1592    isIndirect = true;
1593  }
1594
1595  // Drill through pointers and arrays recursively.
1596  while (true) {
1597    if (const PointerType *ptr = type->getAs<PointerType>()) {
1598      type = ptr->getPointeeType();
1599
1600      // The first level of pointer may be the innermost pointer on a CF type.
1601      if (!isIndirect) {
1602        if (type->isVoidType()) return ACTC_voidPtr;
1603        if (type->isRecordType()) return ACTC_coreFoundation;
1604      }
1605    } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
1606      type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
1607    } else {
1608      break;
1609    }
1610    isIndirect = true;
1611  }
1612
1613  if (isIndirect) {
1614    if (type->isObjCARCBridgableType())
1615      return ACTC_indirectRetainable;
1616    return ACTC_none;
1617  }
1618
1619  if (type->isObjCARCBridgableType())
1620    return ACTC_retainable;
1621
1622  return ACTC_none;
1623}
1624
1625namespace {
1626  /// A result from the cast checker.
1627  enum ACCResult {
1628    /// Cannot be casted.
1629    ACC_invalid,
1630
1631    /// Can be safely retained or not retained.
1632    ACC_bottom,
1633
1634    /// Can be casted at +0.
1635    ACC_plusZero,
1636
1637    /// Can be casted at +1.
1638    ACC_plusOne
1639  };
1640  ACCResult merge(ACCResult left, ACCResult right) {
1641    if (left == right) return left;
1642    if (left == ACC_bottom) return right;
1643    if (right == ACC_bottom) return left;
1644    return ACC_invalid;
1645  }
1646
1647  /// A checker which white-lists certain expressions whose conversion
1648  /// to or from retainable type would otherwise be forbidden in ARC.
1649  class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
1650    typedef StmtVisitor<ARCCastChecker, ACCResult> super;
1651
1652    ASTContext &Context;
1653    ARCConversionTypeClass SourceClass;
1654    ARCConversionTypeClass TargetClass;
1655
1656    static bool isCFType(QualType type) {
1657      // Someday this can use ns_bridged.  For now, it has to do this.
1658      return type->isCARCBridgableType();
1659    }
1660
1661  public:
1662    ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
1663                   ARCConversionTypeClass target)
1664      : Context(Context), SourceClass(source), TargetClass(target) {}
1665
1666    using super::Visit;
1667    ACCResult Visit(Expr *e) {
1668      return super::Visit(e->IgnoreParens());
1669    }
1670
1671    ACCResult VisitStmt(Stmt *s) {
1672      return ACC_invalid;
1673    }
1674
1675    /// Null pointer constants can be casted however you please.
1676    ACCResult VisitExpr(Expr *e) {
1677      if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1678        return ACC_bottom;
1679      return ACC_invalid;
1680    }
1681
1682    /// Objective-C string literals can be safely casted.
1683    ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
1684      // If we're casting to any retainable type, go ahead.  Global
1685      // strings are immune to retains, so this is bottom.
1686      if (isAnyRetainable(TargetClass)) return ACC_bottom;
1687
1688      return ACC_invalid;
1689    }
1690
1691    /// Look through certain implicit and explicit casts.
1692    ACCResult VisitCastExpr(CastExpr *e) {
1693      switch (e->getCastKind()) {
1694        case CK_NullToPointer:
1695          return ACC_bottom;
1696
1697        case CK_NoOp:
1698        case CK_LValueToRValue:
1699        case CK_BitCast:
1700        case CK_GetObjCProperty:
1701        case CK_CPointerToObjCPointerCast:
1702        case CK_BlockPointerToObjCPointerCast:
1703        case CK_AnyPointerToBlockPointerCast:
1704          return Visit(e->getSubExpr());
1705
1706        default:
1707          return ACC_invalid;
1708      }
1709    }
1710
1711    /// Look through unary extension.
1712    ACCResult VisitUnaryExtension(UnaryOperator *e) {
1713      return Visit(e->getSubExpr());
1714    }
1715
1716    /// Ignore the LHS of a comma operator.
1717    ACCResult VisitBinComma(BinaryOperator *e) {
1718      return Visit(e->getRHS());
1719    }
1720
1721    /// Conditional operators are okay if both sides are okay.
1722    ACCResult VisitConditionalOperator(ConditionalOperator *e) {
1723      ACCResult left = Visit(e->getTrueExpr());
1724      if (left == ACC_invalid) return ACC_invalid;
1725      return merge(left, Visit(e->getFalseExpr()));
1726    }
1727
1728    /// Statement expressions are okay if their result expression is okay.
1729    ACCResult VisitStmtExpr(StmtExpr *e) {
1730      return Visit(e->getSubStmt()->body_back());
1731    }
1732
1733    /// Some declaration references are okay.
1734    ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
1735      // References to global constants from system headers are okay.
1736      // These are things like 'kCFStringTransformToLatin'.  They are
1737      // can also be assumed to be immune to retains.
1738      VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
1739      if (isAnyRetainable(TargetClass) &&
1740          isAnyRetainable(SourceClass) &&
1741          var &&
1742          var->getStorageClass() == SC_Extern &&
1743          var->getType().isConstQualified() &&
1744          Context.getSourceManager().isInSystemHeader(var->getLocation())) {
1745        return ACC_bottom;
1746      }
1747
1748      // Nothing else.
1749      return ACC_invalid;
1750    }
1751
1752    /// Some calls are okay.
1753    ACCResult VisitCallExpr(CallExpr *e) {
1754      if (FunctionDecl *fn = e->getDirectCallee())
1755        if (ACCResult result = checkCallToFunction(fn))
1756          return result;
1757
1758      return super::VisitCallExpr(e);
1759    }
1760
1761    ACCResult checkCallToFunction(FunctionDecl *fn) {
1762      // Require a CF*Ref return type.
1763      if (!isCFType(fn->getResultType()))
1764        return ACC_invalid;
1765
1766      if (!isAnyRetainable(TargetClass))
1767        return ACC_invalid;
1768
1769      // Honor an explicit 'not retained' attribute.
1770      if (fn->hasAttr<CFReturnsNotRetainedAttr>())
1771        return ACC_plusZero;
1772
1773      // Honor an explicit 'retained' attribute, except that for
1774      // now we're not going to permit implicit handling of +1 results,
1775      // because it's a bit frightening.
1776      if (fn->hasAttr<CFReturnsRetainedAttr>())
1777        return ACC_invalid; // ACC_plusOne if we start accepting this
1778
1779      // Recognize this specific builtin function, which is used by CFSTR.
1780      unsigned builtinID = fn->getBuiltinID();
1781      if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
1782        return ACC_bottom;
1783
1784      // Otherwise, don't do anything implicit with an unaudited function.
1785      if (!fn->hasAttr<CFAuditedTransferAttr>())
1786        return ACC_invalid;
1787
1788      // Otherwise, it's +0 unless it follows the create convention.
1789      if (ento::coreFoundation::followsCreateRule(fn))
1790        return ACC_invalid; // ACC_plusOne if we start accepting this
1791
1792      return ACC_plusZero;
1793    }
1794
1795    ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
1796      return checkCallToMethod(e->getMethodDecl());
1797    }
1798
1799    ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
1800      ObjCMethodDecl *method;
1801      if (e->isExplicitProperty())
1802        method = e->getExplicitProperty()->getGetterMethodDecl();
1803      else
1804        method = e->getImplicitPropertyGetter();
1805      return checkCallToMethod(method);
1806    }
1807
1808    ACCResult checkCallToMethod(ObjCMethodDecl *method) {
1809      if (!method) return ACC_invalid;
1810
1811      // Check for message sends to functions returning CF types.  We
1812      // just obey the Cocoa conventions with these, even though the
1813      // return type is CF.
1814      if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
1815        return ACC_invalid;
1816
1817      // If the method is explicitly marked not-retained, it's +0.
1818      if (method->hasAttr<CFReturnsNotRetainedAttr>())
1819        return ACC_plusZero;
1820
1821      // If the method is explicitly marked as returning retained, or its
1822      // selector follows a +1 Cocoa convention, treat it as +1.
1823      if (method->hasAttr<CFReturnsRetainedAttr>())
1824        return ACC_plusOne;
1825
1826      switch (method->getSelector().getMethodFamily()) {
1827      case OMF_alloc:
1828      case OMF_copy:
1829      case OMF_mutableCopy:
1830      case OMF_new:
1831        return ACC_plusOne;
1832
1833      default:
1834        // Otherwise, treat it as +0.
1835        return ACC_plusZero;
1836      }
1837    }
1838  };
1839}
1840
1841static void
1842diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
1843                          QualType castType, ARCConversionTypeClass castACTC,
1844                          Expr *castExpr, ARCConversionTypeClass exprACTC,
1845                          Sema::CheckedConversionKind CCK) {
1846  SourceLocation loc =
1847    (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
1848
1849  if (S.makeUnavailableInSystemHeader(loc,
1850                "converts between Objective-C and C pointers in -fobjc-arc"))
1851    return;
1852
1853  QualType castExprType = castExpr->getType();
1854
1855  unsigned srcKind = 0;
1856  switch (exprACTC) {
1857  case ACTC_none:
1858  case ACTC_coreFoundation:
1859  case ACTC_voidPtr:
1860    srcKind = (castExprType->isPointerType() ? 1 : 0);
1861    break;
1862  case ACTC_retainable:
1863    srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
1864    break;
1865  case ACTC_indirectRetainable:
1866    srcKind = 4;
1867    break;
1868  }
1869
1870  // Check whether this could be fixed with a bridge cast.
1871  SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
1872  SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
1873
1874  // Bridge from an ARC type to a CF type.
1875  if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
1876    S.Diag(loc, diag::err_arc_cast_requires_bridge)
1877      << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
1878      << 2 // of C pointer type
1879      << castExprType
1880      << unsigned(castType->isBlockPointerType()) // to ObjC|block type
1881      << castType
1882      << castRange
1883      << castExpr->getSourceRange();
1884
1885    S.Diag(noteLoc, diag::note_arc_bridge)
1886      << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
1887            FixItHint::CreateInsertion(afterLParen, "__bridge "));
1888    S.Diag(noteLoc, diag::note_arc_bridge_transfer)
1889      << castExprType
1890      << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
1891            FixItHint::CreateInsertion(afterLParen, "__bridge_transfer "));
1892
1893    return;
1894  }
1895
1896  // Bridge from a CF type to an ARC type.
1897  if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
1898    S.Diag(loc, diag::err_arc_cast_requires_bridge)
1899      << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
1900      << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
1901      << castExprType
1902      << 2 // to C pointer type
1903      << castType
1904      << castRange
1905      << castExpr->getSourceRange();
1906
1907    S.Diag(noteLoc, diag::note_arc_bridge)
1908      << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
1909            FixItHint::CreateInsertion(afterLParen, "__bridge "));
1910    S.Diag(noteLoc, diag::note_arc_bridge_retained)
1911      << castType
1912      << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
1913            FixItHint::CreateInsertion(afterLParen, "__bridge_retained "));
1914
1915    return;
1916  }
1917
1918  S.Diag(loc, diag::err_arc_mismatched_cast)
1919    << (CCK != Sema::CCK_ImplicitConversion)
1920    << srcKind << castExprType << castType
1921    << castRange << castExpr->getSourceRange();
1922}
1923
1924Sema::ARCConversionResult
1925Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
1926                             Expr *&castExpr, CheckedConversionKind CCK) {
1927  QualType castExprType = castExpr->getType();
1928
1929  // For the purposes of the classification, we assume reference types
1930  // will bind to temporaries.
1931  QualType effCastType = castType;
1932  if (const ReferenceType *ref = castType->getAs<ReferenceType>())
1933    effCastType = ref->getPointeeType();
1934
1935  ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
1936  ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
1937  if (exprACTC == castACTC) return ACR_okay;
1938  if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
1939
1940  // Allow all of these types to be cast to integer types (but not
1941  // vice-versa).
1942  if (castACTC == ACTC_none && castType->isIntegralType(Context))
1943    return ACR_okay;
1944
1945  // Allow casts between pointers to lifetime types (e.g., __strong id*)
1946  // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
1947  // must be explicit.
1948  if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
1949    return ACR_okay;
1950  if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
1951      CCK != CCK_ImplicitConversion)
1952    return ACR_okay;
1953
1954  switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
1955  // For invalid casts, fall through.
1956  case ACC_invalid:
1957    break;
1958
1959  // Do nothing for both bottom and +0.
1960  case ACC_bottom:
1961  case ACC_plusZero:
1962    return ACR_okay;
1963
1964  // If the result is +1, consume it here.
1965  case ACC_plusOne:
1966    castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
1967                                        CK_ARCConsumeObject, castExpr,
1968                                        0, VK_RValue);
1969    ExprNeedsCleanups = true;
1970    return ACR_okay;
1971  }
1972
1973  // If this is a non-implicit cast from id or block type to a
1974  // CoreFoundation type, delay complaining in case the cast is used
1975  // in an acceptable context.
1976  if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
1977      CCK != CCK_ImplicitConversion)
1978    return ACR_unbridged;
1979
1980  diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
1981                            castExpr, exprACTC, CCK);
1982  return ACR_okay;
1983}
1984
1985/// Given that we saw an expression with the ARCUnbridgedCastTy
1986/// placeholder type, complain bitterly.
1987void Sema::diagnoseARCUnbridgedCast(Expr *e) {
1988  // We expect the spurious ImplicitCastExpr to already have been stripped.
1989  assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1990  CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
1991
1992  SourceRange castRange;
1993  QualType castType;
1994  CheckedConversionKind CCK;
1995
1996  if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
1997    castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
1998    castType = cast->getTypeAsWritten();
1999    CCK = CCK_CStyleCast;
2000  } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
2001    castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
2002    castType = cast->getTypeAsWritten();
2003    CCK = CCK_OtherCast;
2004  } else {
2005    castType = cast->getType();
2006    CCK = CCK_ImplicitConversion;
2007  }
2008
2009  ARCConversionTypeClass castACTC =
2010    classifyTypeForARCConversion(castType.getNonReferenceType());
2011
2012  Expr *castExpr = realCast->getSubExpr();
2013  assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
2014
2015  diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
2016                            castExpr, ACTC_retainable, CCK);
2017}
2018
2019/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
2020/// type, remove the placeholder cast.
2021Expr *Sema::stripARCUnbridgedCast(Expr *e) {
2022  assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
2023
2024  if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
2025    Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
2026    return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
2027  } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
2028    assert(uo->getOpcode() == UO_Extension);
2029    Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
2030    return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
2031                                   sub->getValueKind(), sub->getObjectKind(),
2032                                       uo->getOperatorLoc());
2033  } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
2034    assert(!gse->isResultDependent());
2035
2036    unsigned n = gse->getNumAssocs();
2037    SmallVector<Expr*, 4> subExprs(n);
2038    SmallVector<TypeSourceInfo*, 4> subTypes(n);
2039    for (unsigned i = 0; i != n; ++i) {
2040      subTypes[i] = gse->getAssocTypeSourceInfo(i);
2041      Expr *sub = gse->getAssocExpr(i);
2042      if (i == gse->getResultIndex())
2043        sub = stripARCUnbridgedCast(sub);
2044      subExprs[i] = sub;
2045    }
2046
2047    return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
2048                                              gse->getControllingExpr(),
2049                                              subTypes.data(), subExprs.data(),
2050                                              n, gse->getDefaultLoc(),
2051                                              gse->getRParenLoc(),
2052                                       gse->containsUnexpandedParameterPack(),
2053                                              gse->getResultIndex());
2054  } else {
2055    assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
2056    return cast<ImplicitCastExpr>(e)->getSubExpr();
2057  }
2058}
2059
2060bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
2061                                                 QualType exprType) {
2062  QualType canCastType =
2063    Context.getCanonicalType(castType).getUnqualifiedType();
2064  QualType canExprType =
2065    Context.getCanonicalType(exprType).getUnqualifiedType();
2066  if (isa<ObjCObjectPointerType>(canCastType) &&
2067      castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
2068      canExprType->isObjCObjectPointerType()) {
2069    if (const ObjCObjectPointerType *ObjT =
2070        canExprType->getAs<ObjCObjectPointerType>())
2071      if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
2072        return false;
2073  }
2074  return true;
2075}
2076
2077/// Look for an ObjCReclaimReturnedObject cast and destroy it.
2078static Expr *maybeUndoReclaimObject(Expr *e) {
2079  // For now, we just undo operands that are *immediately* reclaim
2080  // expressions, which prevents the vast majority of potential
2081  // problems here.  To catch them all, we'd need to rebuild arbitrary
2082  // value-propagating subexpressions --- we can't reliably rebuild
2083  // in-place because of expression sharing.
2084  if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2085    if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
2086      return ice->getSubExpr();
2087
2088  return e;
2089}
2090
2091ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
2092                                      ObjCBridgeCastKind Kind,
2093                                      SourceLocation BridgeKeywordLoc,
2094                                      TypeSourceInfo *TSInfo,
2095                                      Expr *SubExpr) {
2096  ExprResult SubResult = UsualUnaryConversions(SubExpr);
2097  if (SubResult.isInvalid()) return ExprError();
2098  SubExpr = SubResult.take();
2099
2100  QualType T = TSInfo->getType();
2101  QualType FromType = SubExpr->getType();
2102
2103  CastKind CK;
2104
2105  bool MustConsume = false;
2106  if (T->isDependentType() || SubExpr->isTypeDependent()) {
2107    // Okay: we'll build a dependent expression type.
2108    CK = CK_Dependent;
2109  } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
2110    // Casting CF -> id
2111    CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
2112                                  : CK_CPointerToObjCPointerCast);
2113    switch (Kind) {
2114    case OBC_Bridge:
2115      break;
2116
2117    case OBC_BridgeRetained:
2118      Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2119        << 2
2120        << FromType
2121        << (T->isBlockPointerType()? 1 : 0)
2122        << T
2123        << SubExpr->getSourceRange()
2124        << Kind;
2125      Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2126        << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
2127      Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
2128        << FromType
2129        << FixItHint::CreateReplacement(BridgeKeywordLoc,
2130                                        "__bridge_transfer ");
2131
2132      Kind = OBC_Bridge;
2133      break;
2134
2135    case OBC_BridgeTransfer:
2136      // We must consume the Objective-C object produced by the cast.
2137      MustConsume = true;
2138      break;
2139    }
2140  } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
2141    // Okay: id -> CF
2142    CK = CK_BitCast;
2143    switch (Kind) {
2144    case OBC_Bridge:
2145      // Reclaiming a value that's going to be __bridge-casted to CF
2146      // is very dangerous, so we don't do it.
2147      SubExpr = maybeUndoReclaimObject(SubExpr);
2148      break;
2149
2150    case OBC_BridgeRetained:
2151      // Produce the object before casting it.
2152      SubExpr = ImplicitCastExpr::Create(Context, FromType,
2153                                         CK_ARCProduceObject,
2154                                         SubExpr, 0, VK_RValue);
2155      break;
2156
2157    case OBC_BridgeTransfer:
2158      Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2159        << (FromType->isBlockPointerType()? 1 : 0)
2160        << FromType
2161        << 2
2162        << T
2163        << SubExpr->getSourceRange()
2164        << Kind;
2165
2166      Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2167        << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
2168      Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
2169        << T
2170        << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge_retained ");
2171
2172      Kind = OBC_Bridge;
2173      break;
2174    }
2175  } else {
2176    Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
2177      << FromType << T << Kind
2178      << SubExpr->getSourceRange()
2179      << TSInfo->getTypeLoc().getSourceRange();
2180    return ExprError();
2181  }
2182
2183  Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
2184                                                   BridgeKeywordLoc,
2185                                                   TSInfo, SubExpr);
2186
2187  if (MustConsume) {
2188    ExprNeedsCleanups = true;
2189    Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
2190                                      0, VK_RValue);
2191  }
2192
2193  return Result;
2194}
2195
2196ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
2197                                      SourceLocation LParenLoc,
2198                                      ObjCBridgeCastKind Kind,
2199                                      SourceLocation BridgeKeywordLoc,
2200                                      ParsedType Type,
2201                                      SourceLocation RParenLoc,
2202                                      Expr *SubExpr) {
2203  TypeSourceInfo *TSInfo = 0;
2204  QualType T = GetTypeFromParser(Type, &TSInfo);
2205  if (!TSInfo)
2206    TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
2207  return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
2208                              SubExpr);
2209}
2210