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