SemaExprObjC.cpp revision f85e193739c953358c865005855253af4f68a497
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/StmtVisitor.h"
23#include "clang/AST/TypeLoc.h"
24#include "llvm/ADT/SmallString.h"
25#include "clang/Lex/Preprocessor.h"
26
27using namespace clang;
28using namespace sema;
29
30ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
31                                        Expr **strings,
32                                        unsigned NumStrings) {
33  StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
34
35  // Most ObjC strings are formed out of a single piece.  However, we *can*
36  // have strings formed out of multiple @ strings with multiple pptokens in
37  // each one, e.g. @"foo" "bar" @"baz" "qux"   which need to be turned into one
38  // StringLiteral for ObjCStringLiteral to hold onto.
39  StringLiteral *S = Strings[0];
40
41  // If we have a multi-part string, merge it all together.
42  if (NumStrings != 1) {
43    // Concatenate objc strings.
44    llvm::SmallString<128> StrBuf;
45    llvm::SmallVector<SourceLocation, 8> StrLocs;
46
47    for (unsigned i = 0; i != NumStrings; ++i) {
48      S = Strings[i];
49
50      // ObjC strings can't be wide.
51      if (S->isWide()) {
52        Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
53          << S->getSourceRange();
54        return true;
55      }
56
57      // Append the string.
58      StrBuf += S->getString();
59
60      // Get the locations of the string tokens.
61      StrLocs.append(S->tokloc_begin(), S->tokloc_end());
62    }
63
64    // Create the aggregate string with the appropriate content and location
65    // information.
66    S = StringLiteral::Create(Context, &StrBuf[0], StrBuf.size(),
67                              /*Wide=*/false, /*Pascal=*/false,
68                              Context.getPointerType(Context.CharTy),
69                              &StrLocs[0], StrLocs.size());
70  }
71
72  // Verify that this composite string is acceptable for ObjC strings.
73  if (CheckObjCString(S))
74    return true;
75
76  // Initialize the constant string interface lazily. This assumes
77  // the NSString interface is seen in this translation unit. Note: We
78  // don't use NSConstantString, since the runtime team considers this
79  // interface private (even though it appears in the header files).
80  QualType Ty = Context.getObjCConstantStringInterface();
81  if (!Ty.isNull()) {
82    Ty = Context.getObjCObjectPointerType(Ty);
83  } else if (getLangOptions().NoConstantCFStrings) {
84    IdentifierInfo *NSIdent=0;
85    std::string StringClass(getLangOptions().ObjCConstantStringClass);
86
87    if (StringClass.empty())
88      NSIdent = &Context.Idents.get("NSConstantString");
89    else
90      NSIdent = &Context.Idents.get(StringClass);
91
92    NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
93                                     LookupOrdinaryName);
94    if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
95      Context.setObjCConstantStringInterface(StrIF);
96      Ty = Context.getObjCConstantStringInterface();
97      Ty = Context.getObjCObjectPointerType(Ty);
98    } else {
99      // If there is no NSConstantString interface defined then treat this
100      // as error and recover from it.
101      Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
102        << S->getSourceRange();
103      Ty = Context.getObjCIdType();
104    }
105  } else {
106    IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
107    NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
108                                     LookupOrdinaryName);
109    if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
110      Context.setObjCConstantStringInterface(StrIF);
111      Ty = Context.getObjCConstantStringInterface();
112      Ty = Context.getObjCObjectPointerType(Ty);
113    } else {
114      // If there is no NSString interface defined then treat constant
115      // strings as untyped objects and let the runtime figure it out later.
116      Ty = Context.getObjCIdType();
117    }
118  }
119
120  return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
121}
122
123ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
124                                      TypeSourceInfo *EncodedTypeInfo,
125                                      SourceLocation RParenLoc) {
126  QualType EncodedType = EncodedTypeInfo->getType();
127  QualType StrTy;
128  if (EncodedType->isDependentType())
129    StrTy = Context.DependentTy;
130  else {
131    if (!EncodedType->getAsArrayTypeUnsafe()) // Incomplete array is handled.
132      if (RequireCompleteType(AtLoc, EncodedType,
133                         PDiag(diag::err_incomplete_type_objc_at_encode)
134                             << EncodedTypeInfo->getTypeLoc().getSourceRange()))
135        return ExprError();
136
137    std::string Str;
138    Context.getObjCEncodingForType(EncodedType, Str);
139
140    // The type of @encode is the same as the type of the corresponding string,
141    // which is an array type.
142    StrTy = Context.CharTy;
143    // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
144    if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
145      StrTy.addConst();
146    StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
147                                         ArrayType::Normal, 0);
148  }
149
150  return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
151}
152
153ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
154                                           SourceLocation EncodeLoc,
155                                           SourceLocation LParenLoc,
156                                           ParsedType ty,
157                                           SourceLocation RParenLoc) {
158  // FIXME: Preserve type source info ?
159  TypeSourceInfo *TInfo;
160  QualType EncodedType = GetTypeFromParser(ty, &TInfo);
161  if (!TInfo)
162    TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
163                                             PP.getLocForEndOfToken(LParenLoc));
164
165  return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
166}
167
168ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
169                                             SourceLocation AtLoc,
170                                             SourceLocation SelLoc,
171                                             SourceLocation LParenLoc,
172                                             SourceLocation RParenLoc) {
173  ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
174                             SourceRange(LParenLoc, RParenLoc), false, false);
175  if (!Method)
176    Method = LookupFactoryMethodInGlobalPool(Sel,
177                                          SourceRange(LParenLoc, RParenLoc));
178  if (!Method)
179    Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
180
181  llvm::DenseMap<Selector, SourceLocation>::iterator Pos
182    = ReferencedSelectors.find(Sel);
183  if (Pos == ReferencedSelectors.end())
184    ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
185
186  // In ARC, forbid the user from using @selector for
187  // retain/release/autorelease/dealloc/retainCount.
188  if (getLangOptions().ObjCAutoRefCount) {
189    switch (Sel.getMethodFamily()) {
190    case OMF_retain:
191    case OMF_release:
192    case OMF_autorelease:
193    case OMF_retainCount:
194    case OMF_dealloc:
195      Diag(AtLoc, diag::err_arc_illegal_selector) <<
196        Sel << SourceRange(LParenLoc, RParenLoc);
197      break;
198
199    case OMF_None:
200    case OMF_alloc:
201    case OMF_copy:
202    case OMF_init:
203    case OMF_mutableCopy:
204    case OMF_new:
205    case OMF_self:
206      break;
207    }
208  }
209  QualType Ty = Context.getObjCSelType();
210  return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
211}
212
213ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
214                                             SourceLocation AtLoc,
215                                             SourceLocation ProtoLoc,
216                                             SourceLocation LParenLoc,
217                                             SourceLocation RParenLoc) {
218  ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
219  if (!PDecl) {
220    Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
221    return true;
222  }
223
224  QualType Ty = Context.getObjCProtoType();
225  if (Ty.isNull())
226    return true;
227  Ty = Context.getObjCObjectPointerType(Ty);
228  return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
229}
230
231/// Try to capture an implicit reference to 'self'.
232ObjCMethodDecl *Sema::tryCaptureObjCSelf() {
233  // Ignore block scopes: we can capture through them.
234  DeclContext *DC = CurContext;
235  while (true) {
236    if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
237    else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
238    else break;
239  }
240
241  // If we're not in an ObjC method, error out.  Note that, unlike the
242  // C++ case, we don't require an instance method --- class methods
243  // still have a 'self', and we really do still need to capture it!
244  ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
245  if (!method)
246    return 0;
247
248  ImplicitParamDecl *self = method->getSelfDecl();
249  assert(self && "capturing 'self' in non-definition?");
250
251  // Mark that we're closing on 'this' in all the block scopes, if applicable.
252  for (unsigned idx = FunctionScopes.size() - 1;
253       isa<BlockScopeInfo>(FunctionScopes[idx]);
254       --idx) {
255    BlockScopeInfo *blockScope = cast<BlockScopeInfo>(FunctionScopes[idx]);
256    unsigned &captureIndex = blockScope->CaptureMap[self];
257    if (captureIndex) break;
258
259    bool nested = isa<BlockScopeInfo>(FunctionScopes[idx-1]);
260    blockScope->Captures.push_back(
261              BlockDecl::Capture(self, /*byref*/ false, nested, /*copy*/ 0));
262    captureIndex = blockScope->Captures.size(); // +1
263  }
264
265  return method;
266}
267
268QualType Sema::getMessageSendResultType(QualType ReceiverType,
269                                        ObjCMethodDecl *Method,
270                                    bool isClassMessage, bool isSuperMessage) {
271  assert(Method && "Must have a method");
272  if (!Method->hasRelatedResultType())
273    return Method->getSendResultType();
274
275  // If a method has a related return type:
276  //   - if the method found is an instance method, but the message send
277  //     was a class message send, T is the declared return type of the method
278  //     found
279  if (Method->isInstanceMethod() && isClassMessage)
280    return Method->getSendResultType();
281
282  //   - if the receiver is super, T is a pointer to the class of the
283  //     enclosing method definition
284  if (isSuperMessage) {
285    if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
286      if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
287        return Context.getObjCObjectPointerType(
288                                        Context.getObjCInterfaceType(Class));
289  }
290
291  //   - if the receiver is the name of a class U, T is a pointer to U
292  if (ReceiverType->getAs<ObjCInterfaceType>() ||
293      ReceiverType->isObjCQualifiedInterfaceType())
294    return Context.getObjCObjectPointerType(ReceiverType);
295  //   - if the receiver is of type Class or qualified Class type,
296  //     T is the declared return type of the method.
297  if (ReceiverType->isObjCClassType() ||
298      ReceiverType->isObjCQualifiedClassType())
299    return  Method->getSendResultType();
300
301  //   - if the receiver is id, qualified id, Class, or qualified Class, T
302  //     is the receiver type, otherwise
303  //   - T is the type of the receiver expression.
304  return ReceiverType;
305}
306
307void Sema::EmitRelatedResultTypeNote(const Expr *E) {
308  E = E->IgnoreParenImpCasts();
309  const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
310  if (!MsgSend)
311    return;
312
313  const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
314  if (!Method)
315    return;
316
317  if (!Method->hasRelatedResultType())
318    return;
319
320  if (Context.hasSameUnqualifiedType(Method->getResultType()
321                                                        .getNonReferenceType(),
322                                     MsgSend->getType()))
323    return;
324
325  Diag(Method->getLocation(), diag::note_related_result_type_inferred)
326    << Method->isInstanceMethod() << Method->getSelector()
327    << MsgSend->getType();
328}
329
330bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
331                                     Expr **Args, unsigned NumArgs,
332                                     Selector Sel, ObjCMethodDecl *Method,
333                                     bool isClassMessage, bool isSuperMessage,
334                                     SourceLocation lbrac, SourceLocation rbrac,
335                                     QualType &ReturnType, ExprValueKind &VK) {
336  if (!Method) {
337    // Apply default argument promotion as for (C99 6.5.2.2p6).
338    for (unsigned i = 0; i != NumArgs; i++) {
339      if (Args[i]->isTypeDependent())
340        continue;
341
342      ExprResult Result = DefaultArgumentPromotion(Args[i]);
343      if (Result.isInvalid())
344        return true;
345      Args[i] = Result.take();
346    }
347
348    unsigned DiagID;
349    if (getLangOptions().ObjCAutoRefCount)
350      DiagID = diag::err_arc_method_not_found;
351    else
352      DiagID = isClassMessage ? diag::warn_class_method_not_found
353                              : diag::warn_inst_method_not_found;
354    Diag(lbrac, DiagID)
355      << Sel << isClassMessage << SourceRange(lbrac, rbrac);
356    ReturnType = Context.getObjCIdType();
357    VK = VK_RValue;
358    return false;
359  }
360
361  ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
362                                        isSuperMessage);
363  VK = Expr::getValueKindForType(Method->getResultType());
364
365  unsigned NumNamedArgs = Sel.getNumArgs();
366  // Method might have more arguments than selector indicates. This is due
367  // to addition of c-style arguments in method.
368  if (Method->param_size() > Sel.getNumArgs())
369    NumNamedArgs = Method->param_size();
370  // FIXME. This need be cleaned up.
371  if (NumArgs < NumNamedArgs) {
372    Diag(lbrac, diag::err_typecheck_call_too_few_args)
373      << 2 << NumNamedArgs << NumArgs;
374    return false;
375  }
376
377  bool IsError = false;
378  for (unsigned i = 0; i < NumNamedArgs; i++) {
379    // We can't do any type-checking on a type-dependent argument.
380    if (Args[i]->isTypeDependent())
381      continue;
382
383    Expr *argExpr = Args[i];
384
385    ParmVarDecl *Param = Method->param_begin()[i];
386    assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
387
388    if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
389                            Param->getType(),
390                            PDiag(diag::err_call_incomplete_argument)
391                              << argExpr->getSourceRange()))
392      return true;
393
394    InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
395                                                                      Param);
396    ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
397    if (ArgE.isInvalid())
398      IsError = true;
399    else
400      Args[i] = ArgE.takeAs<Expr>();
401  }
402
403  // Promote additional arguments to variadic methods.
404  if (Method->isVariadic()) {
405    for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
406      if (Args[i]->isTypeDependent())
407        continue;
408
409      ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
410      IsError |= Arg.isInvalid();
411      Args[i] = Arg.take();
412    }
413  } else {
414    // Check for extra arguments to non-variadic methods.
415    if (NumArgs != NumNamedArgs) {
416      Diag(Args[NumNamedArgs]->getLocStart(),
417           diag::err_typecheck_call_too_many_args)
418        << 2 /*method*/ << NumNamedArgs << NumArgs
419        << Method->getSourceRange()
420        << SourceRange(Args[NumNamedArgs]->getLocStart(),
421                       Args[NumArgs-1]->getLocEnd());
422    }
423  }
424  // diagnose nonnull arguments.
425  for (specific_attr_iterator<NonNullAttr>
426       i = Method->specific_attr_begin<NonNullAttr>(),
427       e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
428    CheckNonNullArguments(*i, Args, lbrac);
429  }
430
431  DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
432  return IsError;
433}
434
435bool Sema::isSelfExpr(Expr *receiver) {
436  // 'self' is objc 'self' in an objc method only.
437  DeclContext *DC = CurContext;
438  while (isa<BlockDecl>(DC))
439    DC = DC->getParent();
440  if (DC && !isa<ObjCMethodDecl>(DC))
441    return false;
442  receiver = receiver->IgnoreParenLValueCasts();
443  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
444    if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
445      return true;
446  return false;
447}
448
449// Helper method for ActOnClassMethod/ActOnInstanceMethod.
450// Will search "local" class/category implementations for a method decl.
451// If failed, then we search in class's root for an instance method.
452// Returns 0 if no method is found.
453ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
454                                          ObjCInterfaceDecl *ClassDecl) {
455  ObjCMethodDecl *Method = 0;
456  // lookup in class and all superclasses
457  while (ClassDecl && !Method) {
458    if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
459      Method = ImpDecl->getClassMethod(Sel);
460
461    // Look through local category implementations associated with the class.
462    if (!Method)
463      Method = ClassDecl->getCategoryClassMethod(Sel);
464
465    // Before we give up, check if the selector is an instance method.
466    // But only in the root. This matches gcc's behaviour and what the
467    // runtime expects.
468    if (!Method && !ClassDecl->getSuperClass()) {
469      Method = ClassDecl->lookupInstanceMethod(Sel);
470      // Look through local category implementations associated
471      // with the root class.
472      if (!Method)
473        Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
474    }
475
476    ClassDecl = ClassDecl->getSuperClass();
477  }
478  return Method;
479}
480
481ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
482                                              ObjCInterfaceDecl *ClassDecl) {
483  ObjCMethodDecl *Method = 0;
484  while (ClassDecl && !Method) {
485    // If we have implementations in scope, check "private" methods.
486    if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
487      Method = ImpDecl->getInstanceMethod(Sel);
488
489    // Look through local category implementations associated with the class.
490    if (!Method)
491      Method = ClassDecl->getCategoryInstanceMethod(Sel);
492    ClassDecl = ClassDecl->getSuperClass();
493  }
494  return Method;
495}
496
497/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
498/// list of a qualified objective pointer type.
499ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
500                                              const ObjCObjectPointerType *OPT,
501                                              bool Instance)
502{
503  ObjCMethodDecl *MD = 0;
504  for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
505       E = OPT->qual_end(); I != E; ++I) {
506    ObjCProtocolDecl *PROTO = (*I);
507    if ((MD = PROTO->lookupMethod(Sel, Instance))) {
508      return MD;
509    }
510  }
511  return 0;
512}
513
514/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
515/// objective C interface.  This is a property reference expression.
516ExprResult Sema::
517HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
518                          Expr *BaseExpr, DeclarationName MemberName,
519                          SourceLocation MemberLoc,
520                          SourceLocation SuperLoc, QualType SuperType,
521                          bool Super) {
522  const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
523  ObjCInterfaceDecl *IFace = IFaceT->getDecl();
524
525  if (MemberName.getNameKind() != DeclarationName::Identifier) {
526    Diag(MemberLoc, diag::err_invalid_property_name)
527      << MemberName << QualType(OPT, 0);
528    return ExprError();
529  }
530
531  IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
532
533  if (IFace->isForwardDecl()) {
534    Diag(MemberLoc, diag::err_property_not_found_forward_class)
535         << MemberName << QualType(OPT, 0);
536    Diag(IFace->getLocation(), diag::note_forward_class);
537    return ExprError();
538  }
539  // Search for a declared property first.
540  if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
541    // Check whether we can reference this property.
542    if (DiagnoseUseOfDecl(PD, MemberLoc))
543      return ExprError();
544    QualType ResTy = PD->getType();
545    ResTy = ResTy.getNonLValueExprType(Context);
546    Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
547    ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
548    if (Getter &&
549        (Getter->hasRelatedResultType()
550         || DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc)))
551        ResTy = getMessageSendResultType(QualType(OPT, 0), Getter, false,
552                                         Super);
553
554    if (Super)
555      return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
556                                                     VK_LValue, OK_ObjCProperty,
557                                                     MemberLoc,
558                                                     SuperLoc, SuperType));
559    else
560      return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
561                                                     VK_LValue, OK_ObjCProperty,
562                                                     MemberLoc, BaseExpr));
563  }
564  // Check protocols on qualified interfaces.
565  for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
566       E = OPT->qual_end(); I != E; ++I)
567    if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
568      // Check whether we can reference this property.
569      if (DiagnoseUseOfDecl(PD, MemberLoc))
570        return ExprError();
571
572      QualType T = PD->getType();
573      if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
574        T = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
575      if (Super)
576        return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
577                                                       VK_LValue,
578                                                       OK_ObjCProperty,
579                                                       MemberLoc,
580                                                       SuperLoc, SuperType));
581      else
582        return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
583                                                       VK_LValue,
584                                                       OK_ObjCProperty,
585                                                       MemberLoc,
586                                                       BaseExpr));
587    }
588  // If that failed, look for an "implicit" property by seeing if the nullary
589  // selector is implemented.
590
591  // FIXME: The logic for looking up nullary and unary selectors should be
592  // shared with the code in ActOnInstanceMessage.
593
594  Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
595  ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
596
597  // May be founf in property's qualified list.
598  if (!Getter)
599    Getter = LookupMethodInQualifiedType(Sel, OPT, true);
600
601  // If this reference is in an @implementation, check for 'private' methods.
602  if (!Getter)
603    Getter = IFace->lookupPrivateMethod(Sel);
604
605  // Look through local category implementations associated with the class.
606  if (!Getter)
607    Getter = IFace->getCategoryInstanceMethod(Sel);
608  if (Getter) {
609    // Check if we can reference this property.
610    if (DiagnoseUseOfDecl(Getter, MemberLoc))
611      return ExprError();
612  }
613  // If we found a getter then this may be a valid dot-reference, we
614  // will look for the matching setter, in case it is needed.
615  Selector SetterSel =
616    SelectorTable::constructSetterName(PP.getIdentifierTable(),
617                                       PP.getSelectorTable(), Member);
618  ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
619
620  // May be founf in property's qualified list.
621  if (!Setter)
622    Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
623
624  if (!Setter) {
625    // If this reference is in an @implementation, also check for 'private'
626    // methods.
627    Setter = IFace->lookupPrivateMethod(SetterSel);
628  }
629  // Look through local category implementations associated with the class.
630  if (!Setter)
631    Setter = IFace->getCategoryInstanceMethod(SetterSel);
632
633  if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
634    return ExprError();
635
636  if (Getter || Setter) {
637    QualType PType;
638    if (Getter)
639      PType = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
640    else {
641      ParmVarDecl *ArgDecl = *Setter->param_begin();
642      PType = ArgDecl->getType();
643    }
644
645    ExprValueKind VK = VK_LValue;
646    ExprObjectKind OK = OK_ObjCProperty;
647    if (!getLangOptions().CPlusPlus && !PType.hasQualifiers() &&
648        PType->isVoidType())
649      VK = VK_RValue, OK = OK_Ordinary;
650
651    if (Super)
652      return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
653                                                     PType, VK, OK,
654                                                     MemberLoc,
655                                                     SuperLoc, SuperType));
656    else
657      return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
658                                                     PType, VK, OK,
659                                                     MemberLoc, BaseExpr));
660
661  }
662
663  // Attempt to correct for typos in property names.
664  LookupResult Res(*this, MemberName, MemberLoc, LookupOrdinaryName);
665  if (CorrectTypo(Res, 0, 0, IFace, false, CTC_NoKeywords, OPT) &&
666      Res.getAsSingle<ObjCPropertyDecl>()) {
667    DeclarationName TypoResult = Res.getLookupName();
668    Diag(MemberLoc, diag::err_property_not_found_suggest)
669      << MemberName << QualType(OPT, 0) << TypoResult
670      << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
671    ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
672    Diag(Property->getLocation(), diag::note_previous_decl)
673      << Property->getDeclName();
674    return HandleExprPropertyRefExpr(OPT, BaseExpr, TypoResult, MemberLoc,
675                                     SuperLoc, SuperType, Super);
676  }
677  ObjCInterfaceDecl *ClassDeclared;
678  if (ObjCIvarDecl *Ivar =
679      IFace->lookupInstanceVariable(Member, ClassDeclared)) {
680    QualType T = Ivar->getType();
681    if (const ObjCObjectPointerType * OBJPT =
682        T->getAsObjCInterfacePointerType()) {
683      const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
684      if (ObjCInterfaceDecl *IFace = IFaceT->getDecl())
685        if (IFace->isForwardDecl()) {
686          Diag(MemberLoc, diag::err_property_not_as_forward_class)
687          << MemberName << IFace;
688          Diag(IFace->getLocation(), diag::note_forward_class);
689          return ExprError();
690        }
691    }
692  }
693
694  Diag(MemberLoc, diag::err_property_not_found)
695    << MemberName << QualType(OPT, 0);
696  if (Setter)
697    Diag(Setter->getLocation(), diag::note_getter_unavailable)
698          << MemberName << BaseExpr->getSourceRange();
699  return ExprError();
700}
701
702
703
704ExprResult Sema::
705ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
706                          IdentifierInfo &propertyName,
707                          SourceLocation receiverNameLoc,
708                          SourceLocation propertyNameLoc) {
709
710  IdentifierInfo *receiverNamePtr = &receiverName;
711  ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
712                                                  receiverNameLoc);
713
714  bool IsSuper = false;
715  if (IFace == 0) {
716    // If the "receiver" is 'super' in a method, handle it as an expression-like
717    // property reference.
718    if (receiverNamePtr->isStr("super")) {
719      IsSuper = true;
720
721      if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf()) {
722        if (CurMethod->isInstanceMethod()) {
723          QualType T =
724            Context.getObjCInterfaceType(CurMethod->getClassInterface());
725          T = Context.getObjCObjectPointerType(T);
726
727          return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
728                                           /*BaseExpr*/0, &propertyName,
729                                           propertyNameLoc,
730                                           receiverNameLoc, T, true);
731        }
732
733        // Otherwise, if this is a class method, try dispatching to our
734        // superclass.
735        IFace = CurMethod->getClassInterface()->getSuperClass();
736      }
737    }
738
739    if (IFace == 0) {
740      Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
741      return ExprError();
742    }
743  }
744
745  // Search for a declared property first.
746  Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
747  ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
748
749  // If this reference is in an @implementation, check for 'private' methods.
750  if (!Getter)
751    if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
752      if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
753        if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
754          Getter = ImpDecl->getClassMethod(Sel);
755
756  if (Getter) {
757    // FIXME: refactor/share with ActOnMemberReference().
758    // Check if we can reference this property.
759    if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
760      return ExprError();
761  }
762
763  // Look for the matching setter, in case it is needed.
764  Selector SetterSel =
765    SelectorTable::constructSetterName(PP.getIdentifierTable(),
766                                       PP.getSelectorTable(), &propertyName);
767
768  ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
769  if (!Setter) {
770    // If this reference is in an @implementation, also check for 'private'
771    // methods.
772    if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
773      if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
774        if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
775          Setter = ImpDecl->getClassMethod(SetterSel);
776  }
777  // Look through local category implementations associated with the class.
778  if (!Setter)
779    Setter = IFace->getCategoryClassMethod(SetterSel);
780
781  if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
782    return ExprError();
783
784  if (Getter || Setter) {
785    QualType PType;
786
787    ExprValueKind VK = VK_LValue;
788    if (Getter) {
789      PType = getMessageSendResultType(Context.getObjCInterfaceType(IFace),
790                                       Getter, true,
791                                       receiverNamePtr->isStr("super"));
792      if (!getLangOptions().CPlusPlus &&
793          !PType.hasQualifiers() && PType->isVoidType())
794        VK = VK_RValue;
795    } else {
796      for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
797           E = Setter->param_end(); PI != E; ++PI)
798        PType = (*PI)->getType();
799      VK = VK_LValue;
800    }
801
802    ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
803
804    if (IsSuper)
805    return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
806                                                   PType, VK, OK,
807                                                   propertyNameLoc,
808                                                   receiverNameLoc,
809                                          Context.getObjCInterfaceType(IFace)));
810
811    return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
812                                                   PType, VK, OK,
813                                                   propertyNameLoc,
814                                                   receiverNameLoc, IFace));
815  }
816  return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
817                     << &propertyName << Context.getObjCInterfaceType(IFace));
818}
819
820Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
821                                               IdentifierInfo *Name,
822                                               SourceLocation NameLoc,
823                                               bool IsSuper,
824                                               bool HasTrailingDot,
825                                               ParsedType &ReceiverType) {
826  ReceiverType = ParsedType();
827
828  // If the identifier is "super" and there is no trailing dot, we're
829  // messaging super. If the identifier is "super" and there is a
830  // trailing dot, it's an instance message.
831  if (IsSuper && S->isInObjcMethodScope())
832    return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
833
834  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
835  LookupName(Result, S);
836
837  switch (Result.getResultKind()) {
838  case LookupResult::NotFound:
839    // Normal name lookup didn't find anything. If we're in an
840    // Objective-C method, look for ivars. If we find one, we're done!
841    // FIXME: This is a hack. Ivar lookup should be part of normal
842    // lookup.
843    if (ObjCMethodDecl *Method = getCurMethodDecl()) {
844      ObjCInterfaceDecl *ClassDeclared;
845      if (Method->getClassInterface()->lookupInstanceVariable(Name,
846                                                              ClassDeclared))
847        return ObjCInstanceMessage;
848    }
849
850    // Break out; we'll perform typo correction below.
851    break;
852
853  case LookupResult::NotFoundInCurrentInstantiation:
854  case LookupResult::FoundOverloaded:
855  case LookupResult::FoundUnresolvedValue:
856  case LookupResult::Ambiguous:
857    Result.suppressDiagnostics();
858    return ObjCInstanceMessage;
859
860  case LookupResult::Found: {
861    // If the identifier is a class or not, and there is a trailing dot,
862    // it's an instance message.
863    if (HasTrailingDot)
864      return ObjCInstanceMessage;
865    // We found something. If it's a type, then we have a class
866    // message. Otherwise, it's an instance message.
867    NamedDecl *ND = Result.getFoundDecl();
868    QualType T;
869    if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
870      T = Context.getObjCInterfaceType(Class);
871    else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
872      T = Context.getTypeDeclType(Type);
873    else
874      return ObjCInstanceMessage;
875
876    //  We have a class message, and T is the type we're
877    //  messaging. Build source-location information for it.
878    TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
879    ReceiverType = CreateParsedType(T, TSInfo);
880    return ObjCClassMessage;
881  }
882  }
883
884  // Determine our typo-correction context.
885  CorrectTypoContext CTC = CTC_Expression;
886  if (ObjCMethodDecl *Method = getCurMethodDecl())
887    if (Method->getClassInterface() &&
888        Method->getClassInterface()->getSuperClass())
889      CTC = CTC_ObjCMessageReceiver;
890
891  if (DeclarationName Corrected = CorrectTypo(Result, S, 0, 0, false, CTC)) {
892    if (Result.isSingleResult()) {
893      // If we found a declaration, correct when it refers to an Objective-C
894      // class.
895      NamedDecl *ND = Result.getFoundDecl();
896      if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
897        Diag(NameLoc, diag::err_unknown_receiver_suggest)
898          << Name << Result.getLookupName()
899          << FixItHint::CreateReplacement(SourceRange(NameLoc),
900                                          ND->getNameAsString());
901        Diag(ND->getLocation(), diag::note_previous_decl)
902          << Corrected;
903
904        QualType T = Context.getObjCInterfaceType(Class);
905        TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
906        ReceiverType = CreateParsedType(T, TSInfo);
907        return ObjCClassMessage;
908      }
909    } else if (Result.empty() && Corrected.getAsIdentifierInfo() &&
910               Corrected.getAsIdentifierInfo()->isStr("super")) {
911      // If we've found the keyword "super", this is a send to super.
912      Diag(NameLoc, diag::err_unknown_receiver_suggest)
913        << Name << Corrected
914        << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
915      return ObjCSuperMessage;
916    }
917  }
918
919  // Fall back: let the parser try to parse it as an instance message.
920  return ObjCInstanceMessage;
921}
922
923ExprResult Sema::ActOnSuperMessage(Scope *S,
924                                   SourceLocation SuperLoc,
925                                   Selector Sel,
926                                   SourceLocation LBracLoc,
927                                   SourceLocation SelectorLoc,
928                                   SourceLocation RBracLoc,
929                                   MultiExprArg Args) {
930  // Determine whether we are inside a method or not.
931  ObjCMethodDecl *Method = tryCaptureObjCSelf();
932  if (!Method) {
933    Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
934    return ExprError();
935  }
936
937  ObjCInterfaceDecl *Class = Method->getClassInterface();
938  if (!Class) {
939    Diag(SuperLoc, diag::error_no_super_class_message)
940      << Method->getDeclName();
941    return ExprError();
942  }
943
944  ObjCInterfaceDecl *Super = Class->getSuperClass();
945  if (!Super) {
946    // The current class does not have a superclass.
947    Diag(SuperLoc, diag::error_root_class_cannot_use_super)
948      << Class->getIdentifier();
949    return ExprError();
950  }
951
952  // We are in a method whose class has a superclass, so 'super'
953  // is acting as a keyword.
954  if (Method->isInstanceMethod()) {
955    // Since we are in an instance method, this is an instance
956    // message to the superclass instance.
957    QualType SuperTy = Context.getObjCInterfaceType(Super);
958    SuperTy = Context.getObjCObjectPointerType(SuperTy);
959    return BuildInstanceMessage(0, SuperTy, SuperLoc,
960                                Sel, /*Method=*/0,
961                                LBracLoc, SelectorLoc, RBracLoc, move(Args));
962  }
963
964  // Since we are in a class method, this is a class message to
965  // the superclass.
966  return BuildClassMessage(/*ReceiverTypeInfo=*/0,
967                           Context.getObjCInterfaceType(Super),
968                           SuperLoc, Sel, /*Method=*/0,
969                           LBracLoc, SelectorLoc, RBracLoc, move(Args));
970}
971
972/// \brief Build an Objective-C class message expression.
973///
974/// This routine takes care of both normal class messages and
975/// class messages to the superclass.
976///
977/// \param ReceiverTypeInfo Type source information that describes the
978/// receiver of this message. This may be NULL, in which case we are
979/// sending to the superclass and \p SuperLoc must be a valid source
980/// location.
981
982/// \param ReceiverType The type of the object receiving the
983/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
984/// type as that refers to. For a superclass send, this is the type of
985/// the superclass.
986///
987/// \param SuperLoc The location of the "super" keyword in a
988/// superclass message.
989///
990/// \param Sel The selector to which the message is being sent.
991///
992/// \param Method The method that this class message is invoking, if
993/// already known.
994///
995/// \param LBracLoc The location of the opening square bracket ']'.
996///
997/// \param RBrac The location of the closing square bracket ']'.
998///
999/// \param Args The message arguments.
1000ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
1001                                   QualType ReceiverType,
1002                                   SourceLocation SuperLoc,
1003                                   Selector Sel,
1004                                   ObjCMethodDecl *Method,
1005                                   SourceLocation LBracLoc,
1006                                   SourceLocation SelectorLoc,
1007                                   SourceLocation RBracLoc,
1008                                   MultiExprArg ArgsIn) {
1009  SourceLocation Loc = SuperLoc.isValid()? SuperLoc
1010    : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
1011  if (LBracLoc.isInvalid()) {
1012    Diag(Loc, diag::err_missing_open_square_message_send)
1013      << FixItHint::CreateInsertion(Loc, "[");
1014    LBracLoc = Loc;
1015  }
1016
1017  if (ReceiverType->isDependentType()) {
1018    // If the receiver type is dependent, we can't type-check anything
1019    // at this point. Build a dependent expression.
1020    unsigned NumArgs = ArgsIn.size();
1021    Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1022    assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1023    return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1024                                         VK_RValue, LBracLoc, ReceiverTypeInfo,
1025                                         Sel, SelectorLoc, /*Method=*/0,
1026                                         Args, NumArgs, RBracLoc));
1027  }
1028
1029  // Find the class to which we are sending this message.
1030  ObjCInterfaceDecl *Class = 0;
1031  const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1032  if (!ClassType || !(Class = ClassType->getInterface())) {
1033    Diag(Loc, diag::err_invalid_receiver_class_message)
1034      << ReceiverType;
1035    return ExprError();
1036  }
1037  assert(Class && "We don't know which class we're messaging?");
1038  (void)DiagnoseUseOfDecl(Class, Loc);
1039  // Find the method we are messaging.
1040  if (!Method) {
1041    if (Class->isForwardDecl()) {
1042      if (getLangOptions().ObjCAutoRefCount) {
1043        Diag(Loc, diag::err_arc_receiver_forward_class) << ReceiverType;
1044      } else {
1045        Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
1046      }
1047
1048      // A forward class used in messaging is treated as a 'Class'
1049      Method = LookupFactoryMethodInGlobalPool(Sel,
1050                                               SourceRange(LBracLoc, RBracLoc));
1051      if (Method && !getLangOptions().ObjCAutoRefCount)
1052        Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1053          << Method->getDeclName();
1054    }
1055    if (!Method)
1056      Method = Class->lookupClassMethod(Sel);
1057
1058    // If we have an implementation in scope, check "private" methods.
1059    if (!Method)
1060      Method = LookupPrivateClassMethod(Sel, Class);
1061
1062    if (Method && DiagnoseUseOfDecl(Method, Loc))
1063      return ExprError();
1064  }
1065
1066  // Check the argument types and determine the result type.
1067  QualType ReturnType;
1068  ExprValueKind VK = VK_RValue;
1069
1070  unsigned NumArgs = ArgsIn.size();
1071  Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1072  if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1073                                SuperLoc.isValid(), LBracLoc, RBracLoc,
1074                                ReturnType, VK))
1075    return ExprError();
1076
1077  if (Method && !Method->getResultType()->isVoidType() &&
1078      RequireCompleteType(LBracLoc, Method->getResultType(),
1079                          diag::err_illegal_message_expr_incomplete_type))
1080    return ExprError();
1081
1082  // Construct the appropriate ObjCMessageExpr.
1083  Expr *Result;
1084  if (SuperLoc.isValid())
1085    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1086                                     SuperLoc, /*IsInstanceSuper=*/false,
1087                                     ReceiverType, Sel, SelectorLoc,
1088                                     Method, Args, NumArgs, RBracLoc);
1089  else
1090    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1091                                     ReceiverTypeInfo, Sel, SelectorLoc,
1092                                     Method, Args, NumArgs, RBracLoc);
1093  return MaybeBindToTemporary(Result);
1094}
1095
1096// ActOnClassMessage - used for both unary and keyword messages.
1097// ArgExprs is optional - if it is present, the number of expressions
1098// is obtained from Sel.getNumArgs().
1099ExprResult Sema::ActOnClassMessage(Scope *S,
1100                                   ParsedType Receiver,
1101                                   Selector Sel,
1102                                   SourceLocation LBracLoc,
1103                                   SourceLocation SelectorLoc,
1104                                   SourceLocation RBracLoc,
1105                                   MultiExprArg Args) {
1106  TypeSourceInfo *ReceiverTypeInfo;
1107  QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1108  if (ReceiverType.isNull())
1109    return ExprError();
1110
1111
1112  if (!ReceiverTypeInfo)
1113    ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1114
1115  return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
1116                           /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
1117                           LBracLoc, SelectorLoc, RBracLoc, move(Args));
1118}
1119
1120/// \brief Build an Objective-C instance message expression.
1121///
1122/// This routine takes care of both normal instance messages and
1123/// instance messages to the superclass instance.
1124///
1125/// \param Receiver The expression that computes the object that will
1126/// receive this message. This may be empty, in which case we are
1127/// sending to the superclass instance and \p SuperLoc must be a valid
1128/// source location.
1129///
1130/// \param ReceiverType The (static) type of the object receiving the
1131/// message. When a \p Receiver expression is provided, this is the
1132/// same type as that expression. For a superclass instance send, this
1133/// is a pointer to the type of the superclass.
1134///
1135/// \param SuperLoc The location of the "super" keyword in a
1136/// superclass instance message.
1137///
1138/// \param Sel The selector to which the message is being sent.
1139///
1140/// \param Method The method that this instance message is invoking, if
1141/// already known.
1142///
1143/// \param LBracLoc The location of the opening square bracket ']'.
1144///
1145/// \param RBrac The location of the closing square bracket ']'.
1146///
1147/// \param Args The message arguments.
1148ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
1149                                      QualType ReceiverType,
1150                                      SourceLocation SuperLoc,
1151                                      Selector Sel,
1152                                      ObjCMethodDecl *Method,
1153                                      SourceLocation LBracLoc,
1154                                      SourceLocation SelectorLoc,
1155                                      SourceLocation RBracLoc,
1156                                      MultiExprArg ArgsIn) {
1157  // The location of the receiver.
1158  SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1159
1160  if (LBracLoc.isInvalid()) {
1161    Diag(Loc, diag::err_missing_open_square_message_send)
1162      << FixItHint::CreateInsertion(Loc, "[");
1163    LBracLoc = Loc;
1164  }
1165
1166  // If we have a receiver expression, perform appropriate promotions
1167  // and determine receiver type.
1168  if (Receiver) {
1169    if (Receiver->isTypeDependent()) {
1170      // If the receiver is type-dependent, we can't type-check anything
1171      // at this point. Build a dependent expression.
1172      unsigned NumArgs = ArgsIn.size();
1173      Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1174      assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1175      return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
1176                                           VK_RValue, LBracLoc, Receiver, Sel,
1177                                           SelectorLoc, /*Method=*/0,
1178                                           Args, NumArgs, RBracLoc));
1179    }
1180
1181    // If necessary, apply function/array conversion to the receiver.
1182    // C99 6.7.5.3p[7,8].
1183    ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1184    if (Result.isInvalid())
1185      return ExprError();
1186    Receiver = Result.take();
1187    ReceiverType = Receiver->getType();
1188  }
1189
1190  if (!Method) {
1191    // Handle messages to id.
1192    bool receiverIsId = ReceiverType->isObjCIdType();
1193    if (receiverIsId || ReceiverType->isBlockPointerType() ||
1194        (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1195      Method = LookupInstanceMethodInGlobalPool(Sel,
1196                                                SourceRange(LBracLoc, RBracLoc),
1197                                                receiverIsId);
1198      if (!Method)
1199        Method = LookupFactoryMethodInGlobalPool(Sel,
1200                                                 SourceRange(LBracLoc, RBracLoc),
1201                                                 receiverIsId);
1202    } else if (ReceiverType->isObjCClassType() ||
1203               ReceiverType->isObjCQualifiedClassType()) {
1204      // Handle messages to Class.
1205      // We allow sending a message to a qualified Class ("Class<foo>"), which
1206      // is ok as long as one of the protocols implements the selector (if not, warn).
1207      if (const ObjCObjectPointerType *QClassTy
1208            = ReceiverType->getAsObjCQualifiedClassType()) {
1209        // Search protocols for class methods.
1210        Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1211        if (!Method) {
1212          Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1213          // warn if instance method found for a Class message.
1214          if (Method) {
1215            Diag(Loc, diag::warn_instance_method_on_class_found)
1216              << Method->getSelector() << Sel;
1217            Diag(Method->getLocation(), diag::note_method_declared_at);
1218          }
1219        }
1220      } else {
1221        if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1222          if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1223            // First check the public methods in the class interface.
1224            Method = ClassDecl->lookupClassMethod(Sel);
1225
1226            if (!Method)
1227              Method = LookupPrivateClassMethod(Sel, ClassDecl);
1228          }
1229          if (Method && DiagnoseUseOfDecl(Method, Loc))
1230            return ExprError();
1231        }
1232        if (!Method) {
1233          // If not messaging 'self', look for any factory method named 'Sel'.
1234          if (!Receiver || !isSelfExpr(Receiver)) {
1235            Method = LookupFactoryMethodInGlobalPool(Sel,
1236                                                SourceRange(LBracLoc, RBracLoc),
1237                                                     true);
1238            if (!Method) {
1239              // If no class (factory) method was found, check if an _instance_
1240              // method of the same name exists in the root class only.
1241              Method = LookupInstanceMethodInGlobalPool(Sel,
1242                                               SourceRange(LBracLoc, RBracLoc),
1243                                                        true);
1244              if (Method)
1245                  if (const ObjCInterfaceDecl *ID =
1246                      dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1247                    if (ID->getSuperClass())
1248                      Diag(Loc, diag::warn_root_inst_method_not_found)
1249                      << Sel << SourceRange(LBracLoc, RBracLoc);
1250                  }
1251            }
1252          }
1253        }
1254      }
1255    } else {
1256      ObjCInterfaceDecl* ClassDecl = 0;
1257
1258      // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1259      // long as one of the protocols implements the selector (if not, warn).
1260      if (const ObjCObjectPointerType *QIdTy
1261                                   = ReceiverType->getAsObjCQualifiedIdType()) {
1262        // Search protocols for instance methods.
1263        Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
1264        if (!Method)
1265          Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
1266      } else if (const ObjCObjectPointerType *OCIType
1267                   = ReceiverType->getAsObjCInterfacePointerType()) {
1268        // We allow sending a message to a pointer to an interface (an object).
1269        ClassDecl = OCIType->getInterfaceDecl();
1270
1271        if (ClassDecl->isForwardDecl() && getLangOptions().ObjCAutoRefCount) {
1272          Diag(Loc, diag::err_arc_receiver_forward_instance)
1273            << OCIType->getPointeeType()
1274            << (Receiver ? Receiver->getSourceRange() : SourceRange(SuperLoc));
1275          return ExprError();
1276        }
1277
1278        // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
1279        // faster than the following method (which can do *many* linear searches).
1280        // The idea is to add class info to MethodPool.
1281        Method = ClassDecl->lookupInstanceMethod(Sel);
1282
1283        if (!Method)
1284          // Search protocol qualifiers.
1285          Method = LookupMethodInQualifiedType(Sel, OCIType, true);
1286
1287        const ObjCInterfaceDecl *forwardClass = 0;
1288        if (!Method) {
1289          // If we have implementations in scope, check "private" methods.
1290          Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1291
1292          if (!Method && getLangOptions().ObjCAutoRefCount) {
1293            Diag(Loc, diag::err_arc_may_not_respond)
1294              << OCIType->getPointeeType() << Sel;
1295            return ExprError();
1296          }
1297
1298          if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
1299            // If we still haven't found a method, look in the global pool. This
1300            // behavior isn't very desirable, however we need it for GCC
1301            // compatibility. FIXME: should we deviate??
1302            if (OCIType->qual_empty()) {
1303              Method = LookupInstanceMethodInGlobalPool(Sel,
1304                                                 SourceRange(LBracLoc, RBracLoc));
1305              if (OCIType->getInterfaceDecl()->isForwardDecl())
1306                forwardClass = OCIType->getInterfaceDecl();
1307              if (Method && !forwardClass)
1308                Diag(Loc, diag::warn_maynot_respond)
1309                  << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1310            }
1311          }
1312        }
1313        if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
1314          return ExprError();
1315      } else if (!getLangOptions().ObjCAutoRefCount &&
1316                 !Context.getObjCIdType().isNull() &&
1317                 (ReceiverType->isPointerType() ||
1318                  ReceiverType->isIntegerType())) {
1319        // Implicitly convert integers and pointers to 'id' but emit a warning.
1320        // But not in ARC.
1321        Diag(Loc, diag::warn_bad_receiver_type)
1322          << ReceiverType
1323          << Receiver->getSourceRange();
1324        if (ReceiverType->isPointerType())
1325          Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1326                            CK_BitCast).take();
1327        else {
1328          // TODO: specialized warning on null receivers?
1329          bool IsNull = Receiver->isNullPointerConstant(Context,
1330                                              Expr::NPC_ValueDependentIsNull);
1331          Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1332                            IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
1333        }
1334        ReceiverType = Receiver->getType();
1335      }
1336      else {
1337        ExprResult ReceiverRes;
1338        if (getLangOptions().CPlusPlus)
1339          ReceiverRes = PerformContextuallyConvertToObjCId(Receiver);
1340        if (ReceiverRes.isUsable()) {
1341          Receiver = ReceiverRes.take();
1342          if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
1343            Receiver = ICE->getSubExpr();
1344            ReceiverType = Receiver->getType();
1345          }
1346          return BuildInstanceMessage(Receiver,
1347                                      ReceiverType,
1348                                      SuperLoc,
1349                                      Sel,
1350                                      Method,
1351                                      LBracLoc,
1352                                      SelectorLoc,
1353                                      RBracLoc,
1354                                      move(ArgsIn));
1355        } else {
1356          // Reject other random receiver types (e.g. structs).
1357          Diag(Loc, diag::err_bad_receiver_type)
1358            << ReceiverType << Receiver->getSourceRange();
1359          return ExprError();
1360        }
1361      }
1362    }
1363  }
1364
1365  // Check the message arguments.
1366  unsigned NumArgs = ArgsIn.size();
1367  Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1368  QualType ReturnType;
1369  ExprValueKind VK = VK_RValue;
1370  bool ClassMessage = (ReceiverType->isObjCClassType() ||
1371                       ReceiverType->isObjCQualifiedClassType());
1372  if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
1373                                ClassMessage, SuperLoc.isValid(),
1374                                LBracLoc, RBracLoc, ReturnType, VK))
1375    return ExprError();
1376
1377  if (Method && !Method->getResultType()->isVoidType() &&
1378      RequireCompleteType(LBracLoc, Method->getResultType(),
1379                          diag::err_illegal_message_expr_incomplete_type))
1380    return ExprError();
1381
1382  // In ARC, forbid the user from sending messages to
1383  // retain/release/autorelease/dealloc/retainCount explicitly.
1384  if (getLangOptions().ObjCAutoRefCount) {
1385    ObjCMethodFamily family =
1386      (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
1387    switch (family) {
1388    case OMF_init:
1389      if (Method)
1390        checkInitMethod(Method, ReceiverType);
1391
1392    case OMF_None:
1393    case OMF_alloc:
1394    case OMF_copy:
1395    case OMF_mutableCopy:
1396    case OMF_new:
1397    case OMF_self:
1398      break;
1399
1400    case OMF_dealloc:
1401    case OMF_retain:
1402    case OMF_release:
1403    case OMF_autorelease:
1404    case OMF_retainCount:
1405      Diag(Loc, diag::err_arc_illegal_explicit_message)
1406        << Sel << SelectorLoc;
1407      break;
1408    }
1409  }
1410
1411  // Construct the appropriate ObjCMessageExpr instance.
1412  ObjCMessageExpr *Result;
1413  if (SuperLoc.isValid())
1414    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1415                                     SuperLoc,  /*IsInstanceSuper=*/true,
1416                                     ReceiverType, Sel, SelectorLoc, Method,
1417                                     Args, NumArgs, RBracLoc);
1418  else
1419    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1420                                     Receiver, Sel, SelectorLoc, Method,
1421                                     Args, NumArgs, RBracLoc);
1422
1423  if (getLangOptions().ObjCAutoRefCount) {
1424    // In ARC, annotate delegate init calls.
1425    if (Result->getMethodFamily() == OMF_init &&
1426        (SuperLoc.isValid() || isSelfExpr(Receiver))) {
1427      // Only consider init calls *directly* in init implementations,
1428      // not within blocks.
1429      ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
1430      if (method && method->getMethodFamily() == OMF_init) {
1431        // The implicit assignment to self means we also don't want to
1432        // consume the result.
1433        Result->setDelegateInitCall(true);
1434        return Owned(Result);
1435      }
1436    }
1437
1438    // In ARC, check for message sends which are likely to introduce
1439    // retain cycles.
1440    checkRetainCycles(Result);
1441  }
1442
1443  return MaybeBindToTemporary(Result);
1444}
1445
1446// ActOnInstanceMessage - used for both unary and keyword messages.
1447// ArgExprs is optional - if it is present, the number of expressions
1448// is obtained from Sel.getNumArgs().
1449ExprResult Sema::ActOnInstanceMessage(Scope *S,
1450                                      Expr *Receiver,
1451                                      Selector Sel,
1452                                      SourceLocation LBracLoc,
1453                                      SourceLocation SelectorLoc,
1454                                      SourceLocation RBracLoc,
1455                                      MultiExprArg Args) {
1456  if (!Receiver)
1457    return ExprError();
1458
1459  return BuildInstanceMessage(Receiver, Receiver->getType(),
1460                              /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
1461                              LBracLoc, SelectorLoc, RBracLoc, move(Args));
1462}
1463
1464enum ARCConversionTypeClass {
1465  ACTC_none,
1466  ACTC_retainable,
1467  ACTC_indirectRetainable
1468};
1469static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
1470  ARCConversionTypeClass ACTC = ACTC_retainable;
1471
1472  // Ignore an outermost reference type.
1473  if (const ReferenceType *ref = type->getAs<ReferenceType>())
1474    type = ref->getPointeeType();
1475
1476  // Drill through pointers and arrays recursively.
1477  while (true) {
1478    if (const PointerType *ptr = type->getAs<PointerType>()) {
1479      type = ptr->getPointeeType();
1480    } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
1481      type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
1482    } else {
1483      break;
1484    }
1485    ACTC = ACTC_indirectRetainable;
1486  }
1487
1488  if (!type->isObjCRetainableType()) return ACTC_none;
1489  return ACTC;
1490}
1491
1492namespace {
1493  /// Return true if the given expression can be reasonably converted
1494  /// between a retainable pointer type and a C pointer type.
1495  struct ARCCastChecker : StmtVisitor<ARCCastChecker, bool> {
1496    ASTContext &Context;
1497    ARCCastChecker(ASTContext &Context) : Context(Context) {}
1498    bool VisitStmt(Stmt *s) {
1499      return false;
1500    }
1501    bool VisitExpr(Expr *e) {
1502      return e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
1503    }
1504
1505    bool VisitParenExpr(ParenExpr *e) {
1506      return Visit(e->getSubExpr());
1507    }
1508    bool VisitCastExpr(CastExpr *e) {
1509      switch (e->getCastKind()) {
1510        case CK_NullToPointer:
1511          return true;
1512        case CK_NoOp:
1513        case CK_LValueToRValue:
1514        case CK_BitCast:
1515        case CK_AnyPointerToObjCPointerCast:
1516        case CK_AnyPointerToBlockPointerCast:
1517          return Visit(e->getSubExpr());
1518        default:
1519          return false;
1520      }
1521    }
1522    bool VisitUnaryExtension(UnaryOperator *e) {
1523      return Visit(e->getSubExpr());
1524    }
1525    bool VisitBinComma(BinaryOperator *e) {
1526      return Visit(e->getRHS());
1527    }
1528    bool VisitConditionalOperator(ConditionalOperator *e) {
1529      // Conditional operators are okay if both sides are okay.
1530      return Visit(e->getTrueExpr()) && Visit(e->getFalseExpr());
1531    }
1532    bool VisitObjCStringLiteral(ObjCStringLiteral *e) {
1533      // Always white-list Objective-C string literals.
1534      return true;
1535    }
1536    bool VisitStmtExpr(StmtExpr *e) {
1537      return Visit(e->getSubStmt()->body_back());
1538    }
1539    bool VisitDeclRefExpr(DeclRefExpr *e) {
1540      // White-list references to global extern strings from system
1541      // headers.
1542      if (VarDecl *var = dyn_cast<VarDecl>(e->getDecl()))
1543        if (var->getStorageClass() == SC_Extern &&
1544            var->getType().isConstQualified() &&
1545            Context.getSourceManager().isInSystemHeader(var->getLocation()))
1546          return true;
1547      return false;
1548    }
1549  };
1550}
1551
1552void
1553Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
1554                             Expr *castExpr, CheckedConversionKind CCK) {
1555  QualType castExprType = castExpr->getType();
1556
1557  ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
1558  ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
1559  if (exprACTC == castACTC) return;
1560  if (exprACTC && castType->isBooleanType()) return;
1561
1562  // Allow casts between pointers to lifetime types (e.g., __strong id*)
1563  // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
1564  // must be explicit.
1565  if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
1566    if (const PointerType *CastExprPtr = castExprType->getAs<PointerType>()) {
1567      QualType CastPointee = CastPtr->getPointeeType();
1568      QualType CastExprPointee = CastExprPtr->getPointeeType();
1569      if ((CCK != CCK_ImplicitConversion &&
1570           CastPointee->isObjCIndirectLifetimeType() &&
1571           CastExprPointee->isVoidType()) ||
1572          (CastPointee->isVoidType() &&
1573           CastExprPointee->isObjCIndirectLifetimeType()))
1574        return;
1575    }
1576  }
1577
1578  if (ARCCastChecker(Context).Visit(castExpr))
1579    return;
1580
1581  SourceLocation loc =
1582  (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
1583
1584  if (makeUnavailableInSystemHeader(loc,
1585                                    "converts between Objective-C and C pointers in -fobjc-arc"))
1586    return;
1587
1588  unsigned srcKind;
1589  switch (exprACTC) {
1590    case ACTC_none:
1591      srcKind = (castExprType->isPointerType() ? 1 : 0);
1592      break;
1593    case ACTC_retainable:
1594      srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
1595      break;
1596    case ACTC_indirectRetainable:
1597      srcKind = 4;
1598      break;
1599  }
1600
1601  if (CCK == CCK_CStyleCast) {
1602    // Check whether this could be fixed with a bridge cast.
1603    SourceLocation AfterLParen = PP.getLocForEndOfToken(castRange.getBegin());
1604    SourceLocation NoteLoc = AfterLParen.isValid()? AfterLParen : loc;
1605
1606    if (castType->isObjCARCBridgableType() &&
1607        castExprType->isCARCBridgableType()) {
1608      Diag(loc, diag::err_arc_cast_requires_bridge)
1609        << 2
1610        << castExprType
1611        << (castType->isBlockPointerType()? 1 : 0)
1612        << castType
1613        << castRange
1614        << castExpr->getSourceRange();
1615      Diag(NoteLoc, diag::note_arc_bridge)
1616        << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1617      Diag(NoteLoc, diag::note_arc_bridge_transfer)
1618        << castExprType
1619        << FixItHint::CreateInsertion(AfterLParen, "__bridge_transfer ");
1620
1621      return;
1622    }
1623
1624    if (castType->isCARCBridgableType() &&
1625        castExprType->isObjCARCBridgableType()){
1626      Diag(loc, diag::err_arc_cast_requires_bridge)
1627        << (castExprType->isBlockPointerType()? 1 : 0)
1628        << castExprType
1629        << 2
1630        << castType
1631        << castRange
1632        << castExpr->getSourceRange();
1633
1634      Diag(NoteLoc, diag::note_arc_bridge)
1635        << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1636      Diag(NoteLoc, diag::note_arc_bridge_retained)
1637        << castType
1638        << FixItHint::CreateInsertion(AfterLParen, "__bridge_retained ");
1639      return;
1640    }
1641  }
1642
1643  Diag(loc, diag::err_arc_mismatched_cast)
1644    << (CCK != CCK_ImplicitConversion) << srcKind << castExprType << castType
1645    << castRange << castExpr->getSourceRange();
1646}
1647
1648ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
1649                                      ObjCBridgeCastKind Kind,
1650                                      SourceLocation BridgeKeywordLoc,
1651                                      TypeSourceInfo *TSInfo,
1652                                      Expr *SubExpr) {
1653  QualType T = TSInfo->getType();
1654  QualType FromType = SubExpr->getType();
1655
1656  bool MustConsume = false;
1657  if (T->isDependentType() || SubExpr->isTypeDependent()) {
1658    // Okay: we'll build a dependent expression type.
1659  } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
1660    // Casting CF -> id
1661    switch (Kind) {
1662    case OBC_Bridge:
1663      break;
1664
1665    case OBC_BridgeRetained:
1666      Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
1667        << 2
1668        << FromType
1669        << (T->isBlockPointerType()? 1 : 0)
1670        << T
1671        << SubExpr->getSourceRange()
1672        << Kind;
1673      Diag(BridgeKeywordLoc, diag::note_arc_bridge)
1674        << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
1675      Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
1676        << FromType
1677        << FixItHint::CreateReplacement(BridgeKeywordLoc,
1678                                        "__bridge_transfer ");
1679
1680      Kind = OBC_Bridge;
1681      break;
1682
1683    case OBC_BridgeTransfer:
1684      // We must consume the Objective-C object produced by the cast.
1685      MustConsume = true;
1686      break;
1687    }
1688  } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
1689    // Okay: id -> CF
1690    switch (Kind) {
1691    case OBC_Bridge:
1692      break;
1693
1694    case OBC_BridgeRetained:
1695      // Produce the object before casting it.
1696      SubExpr = ImplicitCastExpr::Create(Context, FromType,
1697                                         CK_ObjCProduceObject,
1698                                         SubExpr, 0, VK_RValue);
1699      break;
1700
1701    case OBC_BridgeTransfer:
1702      Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
1703        << (FromType->isBlockPointerType()? 1 : 0)
1704        << FromType
1705        << 2
1706        << T
1707        << SubExpr->getSourceRange()
1708        << Kind;
1709
1710      Diag(BridgeKeywordLoc, diag::note_arc_bridge)
1711        << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
1712      Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
1713        << T
1714        << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge_retained ");
1715
1716      Kind = OBC_Bridge;
1717      break;
1718    }
1719  } else {
1720    Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
1721      << FromType << T << Kind
1722      << SubExpr->getSourceRange()
1723      << TSInfo->getTypeLoc().getSourceRange();
1724    return ExprError();
1725  }
1726
1727  Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind,
1728                                                   BridgeKeywordLoc,
1729                                                   TSInfo, SubExpr);
1730
1731  if (MustConsume) {
1732    ExprNeedsCleanups = true;
1733    Result = ImplicitCastExpr::Create(Context, T, CK_ObjCConsumeObject, Result,
1734                                      0, VK_RValue);
1735  }
1736
1737  return Result;
1738}
1739
1740ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
1741                                      SourceLocation LParenLoc,
1742                                      ObjCBridgeCastKind Kind,
1743                                      SourceLocation BridgeKeywordLoc,
1744                                      ParsedType Type,
1745                                      SourceLocation RParenLoc,
1746                                      Expr *SubExpr) {
1747  TypeSourceInfo *TSInfo = 0;
1748  QualType T = GetTypeFromParser(Type, &TSInfo);
1749  if (!TSInfo)
1750    TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
1751  return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
1752                              SubExpr);
1753}
1754