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