SemaExprObjC.cpp revision 2a96bf5e66731bb54dff3e4aadfbbced83377530
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/AST/ASTContext.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/TypeLoc.h"
23#include "llvm/ADT/SmallString.h"
24#include "clang/Lex/Preprocessor.h"
25
26using namespace clang;
27using namespace sema;
28
29ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
30                                        Expr **strings,
31                                        unsigned NumStrings) {
32  StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
33
34  // Most ObjC strings are formed out of a single piece.  However, we *can*
35  // have strings formed out of multiple @ strings with multiple pptokens in
36  // each one, e.g. @"foo" "bar" @"baz" "qux"   which need to be turned into one
37  // StringLiteral for ObjCStringLiteral to hold onto.
38  StringLiteral *S = Strings[0];
39
40  // If we have a multi-part string, merge it all together.
41  if (NumStrings != 1) {
42    // Concatenate objc strings.
43    llvm::SmallString<128> StrBuf;
44    llvm::SmallVector<SourceLocation, 8> StrLocs;
45
46    for (unsigned i = 0; i != NumStrings; ++i) {
47      S = Strings[i];
48
49      // ObjC strings can't be wide.
50      if (S->isWide()) {
51        Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
52          << S->getSourceRange();
53        return true;
54      }
55
56      // Append the string.
57      StrBuf += S->getString();
58
59      // Get the locations of the string tokens.
60      StrLocs.append(S->tokloc_begin(), S->tokloc_end());
61    }
62
63    // Create the aggregate string with the appropriate content and location
64    // information.
65    S = StringLiteral::Create(Context, &StrBuf[0], StrBuf.size(), false,
66                              Context.getPointerType(Context.CharTy),
67                              &StrLocs[0], StrLocs.size());
68  }
69
70  // Verify that this composite string is acceptable for ObjC strings.
71  if (CheckObjCString(S))
72    return true;
73
74  // Initialize the constant string interface lazily. This assumes
75  // the NSString interface is seen in this translation unit. Note: We
76  // don't use NSConstantString, since the runtime team considers this
77  // interface private (even though it appears in the header files).
78  QualType Ty = Context.getObjCConstantStringInterface();
79  if (!Ty.isNull()) {
80    Ty = Context.getObjCObjectPointerType(Ty);
81  } else if (getLangOptions().NoConstantCFStrings) {
82    IdentifierInfo *NSIdent=0;
83    std::string StringClass(getLangOptions().ObjCConstantStringClass);
84
85    if (StringClass.empty())
86      NSIdent = &Context.Idents.get("NSConstantString");
87    else
88      NSIdent = &Context.Idents.get(StringClass);
89
90    NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
91                                     LookupOrdinaryName);
92    if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
93      Context.setObjCConstantStringInterface(StrIF);
94      Ty = Context.getObjCConstantStringInterface();
95      Ty = Context.getObjCObjectPointerType(Ty);
96    } else {
97      // If there is no NSConstantString interface defined then treat this
98      // as error and recover from it.
99      Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
100        << S->getSourceRange();
101      Ty = Context.getObjCIdType();
102    }
103  } else {
104    IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
105    NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
106                                     LookupOrdinaryName);
107    if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
108      Context.setObjCConstantStringInterface(StrIF);
109      Ty = Context.getObjCConstantStringInterface();
110      Ty = Context.getObjCObjectPointerType(Ty);
111    } else {
112      // If there is no NSString interface defined then treat constant
113      // strings as untyped objects and let the runtime figure it out later.
114      Ty = Context.getObjCIdType();
115    }
116  }
117
118  return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
119}
120
121Expr *Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
122                                      TypeSourceInfo *EncodedTypeInfo,
123                                      SourceLocation RParenLoc) {
124  QualType EncodedType = EncodedTypeInfo->getType();
125  QualType StrTy;
126  if (EncodedType->isDependentType())
127    StrTy = Context.DependentTy;
128  else {
129    std::string Str;
130    Context.getObjCEncodingForType(EncodedType, Str);
131
132    // The type of @encode is the same as the type of the corresponding string,
133    // which is an array type.
134    StrTy = Context.CharTy;
135    // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
136    if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
137      StrTy.addConst();
138    StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
139                                         ArrayType::Normal, 0);
140  }
141
142  return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
143}
144
145ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
146                                           SourceLocation EncodeLoc,
147                                           SourceLocation LParenLoc,
148                                           ParsedType ty,
149                                           SourceLocation RParenLoc) {
150  // FIXME: Preserve type source info ?
151  TypeSourceInfo *TInfo;
152  QualType EncodedType = GetTypeFromParser(ty, &TInfo);
153  if (!TInfo)
154    TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
155                                             PP.getLocForEndOfToken(LParenLoc));
156
157  return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
158}
159
160ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
161                                             SourceLocation AtLoc,
162                                             SourceLocation SelLoc,
163                                             SourceLocation LParenLoc,
164                                             SourceLocation RParenLoc) {
165  ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
166                             SourceRange(LParenLoc, RParenLoc), false, false);
167  if (!Method)
168    Method = LookupFactoryMethodInGlobalPool(Sel,
169                                          SourceRange(LParenLoc, RParenLoc));
170  if (!Method)
171    Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
172
173  llvm::DenseMap<Selector, SourceLocation>::iterator Pos
174    = ReferencedSelectors.find(Sel);
175  if (Pos == ReferencedSelectors.end())
176    ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
177
178  QualType Ty = Context.getObjCSelType();
179  return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
180}
181
182ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
183                                             SourceLocation AtLoc,
184                                             SourceLocation ProtoLoc,
185                                             SourceLocation LParenLoc,
186                                             SourceLocation RParenLoc) {
187  ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
188  if (!PDecl) {
189    Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
190    return true;
191  }
192
193  QualType Ty = Context.getObjCProtoType();
194  if (Ty.isNull())
195    return true;
196  Ty = Context.getObjCObjectPointerType(Ty);
197  return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
198}
199
200/// Try to capture an implicit reference to 'self'.
201ObjCMethodDecl *Sema::tryCaptureObjCSelf() {
202  // Ignore block scopes: we can capture through them.
203  DeclContext *DC = CurContext;
204  while (true) {
205    if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
206    else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
207    else break;
208  }
209
210  // If we're not in an ObjC method, error out.  Note that, unlike the
211  // C++ case, we don't require an instance method --- class methods
212  // still have a 'self', and we really do still need to capture it!
213  ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
214  if (!method)
215    return 0;
216
217  ImplicitParamDecl *self = method->getSelfDecl();
218  assert(self && "capturing 'self' in non-definition?");
219
220  // Mark that we're closing on 'this' in all the block scopes, if applicable.
221  for (unsigned idx = FunctionScopes.size() - 1;
222       isa<BlockScopeInfo>(FunctionScopes[idx]);
223       --idx) {
224    BlockScopeInfo *blockScope = cast<BlockScopeInfo>(FunctionScopes[idx]);
225    unsigned &captureIndex = blockScope->CaptureMap[self];
226    if (captureIndex) break;
227
228    bool nested = isa<BlockScopeInfo>(FunctionScopes[idx-1]);
229    blockScope->Captures.push_back(
230              BlockDecl::Capture(self, /*byref*/ false, nested, /*copy*/ 0));
231    captureIndex = blockScope->Captures.size(); // +1
232  }
233
234  return method;
235}
236
237
238bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
239                                     Selector Sel, ObjCMethodDecl *Method,
240                                     bool isClassMessage,
241                                     SourceLocation lbrac, SourceLocation rbrac,
242                                     QualType &ReturnType, ExprValueKind &VK) {
243  if (!Method) {
244    // Apply default argument promotion as for (C99 6.5.2.2p6).
245    for (unsigned i = 0; i != NumArgs; i++) {
246      if (Args[i]->isTypeDependent())
247        continue;
248
249      DefaultArgumentPromotion(Args[i]);
250    }
251
252    unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found :
253                                       diag::warn_inst_method_not_found;
254    Diag(lbrac, DiagID)
255      << Sel << isClassMessage << SourceRange(lbrac, rbrac);
256    ReturnType = Context.getObjCIdType();
257    VK = VK_RValue;
258    return false;
259  }
260
261  ReturnType = Method->getSendResultType();
262  VK = Expr::getValueKindForType(Method->getResultType());
263
264  unsigned NumNamedArgs = Sel.getNumArgs();
265  // Method might have more arguments than selector indicates. This is due
266  // to addition of c-style arguments in method.
267  if (Method->param_size() > Sel.getNumArgs())
268    NumNamedArgs = Method->param_size();
269  // FIXME. This need be cleaned up.
270  if (NumArgs < NumNamedArgs) {
271    Diag(lbrac, diag::err_typecheck_call_too_few_args)
272      << 2 << NumNamedArgs << NumArgs;
273    return false;
274  }
275
276  bool IsError = false;
277  for (unsigned i = 0; i < NumNamedArgs; i++) {
278    // We can't do any type-checking on a type-dependent argument.
279    if (Args[i]->isTypeDependent())
280      continue;
281
282    Expr *argExpr = Args[i];
283
284    ParmVarDecl *Param = Method->param_begin()[i];
285    assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
286
287    if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
288                            Param->getType(),
289                            PDiag(diag::err_call_incomplete_argument)
290                              << argExpr->getSourceRange()))
291      return true;
292
293    InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
294                                                                      Param);
295    ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
296    if (ArgE.isInvalid())
297      IsError = true;
298    else
299      Args[i] = ArgE.takeAs<Expr>();
300  }
301
302  // Promote additional arguments to variadic methods.
303  if (Method->isVariadic()) {
304    for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
305      if (Args[i]->isTypeDependent())
306        continue;
307
308      IsError |= DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
309    }
310  } else {
311    // Check for extra arguments to non-variadic methods.
312    if (NumArgs != NumNamedArgs) {
313      Diag(Args[NumNamedArgs]->getLocStart(),
314           diag::err_typecheck_call_too_many_args)
315        << 2 /*method*/ << NumNamedArgs << NumArgs
316        << Method->getSourceRange()
317        << SourceRange(Args[NumNamedArgs]->getLocStart(),
318                       Args[NumArgs-1]->getLocEnd());
319    }
320  }
321
322  DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
323  return IsError;
324}
325
326bool Sema::isSelfExpr(Expr *RExpr) {
327  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RExpr))
328    if (ICE->getCastKind() == CK_LValueToRValue)
329      RExpr = ICE->getSubExpr();
330  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RExpr))
331    if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
332      return true;
333  return false;
334}
335
336// Helper method for ActOnClassMethod/ActOnInstanceMethod.
337// Will search "local" class/category implementations for a method decl.
338// If failed, then we search in class's root for an instance method.
339// Returns 0 if no method is found.
340ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
341                                          ObjCInterfaceDecl *ClassDecl) {
342  ObjCMethodDecl *Method = 0;
343  // lookup in class and all superclasses
344  while (ClassDecl && !Method) {
345    if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
346      Method = ImpDecl->getClassMethod(Sel);
347
348    // Look through local category implementations associated with the class.
349    if (!Method)
350      Method = ClassDecl->getCategoryClassMethod(Sel);
351
352    // Before we give up, check if the selector is an instance method.
353    // But only in the root. This matches gcc's behaviour and what the
354    // runtime expects.
355    if (!Method && !ClassDecl->getSuperClass()) {
356      Method = ClassDecl->lookupInstanceMethod(Sel);
357      // Look through local category implementations associated
358      // with the root class.
359      if (!Method)
360        Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
361    }
362
363    ClassDecl = ClassDecl->getSuperClass();
364  }
365  return Method;
366}
367
368ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
369                                              ObjCInterfaceDecl *ClassDecl) {
370  ObjCMethodDecl *Method = 0;
371  while (ClassDecl && !Method) {
372    // If we have implementations in scope, check "private" methods.
373    if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
374      Method = ImpDecl->getInstanceMethod(Sel);
375
376    // Look through local category implementations associated with the class.
377    if (!Method)
378      Method = ClassDecl->getCategoryInstanceMethod(Sel);
379    ClassDecl = ClassDecl->getSuperClass();
380  }
381  return Method;
382}
383
384/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
385/// objective C interface.  This is a property reference expression.
386ExprResult Sema::
387HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
388                          Expr *BaseExpr, DeclarationName MemberName,
389                          SourceLocation MemberLoc,
390                          SourceLocation SuperLoc, QualType SuperType,
391                          bool Super) {
392  const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
393  ObjCInterfaceDecl *IFace = IFaceT->getDecl();
394  IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
395
396  if (IFace->isForwardDecl()) {
397    Diag(MemberLoc, diag::err_property_not_found_forward_class)
398         << MemberName << QualType(OPT, 0);
399    Diag(IFace->getLocation(), diag::note_forward_class);
400    return ExprError();
401  }
402  // Search for a declared property first.
403  if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
404    // Check whether we can reference this property.
405    if (DiagnoseUseOfDecl(PD, MemberLoc))
406      return ExprError();
407    QualType ResTy = PD->getType();
408    Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
409    ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
410    if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
411      ResTy = Getter->getResultType();
412
413    if (Super)
414      return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
415                                                     VK_LValue, OK_ObjCProperty,
416                                                     MemberLoc,
417                                                     SuperLoc, SuperType));
418    else
419      return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
420                                                     VK_LValue, OK_ObjCProperty,
421                                                     MemberLoc, BaseExpr));
422  }
423  // Check protocols on qualified interfaces.
424  for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
425       E = OPT->qual_end(); I != E; ++I)
426    if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
427      // Check whether we can reference this property.
428      if (DiagnoseUseOfDecl(PD, MemberLoc))
429        return ExprError();
430      if (Super)
431        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
432                                                       VK_LValue,
433                                                       OK_ObjCProperty,
434                                                       MemberLoc,
435                                                       SuperLoc, SuperType));
436      else
437        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
438                                                       VK_LValue,
439                                                       OK_ObjCProperty,
440                                                       MemberLoc,
441                                                       BaseExpr));
442    }
443  // If that failed, look for an "implicit" property by seeing if the nullary
444  // selector is implemented.
445
446  // FIXME: The logic for looking up nullary and unary selectors should be
447  // shared with the code in ActOnInstanceMessage.
448
449  Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
450  ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
451
452  // If this reference is in an @implementation, check for 'private' methods.
453  if (!Getter)
454    Getter = IFace->lookupPrivateMethod(Sel);
455
456  // Look through local category implementations associated with the class.
457  if (!Getter)
458    Getter = IFace->getCategoryInstanceMethod(Sel);
459  if (Getter) {
460    // Check if we can reference this property.
461    if (DiagnoseUseOfDecl(Getter, MemberLoc))
462      return ExprError();
463  }
464  // If we found a getter then this may be a valid dot-reference, we
465  // will look for the matching setter, in case it is needed.
466  Selector SetterSel =
467    SelectorTable::constructSetterName(PP.getIdentifierTable(),
468                                       PP.getSelectorTable(), Member);
469  ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
470  if (!Setter) {
471    // If this reference is in an @implementation, also check for 'private'
472    // methods.
473    Setter = IFace->lookupPrivateMethod(SetterSel);
474  }
475  // Look through local category implementations associated with the class.
476  if (!Setter)
477    Setter = IFace->getCategoryInstanceMethod(SetterSel);
478
479  if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
480    return ExprError();
481
482  if (Getter || Setter) {
483    QualType PType;
484    if (Getter)
485      PType = Getter->getSendResultType();
486    else {
487      ParmVarDecl *ArgDecl = *Setter->param_begin();
488      PType = ArgDecl->getType();
489    }
490
491    ExprValueKind VK = VK_LValue;
492    ExprObjectKind OK = OK_ObjCProperty;
493    if (!getLangOptions().CPlusPlus && !PType.hasQualifiers() &&
494        PType->isVoidType())
495      VK = VK_RValue, OK = OK_Ordinary;
496
497    if (Super)
498      return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
499                                                     PType, VK, OK,
500                                                     MemberLoc,
501                                                     SuperLoc, SuperType));
502    else
503      return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
504                                                     PType, VK, OK,
505                                                     MemberLoc, BaseExpr));
506
507  }
508
509  // Attempt to correct for typos in property names.
510  LookupResult Res(*this, MemberName, MemberLoc, LookupOrdinaryName);
511  if (CorrectTypo(Res, 0, 0, IFace, false, CTC_NoKeywords, OPT) &&
512      Res.getAsSingle<ObjCPropertyDecl>()) {
513    DeclarationName TypoResult = Res.getLookupName();
514    Diag(MemberLoc, diag::err_property_not_found_suggest)
515      << MemberName << QualType(OPT, 0) << TypoResult
516      << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
517    ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
518    Diag(Property->getLocation(), diag::note_previous_decl)
519      << Property->getDeclName();
520    return HandleExprPropertyRefExpr(OPT, BaseExpr, TypoResult, MemberLoc,
521                                     SuperLoc, SuperType, Super);
522  }
523  ObjCInterfaceDecl *ClassDeclared;
524  if (ObjCIvarDecl *Ivar =
525      IFace->lookupInstanceVariable(Member, ClassDeclared)) {
526    QualType T = Ivar->getType();
527    if (const ObjCObjectPointerType * OBJPT =
528        T->getAsObjCInterfacePointerType()) {
529      const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
530      if (ObjCInterfaceDecl *IFace = IFaceT->getDecl())
531        if (IFace->isForwardDecl()) {
532          Diag(MemberLoc, diag::err_property_not_as_forward_class)
533          << MemberName << IFace;
534          Diag(IFace->getLocation(), diag::note_forward_class);
535          return ExprError();
536        }
537    }
538  }
539
540  Diag(MemberLoc, diag::err_property_not_found)
541    << MemberName << QualType(OPT, 0);
542  if (Setter)
543    Diag(Setter->getLocation(), diag::note_getter_unavailable)
544          << MemberName << BaseExpr->getSourceRange();
545  return ExprError();
546}
547
548
549
550ExprResult Sema::
551ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
552                          IdentifierInfo &propertyName,
553                          SourceLocation receiverNameLoc,
554                          SourceLocation propertyNameLoc) {
555
556  IdentifierInfo *receiverNamePtr = &receiverName;
557  ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
558                                                  receiverNameLoc);
559  if (IFace == 0) {
560    // If the "receiver" is 'super' in a method, handle it as an expression-like
561    // property reference.
562    if (receiverNamePtr->isStr("super")) {
563      if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf()) {
564        if (CurMethod->isInstanceMethod()) {
565          QualType T =
566            Context.getObjCInterfaceType(CurMethod->getClassInterface());
567          T = Context.getObjCObjectPointerType(T);
568
569          return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
570                                           /*BaseExpr*/0, &propertyName,
571                                           propertyNameLoc,
572                                           receiverNameLoc, T, true);
573        }
574
575        // Otherwise, if this is a class method, try dispatching to our
576        // superclass.
577        IFace = CurMethod->getClassInterface()->getSuperClass();
578      }
579    }
580
581    if (IFace == 0) {
582      Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
583      return ExprError();
584    }
585  }
586
587  // Search for a declared property first.
588  Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
589  ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
590
591  // If this reference is in an @implementation, check for 'private' methods.
592  if (!Getter)
593    if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
594      if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
595        if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
596          Getter = ImpDecl->getClassMethod(Sel);
597
598  if (Getter) {
599    // FIXME: refactor/share with ActOnMemberReference().
600    // Check if we can reference this property.
601    if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
602      return ExprError();
603  }
604
605  // Look for the matching setter, in case it is needed.
606  Selector SetterSel =
607    SelectorTable::constructSetterName(PP.getIdentifierTable(),
608                                       PP.getSelectorTable(), &propertyName);
609
610  ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
611  if (!Setter) {
612    // If this reference is in an @implementation, also check for 'private'
613    // methods.
614    if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
615      if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
616        if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
617          Setter = ImpDecl->getClassMethod(SetterSel);
618  }
619  // Look through local category implementations associated with the class.
620  if (!Setter)
621    Setter = IFace->getCategoryClassMethod(SetterSel);
622
623  if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
624    return ExprError();
625
626  if (Getter || Setter) {
627    QualType PType;
628
629    ExprValueKind VK = VK_LValue;
630    if (Getter) {
631      PType = Getter->getSendResultType();
632      if (!getLangOptions().CPlusPlus &&
633          !PType.hasQualifiers() && PType->isVoidType())
634        VK = VK_RValue;
635    } else {
636      for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
637           E = Setter->param_end(); PI != E; ++PI)
638        PType = (*PI)->getType();
639      VK = VK_LValue;
640    }
641
642    ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
643
644    return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
645                                                   PType, VK, OK,
646                                                   propertyNameLoc,
647                                                   receiverNameLoc, IFace));
648  }
649  return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
650                     << &propertyName << Context.getObjCInterfaceType(IFace));
651}
652
653Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
654                                               IdentifierInfo *Name,
655                                               SourceLocation NameLoc,
656                                               bool IsSuper,
657                                               bool HasTrailingDot,
658                                               ParsedType &ReceiverType) {
659  ReceiverType = ParsedType();
660
661  // If the identifier is "super" and there is no trailing dot, we're
662  // messaging super. If the identifier is "super" and there is a
663  // trailing dot, it's an instance message.
664  if (IsSuper && S->isInObjcMethodScope())
665    return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
666
667  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
668  LookupName(Result, S);
669
670  switch (Result.getResultKind()) {
671  case LookupResult::NotFound:
672    // Normal name lookup didn't find anything. If we're in an
673    // Objective-C method, look for ivars. If we find one, we're done!
674    // FIXME: This is a hack. Ivar lookup should be part of normal
675    // lookup.
676    if (ObjCMethodDecl *Method = getCurMethodDecl()) {
677      ObjCInterfaceDecl *ClassDeclared;
678      if (Method->getClassInterface()->lookupInstanceVariable(Name,
679                                                              ClassDeclared))
680        return ObjCInstanceMessage;
681    }
682
683    // Break out; we'll perform typo correction below.
684    break;
685
686  case LookupResult::NotFoundInCurrentInstantiation:
687  case LookupResult::FoundOverloaded:
688  case LookupResult::FoundUnresolvedValue:
689  case LookupResult::Ambiguous:
690    Result.suppressDiagnostics();
691    return ObjCInstanceMessage;
692
693  case LookupResult::Found: {
694    // If the identifier is a class or not, and there is a trailing dot,
695    // it's an instance message.
696    if (HasTrailingDot)
697      return ObjCInstanceMessage;
698    // We found something. If it's a type, then we have a class
699    // message. Otherwise, it's an instance message.
700    NamedDecl *ND = Result.getFoundDecl();
701    QualType T;
702    if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
703      T = Context.getObjCInterfaceType(Class);
704    else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
705      T = Context.getTypeDeclType(Type);
706    else
707      return ObjCInstanceMessage;
708
709    //  We have a class message, and T is the type we're
710    //  messaging. Build source-location information for it.
711    TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
712    ReceiverType = CreateParsedType(T, TSInfo);
713    return ObjCClassMessage;
714  }
715  }
716
717  // Determine our typo-correction context.
718  CorrectTypoContext CTC = CTC_Expression;
719  if (ObjCMethodDecl *Method = getCurMethodDecl())
720    if (Method->getClassInterface() &&
721        Method->getClassInterface()->getSuperClass())
722      CTC = CTC_ObjCMessageReceiver;
723
724  if (DeclarationName Corrected = CorrectTypo(Result, S, 0, 0, false, CTC)) {
725    if (Result.isSingleResult()) {
726      // If we found a declaration, correct when it refers to an Objective-C
727      // class.
728      NamedDecl *ND = Result.getFoundDecl();
729      if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
730        Diag(NameLoc, diag::err_unknown_receiver_suggest)
731          << Name << Result.getLookupName()
732          << FixItHint::CreateReplacement(SourceRange(NameLoc),
733                                          ND->getNameAsString());
734        Diag(ND->getLocation(), diag::note_previous_decl)
735          << Corrected;
736
737        QualType T = Context.getObjCInterfaceType(Class);
738        TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
739        ReceiverType = CreateParsedType(T, TSInfo);
740        return ObjCClassMessage;
741      }
742    } else if (Result.empty() && Corrected.getAsIdentifierInfo() &&
743               Corrected.getAsIdentifierInfo()->isStr("super")) {
744      // If we've found the keyword "super", this is a send to super.
745      Diag(NameLoc, diag::err_unknown_receiver_suggest)
746        << Name << Corrected
747        << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
748      return ObjCSuperMessage;
749    }
750  }
751
752  // Fall back: let the parser try to parse it as an instance message.
753  return ObjCInstanceMessage;
754}
755
756ExprResult Sema::ActOnSuperMessage(Scope *S,
757                                   SourceLocation SuperLoc,
758                                   Selector Sel,
759                                   SourceLocation LBracLoc,
760                                   SourceLocation SelectorLoc,
761                                   SourceLocation RBracLoc,
762                                   MultiExprArg Args) {
763  // Determine whether we are inside a method or not.
764  ObjCMethodDecl *Method = tryCaptureObjCSelf();
765  if (!Method) {
766    Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
767    return ExprError();
768  }
769
770  ObjCInterfaceDecl *Class = Method->getClassInterface();
771  if (!Class) {
772    Diag(SuperLoc, diag::error_no_super_class_message)
773      << Method->getDeclName();
774    return ExprError();
775  }
776
777  ObjCInterfaceDecl *Super = Class->getSuperClass();
778  if (!Super) {
779    // The current class does not have a superclass.
780    Diag(SuperLoc, diag::error_root_class_cannot_use_super)
781      << Class->getIdentifier();
782    return ExprError();
783  }
784
785  // We are in a method whose class has a superclass, so 'super'
786  // is acting as a keyword.
787  if (Method->isInstanceMethod()) {
788    // Since we are in an instance method, this is an instance
789    // message to the superclass instance.
790    QualType SuperTy = Context.getObjCInterfaceType(Super);
791    SuperTy = Context.getObjCObjectPointerType(SuperTy);
792    return BuildInstanceMessage(0, SuperTy, SuperLoc,
793                                Sel, /*Method=*/0,
794                                LBracLoc, SelectorLoc, RBracLoc, move(Args));
795  }
796
797  // Since we are in a class method, this is a class message to
798  // the superclass.
799  return BuildClassMessage(/*ReceiverTypeInfo=*/0,
800                           Context.getObjCInterfaceType(Super),
801                           SuperLoc, Sel, /*Method=*/0,
802                           LBracLoc, SelectorLoc, RBracLoc, move(Args));
803}
804
805/// \brief Build an Objective-C class message expression.
806///
807/// This routine takes care of both normal class messages and
808/// class messages to the superclass.
809///
810/// \param ReceiverTypeInfo Type source information that describes the
811/// receiver of this message. This may be NULL, in which case we are
812/// sending to the superclass and \p SuperLoc must be a valid source
813/// location.
814
815/// \param ReceiverType The type of the object receiving the
816/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
817/// type as that refers to. For a superclass send, this is the type of
818/// the superclass.
819///
820/// \param SuperLoc The location of the "super" keyword in a
821/// superclass message.
822///
823/// \param Sel The selector to which the message is being sent.
824///
825/// \param Method The method that this class message is invoking, if
826/// already known.
827///
828/// \param LBracLoc The location of the opening square bracket ']'.
829///
830/// \param RBrac The location of the closing square bracket ']'.
831///
832/// \param Args The message arguments.
833ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
834                                   QualType ReceiverType,
835                                   SourceLocation SuperLoc,
836                                   Selector Sel,
837                                   ObjCMethodDecl *Method,
838                                   SourceLocation LBracLoc,
839                                   SourceLocation SelectorLoc,
840                                   SourceLocation RBracLoc,
841                                   MultiExprArg ArgsIn) {
842  SourceLocation Loc = SuperLoc.isValid()? SuperLoc
843    : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
844  if (LBracLoc.isInvalid()) {
845    Diag(Loc, diag::err_missing_open_square_message_send)
846      << FixItHint::CreateInsertion(Loc, "[");
847    LBracLoc = Loc;
848  }
849
850  if (ReceiverType->isDependentType()) {
851    // If the receiver type is dependent, we can't type-check anything
852    // at this point. Build a dependent expression.
853    unsigned NumArgs = ArgsIn.size();
854    Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
855    assert(SuperLoc.isInvalid() && "Message to super with dependent type");
856    return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
857                                         VK_RValue, LBracLoc, ReceiverTypeInfo,
858                                         Sel, SelectorLoc, /*Method=*/0,
859                                         Args, NumArgs, RBracLoc));
860  }
861
862  // Find the class to which we are sending this message.
863  ObjCInterfaceDecl *Class = 0;
864  const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
865  if (!ClassType || !(Class = ClassType->getInterface())) {
866    Diag(Loc, diag::err_invalid_receiver_class_message)
867      << ReceiverType;
868    return ExprError();
869  }
870  assert(Class && "We don't know which class we're messaging?");
871
872  // Find the method we are messaging.
873  if (!Method) {
874    if (Class->isForwardDecl()) {
875      // A forward class used in messaging is treated as a 'Class'
876      Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
877      Method = LookupFactoryMethodInGlobalPool(Sel,
878                                               SourceRange(LBracLoc, RBracLoc));
879      if (Method)
880        Diag(Method->getLocation(), diag::note_method_sent_forward_class)
881          << Method->getDeclName();
882    }
883    if (!Method)
884      Method = Class->lookupClassMethod(Sel);
885
886    // If we have an implementation in scope, check "private" methods.
887    if (!Method)
888      Method = LookupPrivateClassMethod(Sel, Class);
889
890    if (Method && DiagnoseUseOfDecl(Method, Loc))
891      return ExprError();
892  }
893
894  // Check the argument types and determine the result type.
895  QualType ReturnType;
896  ExprValueKind VK = VK_RValue;
897
898  unsigned NumArgs = ArgsIn.size();
899  Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
900  if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, true,
901                                LBracLoc, RBracLoc, ReturnType, VK))
902    return ExprError();
903
904  if (Method && !Method->getResultType()->isVoidType() &&
905      RequireCompleteType(LBracLoc, Method->getResultType(),
906                          diag::err_illegal_message_expr_incomplete_type))
907    return ExprError();
908
909  // Construct the appropriate ObjCMessageExpr.
910  Expr *Result;
911  if (SuperLoc.isValid())
912    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
913                                     SuperLoc, /*IsInstanceSuper=*/false,
914                                     ReceiverType, Sel, SelectorLoc,
915                                     Method, Args, NumArgs, RBracLoc);
916  else
917    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
918                                     ReceiverTypeInfo, Sel, SelectorLoc,
919                                     Method, Args, NumArgs, RBracLoc);
920  return MaybeBindToTemporary(Result);
921}
922
923// ActOnClassMessage - used for both unary and keyword messages.
924// ArgExprs is optional - if it is present, the number of expressions
925// is obtained from Sel.getNumArgs().
926ExprResult Sema::ActOnClassMessage(Scope *S,
927                                   ParsedType Receiver,
928                                   Selector Sel,
929                                   SourceLocation LBracLoc,
930                                   SourceLocation SelectorLoc,
931                                   SourceLocation RBracLoc,
932                                   MultiExprArg Args) {
933  TypeSourceInfo *ReceiverTypeInfo;
934  QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
935  if (ReceiverType.isNull())
936    return ExprError();
937
938
939  if (!ReceiverTypeInfo)
940    ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
941
942  return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
943                           /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
944                           LBracLoc, SelectorLoc, RBracLoc, move(Args));
945}
946
947/// \brief Build an Objective-C instance message expression.
948///
949/// This routine takes care of both normal instance messages and
950/// instance messages to the superclass instance.
951///
952/// \param Receiver The expression that computes the object that will
953/// receive this message. This may be empty, in which case we are
954/// sending to the superclass instance and \p SuperLoc must be a valid
955/// source location.
956///
957/// \param ReceiverType The (static) type of the object receiving the
958/// message. When a \p Receiver expression is provided, this is the
959/// same type as that expression. For a superclass instance send, this
960/// is a pointer to the type of the superclass.
961///
962/// \param SuperLoc The location of the "super" keyword in a
963/// superclass instance message.
964///
965/// \param Sel The selector to which the message is being sent.
966///
967/// \param Method The method that this instance message is invoking, if
968/// already known.
969///
970/// \param LBracLoc The location of the opening square bracket ']'.
971///
972/// \param RBrac The location of the closing square bracket ']'.
973///
974/// \param Args The message arguments.
975ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
976                                      QualType ReceiverType,
977                                      SourceLocation SuperLoc,
978                                      Selector Sel,
979                                      ObjCMethodDecl *Method,
980                                      SourceLocation LBracLoc,
981                                      SourceLocation SelectorLoc,
982                                      SourceLocation RBracLoc,
983                                      MultiExprArg ArgsIn) {
984  // The location of the receiver.
985  SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
986
987  if (LBracLoc.isInvalid()) {
988    Diag(Loc, diag::err_missing_open_square_message_send)
989      << FixItHint::CreateInsertion(Loc, "[");
990    LBracLoc = Loc;
991  }
992
993  // If we have a receiver expression, perform appropriate promotions
994  // and determine receiver type.
995  if (Receiver) {
996    if (Receiver->isTypeDependent()) {
997      // If the receiver is type-dependent, we can't type-check anything
998      // at this point. Build a dependent expression.
999      unsigned NumArgs = ArgsIn.size();
1000      Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1001      assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1002      return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
1003                                           VK_RValue, LBracLoc, Receiver, Sel,
1004                                           SelectorLoc, /*Method=*/0,
1005                                           Args, NumArgs, RBracLoc));
1006    }
1007
1008    // If necessary, apply function/array conversion to the receiver.
1009    // C99 6.7.5.3p[7,8].
1010    DefaultFunctionArrayLvalueConversion(Receiver);
1011    ReceiverType = Receiver->getType();
1012  }
1013
1014  if (!Method) {
1015    // Handle messages to id.
1016    bool receiverIsId = ReceiverType->isObjCIdType();
1017    if (receiverIsId || ReceiverType->isBlockPointerType() ||
1018        (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1019      Method = LookupInstanceMethodInGlobalPool(Sel,
1020                                                SourceRange(LBracLoc, RBracLoc),
1021                                                receiverIsId);
1022      if (!Method)
1023        Method = LookupFactoryMethodInGlobalPool(Sel,
1024                                                 SourceRange(LBracLoc, RBracLoc),
1025                                                 receiverIsId);
1026    } else if (ReceiverType->isObjCClassType() ||
1027               ReceiverType->isObjCQualifiedClassType()) {
1028      // Handle messages to Class.
1029      if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1030        if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1031          // First check the public methods in the class interface.
1032          Method = ClassDecl->lookupClassMethod(Sel);
1033
1034          if (!Method)
1035            Method = LookupPrivateClassMethod(Sel, ClassDecl);
1036
1037          // FIXME: if we still haven't found a method, we need to look in
1038          // protocols (if we have qualifiers).
1039        }
1040        if (Method && DiagnoseUseOfDecl(Method, Loc))
1041          return ExprError();
1042      }
1043      if (!Method) {
1044        // If not messaging 'self', look for any factory method named 'Sel'.
1045        if (!Receiver || !isSelfExpr(Receiver)) {
1046          Method = LookupFactoryMethodInGlobalPool(Sel,
1047                                               SourceRange(LBracLoc, RBracLoc),
1048                                                   true);
1049          if (!Method) {
1050            // If no class (factory) method was found, check if an _instance_
1051            // method of the same name exists in the root class only.
1052            Method = LookupInstanceMethodInGlobalPool(Sel,
1053                                               SourceRange(LBracLoc, RBracLoc),
1054                                                      true);
1055            if (Method)
1056                if (const ObjCInterfaceDecl *ID =
1057                  dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1058                if (ID->getSuperClass())
1059                  Diag(Loc, diag::warn_root_inst_method_not_found)
1060                    << Sel << SourceRange(LBracLoc, RBracLoc);
1061              }
1062          }
1063        }
1064      }
1065    } else {
1066      ObjCInterfaceDecl* ClassDecl = 0;
1067
1068      // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1069      // long as one of the protocols implements the selector (if not, warn).
1070      if (const ObjCObjectPointerType *QIdTy
1071                                   = ReceiverType->getAsObjCQualifiedIdType()) {
1072        // Search protocols for instance methods.
1073        for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
1074               E = QIdTy->qual_end(); I != E; ++I) {
1075          ObjCProtocolDecl *PDecl = *I;
1076          if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
1077            break;
1078          // Since we aren't supporting "Class<foo>", look for a class method.
1079          if (PDecl && (Method = PDecl->lookupClassMethod(Sel)))
1080            break;
1081        }
1082      } else if (const ObjCObjectPointerType *OCIType
1083                   = ReceiverType->getAsObjCInterfacePointerType()) {
1084        // We allow sending a message to a pointer to an interface (an object).
1085        ClassDecl = OCIType->getInterfaceDecl();
1086        // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
1087        // faster than the following method (which can do *many* linear searches).
1088        // The idea is to add class info to MethodPool.
1089        Method = ClassDecl->lookupInstanceMethod(Sel);
1090
1091        if (!Method) {
1092          // Search protocol qualifiers.
1093          for (ObjCObjectPointerType::qual_iterator QI = OCIType->qual_begin(),
1094                 E = OCIType->qual_end(); QI != E; ++QI) {
1095            if ((Method = (*QI)->lookupInstanceMethod(Sel)))
1096              break;
1097          }
1098        }
1099        bool forwardClass = false;
1100        if (!Method) {
1101          // If we have implementations in scope, check "private" methods.
1102          Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1103
1104          if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
1105            // If we still haven't found a method, look in the global pool. This
1106            // behavior isn't very desirable, however we need it for GCC
1107            // compatibility. FIXME: should we deviate??
1108            if (OCIType->qual_empty()) {
1109              Method = LookupInstanceMethodInGlobalPool(Sel,
1110                                                 SourceRange(LBracLoc, RBracLoc));
1111              forwardClass = OCIType->getInterfaceDecl()->isForwardDecl();
1112              if (Method && !forwardClass)
1113                Diag(Loc, diag::warn_maynot_respond)
1114                  << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1115            }
1116          }
1117        }
1118        if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
1119          return ExprError();
1120      } else if (!Context.getObjCIdType().isNull() &&
1121                 (ReceiverType->isPointerType() ||
1122                  ReceiverType->isIntegerType())) {
1123        // Implicitly convert integers and pointers to 'id' but emit a warning.
1124        Diag(Loc, diag::warn_bad_receiver_type)
1125          << ReceiverType
1126          << Receiver->getSourceRange();
1127        if (ReceiverType->isPointerType())
1128          ImpCastExprToType(Receiver, Context.getObjCIdType(),
1129                            CK_BitCast);
1130        else {
1131          // TODO: specialized warning on null receivers?
1132          bool IsNull = Receiver->isNullPointerConstant(Context,
1133                                              Expr::NPC_ValueDependentIsNull);
1134          ImpCastExprToType(Receiver, Context.getObjCIdType(),
1135                            IsNull ? CK_NullToPointer : CK_IntegralToPointer);
1136        }
1137        ReceiverType = Receiver->getType();
1138      }
1139      else if (getLangOptions().CPlusPlus &&
1140               !PerformContextuallyConvertToObjCId(Receiver)) {
1141        if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
1142          Receiver = ICE->getSubExpr();
1143          ReceiverType = Receiver->getType();
1144        }
1145        return BuildInstanceMessage(Receiver,
1146                                    ReceiverType,
1147                                    SuperLoc,
1148                                    Sel,
1149                                    Method,
1150                                    LBracLoc,
1151                                    SelectorLoc,
1152                                    RBracLoc,
1153                                    move(ArgsIn));
1154      } else {
1155        // Reject other random receiver types (e.g. structs).
1156        Diag(Loc, diag::err_bad_receiver_type)
1157          << ReceiverType << Receiver->getSourceRange();
1158        return ExprError();
1159      }
1160    }
1161  }
1162
1163  // Check the message arguments.
1164  unsigned NumArgs = ArgsIn.size();
1165  Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1166  QualType ReturnType;
1167  ExprValueKind VK = VK_RValue;
1168  bool ClassMessage = (ReceiverType->isObjCClassType() ||
1169                       ReceiverType->isObjCQualifiedClassType());
1170  if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, ClassMessage,
1171                                LBracLoc, RBracLoc, ReturnType, VK))
1172    return ExprError();
1173
1174  if (Method && !Method->getResultType()->isVoidType() &&
1175      RequireCompleteType(LBracLoc, Method->getResultType(),
1176                          diag::err_illegal_message_expr_incomplete_type))
1177    return ExprError();
1178
1179  // Construct the appropriate ObjCMessageExpr instance.
1180  Expr *Result;
1181  if (SuperLoc.isValid())
1182    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1183                                     SuperLoc,  /*IsInstanceSuper=*/true,
1184                                     ReceiverType, Sel, SelectorLoc, Method,
1185                                     Args, NumArgs, RBracLoc);
1186  else
1187    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1188                                     Receiver, Sel, SelectorLoc, Method,
1189                                     Args, NumArgs, RBracLoc);
1190  return MaybeBindToTemporary(Result);
1191}
1192
1193// ActOnInstanceMessage - used for both unary and keyword messages.
1194// ArgExprs is optional - if it is present, the number of expressions
1195// is obtained from Sel.getNumArgs().
1196ExprResult Sema::ActOnInstanceMessage(Scope *S,
1197                                      Expr *Receiver,
1198                                      Selector Sel,
1199                                      SourceLocation LBracLoc,
1200                                      SourceLocation SelectorLoc,
1201                                      SourceLocation RBracLoc,
1202                                      MultiExprArg Args) {
1203  if (!Receiver)
1204    return ExprError();
1205
1206  return BuildInstanceMessage(Receiver, Receiver->getType(),
1207                              /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
1208                              LBracLoc, SelectorLoc, RBracLoc, move(Args));
1209}
1210
1211