]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaExprObjC.cpp
MFC r234353:
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / lib / Sema / SemaExprObjC.cpp
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/Edit/Rewriters.h"
21 #include "clang/Edit/Commit.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "clang/Lex/Preprocessor.h"
29
30 using namespace clang;
31 using namespace sema;
32 using llvm::makeArrayRef;
33
34 ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
35                                         Expr **strings,
36                                         unsigned NumStrings) {
37   StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
38
39   // Most ObjC strings are formed out of a single piece.  However, we *can*
40   // have strings formed out of multiple @ strings with multiple pptokens in
41   // each one, e.g. @"foo" "bar" @"baz" "qux"   which need to be turned into one
42   // StringLiteral for ObjCStringLiteral to hold onto.
43   StringLiteral *S = Strings[0];
44
45   // If we have a multi-part string, merge it all together.
46   if (NumStrings != 1) {
47     // Concatenate objc strings.
48     SmallString<128> StrBuf;
49     SmallVector<SourceLocation, 8> StrLocs;
50
51     for (unsigned i = 0; i != NumStrings; ++i) {
52       S = Strings[i];
53
54       // ObjC strings can't be wide or UTF.
55       if (!S->isAscii()) {
56         Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
57           << S->getSourceRange();
58         return true;
59       }
60
61       // Append the string.
62       StrBuf += S->getString();
63
64       // Get the locations of the string tokens.
65       StrLocs.append(S->tokloc_begin(), S->tokloc_end());
66     }
67
68     // Create the aggregate string with the appropriate content and location
69     // information.
70     S = StringLiteral::Create(Context, StrBuf,
71                               StringLiteral::Ascii, /*Pascal=*/false,
72                               Context.getPointerType(Context.CharTy),
73                               &StrLocs[0], StrLocs.size());
74   }
75   
76   return BuildObjCStringLiteral(AtLocs[0], S);
77 }
78
79 ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
80   // Verify that this composite string is acceptable for ObjC strings.
81   if (CheckObjCString(S))
82     return true;
83
84   // Initialize the constant string interface lazily. This assumes
85   // the NSString interface is seen in this translation unit. Note: We
86   // don't use NSConstantString, since the runtime team considers this
87   // interface private (even though it appears in the header files).
88   QualType Ty = Context.getObjCConstantStringInterface();
89   if (!Ty.isNull()) {
90     Ty = Context.getObjCObjectPointerType(Ty);
91   } else if (getLangOpts().NoConstantCFStrings) {
92     IdentifierInfo *NSIdent=0;
93     std::string StringClass(getLangOpts().ObjCConstantStringClass);
94     
95     if (StringClass.empty())
96       NSIdent = &Context.Idents.get("NSConstantString");
97     else
98       NSIdent = &Context.Idents.get(StringClass);
99     
100     NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
101                                      LookupOrdinaryName);
102     if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
103       Context.setObjCConstantStringInterface(StrIF);
104       Ty = Context.getObjCConstantStringInterface();
105       Ty = Context.getObjCObjectPointerType(Ty);
106     } else {
107       // If there is no NSConstantString interface defined then treat this
108       // as error and recover from it.
109       Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
110         << S->getSourceRange();
111       Ty = Context.getObjCIdType();
112     }
113   } else {
114     IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
115     NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
116                                      LookupOrdinaryName);
117     if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
118       Context.setObjCConstantStringInterface(StrIF);
119       Ty = Context.getObjCConstantStringInterface();
120       Ty = Context.getObjCObjectPointerType(Ty);
121     } else {
122       // If there is no NSString interface defined, implicitly declare
123       // a @class NSString; and use that instead. This is to make sure
124       // type of an NSString literal is represented correctly, instead of
125       // being an 'id' type.
126       Ty = Context.getObjCNSStringType();
127       if (Ty.isNull()) {
128         ObjCInterfaceDecl *NSStringIDecl = 
129           ObjCInterfaceDecl::Create (Context, 
130                                      Context.getTranslationUnitDecl(), 
131                                      SourceLocation(), NSIdent, 
132                                      0, SourceLocation());
133         Ty = Context.getObjCInterfaceType(NSStringIDecl);
134         Context.setObjCNSStringType(Ty);
135       }
136       Ty = Context.getObjCObjectPointerType(Ty);
137     }
138   }
139
140   return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
141 }
142
143 /// \brief Retrieve the NSNumber factory method that should be used to create
144 /// an Objective-C literal for the given type.
145 static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
146                                                 QualType T, QualType ReturnType,
147                                                 SourceRange Range) {
148   llvm::Optional<NSAPI::NSNumberLiteralMethodKind> Kind 
149     = S.NSAPIObj->getNSNumberFactoryMethodKind(T);
150   
151   if (!Kind) {
152     S.Diag(Loc, diag::err_invalid_nsnumber_type)
153       << T << Range;
154     return 0;
155   }
156     
157   // If we already looked up this method, we're done.
158   if (S.NSNumberLiteralMethods[*Kind])
159     return S.NSNumberLiteralMethods[*Kind];
160   
161   Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
162                                                         /*Instance=*/false);
163   
164   // Look for the appropriate method within NSNumber.
165   ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);;
166   if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
167     TypeSourceInfo *ResultTInfo = 0;
168     Method = ObjCMethodDecl::Create(S.Context, SourceLocation(), SourceLocation(), Sel,
169                            ReturnType,
170                            ResultTInfo,
171                            S.Context.getTranslationUnitDecl(),
172                            false /*Instance*/, false/*isVariadic*/,
173                            /*isSynthesized=*/false,
174                            /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
175                            ObjCMethodDecl::Required,
176                            false);
177     ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
178                                              SourceLocation(), SourceLocation(),
179                                              &S.Context.Idents.get("value"),
180                                              T, /*TInfo=*/0, SC_None, SC_None, 0);
181     Method->setMethodParams(S.Context, value, ArrayRef<SourceLocation>());
182   }
183
184   if (!Method) {
185     S.Diag(Loc, diag::err_undeclared_nsnumber_method) << Sel;
186     return 0;
187   }
188   
189   // Make sure the return type is reasonable.
190   if (!Method->getResultType()->isObjCObjectPointerType()) {
191     S.Diag(Loc, diag::err_objc_literal_method_sig)
192       << Sel;
193     S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
194       << Method->getResultType();
195     return 0;
196   }
197
198   // Note: if the parameter type is out-of-line, we'll catch it later in the
199   // implicit conversion.
200   
201   S.NSNumberLiteralMethods[*Kind] = Method;
202   return Method;
203 }
204
205 /// BuildObjCNumericLiteral - builds an ObjCNumericLiteral AST node for the
206 /// numeric literal expression. Type of the expression will be "NSNumber *"
207 /// or "id" if NSNumber is unavailable.
208 ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
209   // Look up the NSNumber class, if we haven't done so already.
210   if (!NSNumberDecl) {
211     NamedDecl *IF = LookupSingleName(TUScope,
212                                 NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber),
213                                 AtLoc, LookupOrdinaryName);
214     NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
215     
216     if (!NSNumberDecl && getLangOpts().DebuggerObjCLiteral)
217       NSNumberDecl =  ObjCInterfaceDecl::Create (Context,
218                         Context.getTranslationUnitDecl(),
219                         SourceLocation(), 
220                         NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber),
221                         0, SourceLocation());
222     if (!NSNumberDecl) {
223       Diag(AtLoc, diag::err_undeclared_nsnumber);
224       return ExprError();
225     }
226   }
227   
228   // Determine the type of the literal.
229   QualType NumberType = Number->getType();
230   if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
231     // In C, character literals have type 'int'. That's not the type we want
232     // to use to determine the Objective-c literal kind.
233     switch (Char->getKind()) {
234     case CharacterLiteral::Ascii:
235       NumberType = Context.CharTy;
236       break;
237       
238     case CharacterLiteral::Wide:
239       NumberType = Context.getWCharType();
240       break;
241       
242     case CharacterLiteral::UTF16:
243       NumberType = Context.Char16Ty;
244       break;
245       
246     case CharacterLiteral::UTF32:
247       NumberType = Context.Char32Ty;
248       break;
249     }
250   }
251   
252   ObjCMethodDecl *Method = 0;
253   // Look for the appropriate method within NSNumber.
254   // Construct the literal.
255   QualType Ty
256     = Context.getObjCObjectPointerType(
257                                     Context.getObjCInterfaceType(NSNumberDecl));
258   Method  = getNSNumberFactoryMethod(*this, AtLoc, 
259                                      NumberType, Ty, 
260                                      Number->getSourceRange());
261
262   if (!Method)
263     return ExprError();
264
265   // Convert the number to the type that the parameter expects.
266   QualType ElementT = Method->param_begin()[0]->getType();
267   ExprResult ConvertedNumber = PerformImplicitConversion(Number, ElementT,
268                                                          AA_Sending);
269   if (ConvertedNumber.isInvalid())
270     return ExprError();
271   Number = ConvertedNumber.get();
272   
273   return MaybeBindToTemporary(
274            new (Context) ObjCNumericLiteral(Number, Ty, Method, AtLoc));
275 }
276
277 ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc, 
278                                       SourceLocation ValueLoc,
279                                       bool Value) {
280   ExprResult Inner;
281   if (getLangOpts().CPlusPlus) {
282     Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
283   } else {
284     // C doesn't actually have a way to represent literal values of type 
285     // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
286     Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
287     Inner = ImpCastExprToType(Inner.get(), Context.BoolTy, 
288                               CK_IntegralToBoolean);
289   }
290   
291   return BuildObjCNumericLiteral(AtLoc, Inner.get());
292 }
293
294 /// \brief Check that the given expression is a valid element of an Objective-C
295 /// collection literal.
296 static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, 
297                                                     QualType T) {  
298   // If the expression is type-dependent, there's nothing for us to do.
299   if (Element->isTypeDependent())
300     return Element;
301
302   ExprResult Result = S.CheckPlaceholderExpr(Element);
303   if (Result.isInvalid())
304     return ExprError();
305   Element = Result.get();
306
307   // In C++, check for an implicit conversion to an Objective-C object pointer 
308   // type.
309   if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
310     InitializedEntity Entity
311       = InitializedEntity::InitializeParameter(S.Context, T, /*Consumed=*/false);
312     InitializationKind Kind
313       = InitializationKind::CreateCopy(Element->getLocStart(), SourceLocation());
314     InitializationSequence Seq(S, Entity, Kind, &Element, 1);
315     if (!Seq.Failed())
316       return Seq.Perform(S, Entity, Kind, MultiExprArg(S, &Element, 1));
317   }
318
319   Expr *OrigElement = Element;
320
321   // Perform lvalue-to-rvalue conversion.
322   Result = S.DefaultLvalueConversion(Element);
323   if (Result.isInvalid())
324     return ExprError();
325   Element = Result.get();  
326
327   // Make sure that we have an Objective-C pointer type or block.
328   if (!Element->getType()->isObjCObjectPointerType() &&
329       !Element->getType()->isBlockPointerType()) {
330     bool Recovered = false;
331     
332     // If this is potentially an Objective-C numeric literal, add the '@'.
333     if (isa<IntegerLiteral>(OrigElement) || 
334         isa<CharacterLiteral>(OrigElement) ||
335         isa<FloatingLiteral>(OrigElement) ||
336         isa<ObjCBoolLiteralExpr>(OrigElement) ||
337         isa<CXXBoolLiteralExpr>(OrigElement)) {
338       if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
339         int Which = isa<CharacterLiteral>(OrigElement) ? 1
340                   : (isa<CXXBoolLiteralExpr>(OrigElement) ||
341                      isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
342                   : 3;
343         
344         S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
345           << Which << OrigElement->getSourceRange()
346           << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
347         
348         Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
349                                            OrigElement);
350         if (Result.isInvalid())
351           return ExprError();
352         
353         Element = Result.get();
354         Recovered = true;
355       }
356     }
357     // If this is potentially an Objective-C string literal, add the '@'.
358     else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
359       if (String->isAscii()) {
360         S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
361           << 0 << OrigElement->getSourceRange()
362           << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
363
364         Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
365         if (Result.isInvalid())
366           return ExprError();
367         
368         Element = Result.get();
369         Recovered = true;
370       }
371     }
372     
373     if (!Recovered) {
374       S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
375         << Element->getType();
376       return ExprError();
377     }
378   }
379   
380   // Make sure that the element has the type that the container factory 
381   // function expects. 
382   return S.PerformCopyInitialization(
383            InitializedEntity::InitializeParameter(S.Context, T, 
384                                                   /*Consumed=*/false),
385            Element->getLocStart(), Element);
386 }
387
388 ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
389                                         Expr *IndexExpr,
390                                         ObjCMethodDecl *getterMethod,
391                                         ObjCMethodDecl *setterMethod) {
392   // Feature support is for modern abi.
393   if (!LangOpts.ObjCNonFragileABI)
394     return ExprError();
395   // If the expression is type-dependent, there's nothing for us to do.
396   assert ((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
397           "base or index cannot have dependent type here");
398   ExprResult Result = CheckPlaceholderExpr(IndexExpr);
399   if (Result.isInvalid())
400     return ExprError();
401   IndexExpr = Result.get();
402   
403   // Perform lvalue-to-rvalue conversion.
404   Result = DefaultLvalueConversion(BaseExpr);
405   if (Result.isInvalid())
406     return ExprError();
407   BaseExpr = Result.get();
408   return Owned(ObjCSubscriptRefExpr::Create(Context, 
409                                             BaseExpr,
410                                             IndexExpr,
411                                             Context.PseudoObjectTy,
412                                             getterMethod,
413                                             setterMethod, RB));
414   
415 }
416
417 ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
418   // Look up the NSArray class, if we haven't done so already.
419   if (!NSArrayDecl) {
420     NamedDecl *IF = LookupSingleName(TUScope,
421                                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
422                                  SR.getBegin(),
423                                  LookupOrdinaryName);
424     NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
425     if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
426       NSArrayDecl =  ObjCInterfaceDecl::Create (Context,
427                             Context.getTranslationUnitDecl(),
428                             SourceLocation(),
429                             NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
430                             0, SourceLocation());
431
432     if (!NSArrayDecl) {
433       Diag(SR.getBegin(), diag::err_undeclared_nsarray);
434       return ExprError();
435     }
436   }
437   
438   // Find the arrayWithObjects:count: method, if we haven't done so already.
439   QualType IdT = Context.getObjCIdType();
440   if (!ArrayWithObjectsMethod) {
441     Selector
442       Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
443     ArrayWithObjectsMethod = NSArrayDecl->lookupClassMethod(Sel);
444     if (!ArrayWithObjectsMethod && getLangOpts().DebuggerObjCLiteral) {
445       TypeSourceInfo *ResultTInfo = 0;
446       ArrayWithObjectsMethod =
447                          ObjCMethodDecl::Create(Context,
448                            SourceLocation(), SourceLocation(), Sel,
449                            IdT,
450                            ResultTInfo,
451                            Context.getTranslationUnitDecl(),
452                            false /*Instance*/, false/*isVariadic*/,
453                            /*isSynthesized=*/false,
454                            /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
455                            ObjCMethodDecl::Required,
456                            false);
457       SmallVector<ParmVarDecl *, 2> Params;
458       ParmVarDecl *objects = ParmVarDecl::Create(Context, ArrayWithObjectsMethod,
459                                                 SourceLocation(), SourceLocation(),
460                                                 &Context.Idents.get("objects"),
461                                                 Context.getPointerType(IdT),
462                                                 /*TInfo=*/0,
463                                                 SC_None,
464                                                 SC_None,
465                                                 0);
466       Params.push_back(objects);
467       ParmVarDecl *cnt = ParmVarDecl::Create(Context, ArrayWithObjectsMethod,
468                                                 SourceLocation(), SourceLocation(),
469                                                 &Context.Idents.get("cnt"),
470                                                 Context.UnsignedLongTy,
471                                                 /*TInfo=*/0,
472                                                 SC_None,
473                                                 SC_None,
474                                                 0);
475       Params.push_back(cnt);
476       ArrayWithObjectsMethod->setMethodParams(Context, Params,
477                                               ArrayRef<SourceLocation>());
478
479
480     }
481
482     if (!ArrayWithObjectsMethod) {
483       Diag(SR.getBegin(), diag::err_undeclared_arraywithobjects) << Sel;
484       return ExprError();
485     }
486   }
487   
488   // Make sure the return type is reasonable.
489   if (!ArrayWithObjectsMethod->getResultType()->isObjCObjectPointerType()) {
490     Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
491       << ArrayWithObjectsMethod->getSelector();
492     Diag(ArrayWithObjectsMethod->getLocation(),
493          diag::note_objc_literal_method_return)
494       << ArrayWithObjectsMethod->getResultType();
495     return ExprError();
496   }
497
498   // Dig out the type that all elements should be converted to.
499   QualType T = ArrayWithObjectsMethod->param_begin()[0]->getType();
500   const PointerType *PtrT = T->getAs<PointerType>();
501   if (!PtrT || 
502       !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
503     Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
504       << ArrayWithObjectsMethod->getSelector();
505     Diag(ArrayWithObjectsMethod->param_begin()[0]->getLocation(),
506          diag::note_objc_literal_method_param)
507       << 0 << T 
508       << Context.getPointerType(IdT.withConst());
509     return ExprError();
510   }
511   T = PtrT->getPointeeType();
512   
513   // Check that the 'count' parameter is integral.
514   if (!ArrayWithObjectsMethod->param_begin()[1]->getType()->isIntegerType()) {
515     Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
516       << ArrayWithObjectsMethod->getSelector();
517     Diag(ArrayWithObjectsMethod->param_begin()[1]->getLocation(),
518          diag::note_objc_literal_method_param)
519       << 1 
520       << ArrayWithObjectsMethod->param_begin()[1]->getType()
521       << "integral";
522     return ExprError();
523   }
524
525   // Check that each of the elements provided is valid in a collection literal,
526   // performing conversions as necessary.
527   Expr **ElementsBuffer = Elements.get();
528   for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
529     ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
530                                                              ElementsBuffer[I],
531                                                              T);
532     if (Converted.isInvalid())
533       return ExprError();
534     
535     ElementsBuffer[I] = Converted.get();
536   }
537     
538   QualType Ty 
539     = Context.getObjCObjectPointerType(
540                                     Context.getObjCInterfaceType(NSArrayDecl));
541
542   return MaybeBindToTemporary(
543            ObjCArrayLiteral::Create(Context, 
544                                     llvm::makeArrayRef(Elements.get(), 
545                                                        Elements.size()), 
546                                     Ty, ArrayWithObjectsMethod, SR));
547 }
548
549 ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, 
550                                             ObjCDictionaryElement *Elements,
551                                             unsigned NumElements) {
552   // Look up the NSDictionary class, if we haven't done so already.
553   if (!NSDictionaryDecl) {
554     NamedDecl *IF = LookupSingleName(TUScope,
555                             NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
556                             SR.getBegin(), LookupOrdinaryName);
557     NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
558     if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
559       NSDictionaryDecl =  ObjCInterfaceDecl::Create (Context,
560                             Context.getTranslationUnitDecl(),
561                             SourceLocation(),
562                             NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
563                             0, SourceLocation());
564
565     if (!NSDictionaryDecl) {
566       Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
567       return ExprError();    
568     }
569   }
570   
571   // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
572   // so already.
573   QualType IdT = Context.getObjCIdType();
574   if (!DictionaryWithObjectsMethod) {
575     Selector Sel = NSAPIObj->getNSDictionarySelector(
576                                     NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
577     DictionaryWithObjectsMethod = NSDictionaryDecl->lookupClassMethod(Sel);
578     if (!DictionaryWithObjectsMethod && getLangOpts().DebuggerObjCLiteral) {
579       DictionaryWithObjectsMethod = 
580                          ObjCMethodDecl::Create(Context,  
581                            SourceLocation(), SourceLocation(), Sel,
582                            IdT,
583                            0 /*TypeSourceInfo */,
584                            Context.getTranslationUnitDecl(),
585                            false /*Instance*/, false/*isVariadic*/,
586                            /*isSynthesized=*/false,
587                            /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
588                            ObjCMethodDecl::Required,
589                            false);
590       SmallVector<ParmVarDecl *, 3> Params;
591       ParmVarDecl *objects = ParmVarDecl::Create(Context, DictionaryWithObjectsMethod,
592                                                 SourceLocation(), SourceLocation(),
593                                                 &Context.Idents.get("objects"),
594                                                 Context.getPointerType(IdT),
595                                                 /*TInfo=*/0,
596                                                 SC_None,
597                                                 SC_None,
598                                                 0);
599       Params.push_back(objects);
600       ParmVarDecl *keys = ParmVarDecl::Create(Context, DictionaryWithObjectsMethod,
601                                                 SourceLocation(), SourceLocation(),
602                                                 &Context.Idents.get("keys"),
603                                                 Context.getPointerType(IdT),
604                                                 /*TInfo=*/0,
605                                                 SC_None,
606                                                 SC_None,
607                                                 0);
608       Params.push_back(keys);
609       ParmVarDecl *cnt = ParmVarDecl::Create(Context, DictionaryWithObjectsMethod,
610                                                 SourceLocation(), SourceLocation(),
611                                                 &Context.Idents.get("cnt"),
612                                                 Context.UnsignedLongTy,
613                                                 /*TInfo=*/0,
614                                                 SC_None,
615                                                 SC_None,
616                                                 0);
617       Params.push_back(cnt);
618       DictionaryWithObjectsMethod->setMethodParams(Context, Params, 
619                                                    ArrayRef<SourceLocation>());
620     }
621
622     if (!DictionaryWithObjectsMethod) {
623       Diag(SR.getBegin(), diag::err_undeclared_dictwithobjects) << Sel;
624       return ExprError();    
625     }
626   }
627   
628   // Make sure the return type is reasonable.
629   if (!DictionaryWithObjectsMethod->getResultType()->isObjCObjectPointerType()){
630     Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
631     << DictionaryWithObjectsMethod->getSelector();
632     Diag(DictionaryWithObjectsMethod->getLocation(),
633          diag::note_objc_literal_method_return)
634     << DictionaryWithObjectsMethod->getResultType();
635     return ExprError();
636   }
637
638   // Dig out the type that all values should be converted to.
639   QualType ValueT =  DictionaryWithObjectsMethod->param_begin()[0]->getType();
640   const PointerType *PtrValue = ValueT->getAs<PointerType>();
641   if (!PtrValue || 
642       !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
643     Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
644       << DictionaryWithObjectsMethod->getSelector();
645     Diag(DictionaryWithObjectsMethod->param_begin()[0]->getLocation(),
646          diag::note_objc_literal_method_param)
647       << 0 << ValueT
648       << Context.getPointerType(IdT.withConst());
649     return ExprError();
650   }
651   ValueT = PtrValue->getPointeeType();
652
653   // Dig out the type that all keys should be converted to.
654   QualType KeyT = DictionaryWithObjectsMethod->param_begin()[1]->getType();
655   const PointerType *PtrKey = KeyT->getAs<PointerType>();
656   if (!PtrKey || 
657       !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
658                                       IdT)) {
659     bool err = true;
660     if (PtrKey) {
661       if (QIDNSCopying.isNull()) {
662         // key argument of selector is id<NSCopying>?
663         if (ObjCProtocolDecl *NSCopyingPDecl =
664             LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
665           ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
666           QIDNSCopying = 
667             Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
668                                       (ObjCProtocolDecl**) PQ,1);
669           QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
670         }
671       }
672       if (!QIDNSCopying.isNull())
673         err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
674                                               QIDNSCopying);
675     }
676     
677     if (err) {
678       Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
679         << DictionaryWithObjectsMethod->getSelector();
680       Diag(DictionaryWithObjectsMethod->param_begin()[1]->getLocation(),
681            diag::note_objc_literal_method_param)
682         << 1 << KeyT
683         << Context.getPointerType(IdT.withConst());
684       return ExprError();
685     }
686   }
687   KeyT = PtrKey->getPointeeType();
688
689   // Check that the 'count' parameter is integral.
690   if (!DictionaryWithObjectsMethod->param_begin()[2]->getType()
691                                                             ->isIntegerType()) {
692     Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
693       << DictionaryWithObjectsMethod->getSelector();
694     Diag(DictionaryWithObjectsMethod->param_begin()[2]->getLocation(),
695          diag::note_objc_literal_method_param)
696       << 2
697       << DictionaryWithObjectsMethod->param_begin()[2]->getType()
698       << "integral";
699     return ExprError();
700   }
701
702   // Check that each of the keys and values provided is valid in a collection 
703   // literal, performing conversions as necessary.
704   bool HasPackExpansions = false;
705   for (unsigned I = 0, N = NumElements; I != N; ++I) {
706     // Check the key.
707     ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key, 
708                                                        KeyT);
709     if (Key.isInvalid())
710       return ExprError();
711     
712     // Check the value.
713     ExprResult Value
714       = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
715     if (Value.isInvalid())
716       return ExprError();
717     
718     Elements[I].Key = Key.get();
719     Elements[I].Value = Value.get();
720     
721     if (Elements[I].EllipsisLoc.isInvalid())
722       continue;
723     
724     if (!Elements[I].Key->containsUnexpandedParameterPack() &&
725         !Elements[I].Value->containsUnexpandedParameterPack()) {
726       Diag(Elements[I].EllipsisLoc, 
727            diag::err_pack_expansion_without_parameter_packs)
728         << SourceRange(Elements[I].Key->getLocStart(),
729                        Elements[I].Value->getLocEnd());
730       return ExprError();
731     }
732     
733     HasPackExpansions = true;
734   }
735
736   
737   QualType Ty
738     = Context.getObjCObjectPointerType(
739                                 Context.getObjCInterfaceType(NSDictionaryDecl));  
740   return MaybeBindToTemporary(
741            ObjCDictionaryLiteral::Create(Context, 
742                                          llvm::makeArrayRef(Elements, 
743                                                             NumElements),
744                                          HasPackExpansions,
745                                          Ty, 
746                                          DictionaryWithObjectsMethod, SR));
747 }
748
749 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
750                                       TypeSourceInfo *EncodedTypeInfo,
751                                       SourceLocation RParenLoc) {
752   QualType EncodedType = EncodedTypeInfo->getType();
753   QualType StrTy;
754   if (EncodedType->isDependentType())
755     StrTy = Context.DependentTy;
756   else {
757     if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
758         !EncodedType->isVoidType()) // void is handled too.
759       if (RequireCompleteType(AtLoc, EncodedType,
760                          PDiag(diag::err_incomplete_type_objc_at_encode)
761                              << EncodedTypeInfo->getTypeLoc().getSourceRange()))
762         return ExprError();
763
764     std::string Str;
765     Context.getObjCEncodingForType(EncodedType, Str);
766
767     // The type of @encode is the same as the type of the corresponding string,
768     // which is an array type.
769     StrTy = Context.CharTy;
770     // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
771     if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
772       StrTy.addConst();
773     StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
774                                          ArrayType::Normal, 0);
775   }
776
777   return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
778 }
779
780 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
781                                            SourceLocation EncodeLoc,
782                                            SourceLocation LParenLoc,
783                                            ParsedType ty,
784                                            SourceLocation RParenLoc) {
785   // FIXME: Preserve type source info ?
786   TypeSourceInfo *TInfo;
787   QualType EncodedType = GetTypeFromParser(ty, &TInfo);
788   if (!TInfo)
789     TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
790                                              PP.getLocForEndOfToken(LParenLoc));
791
792   return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
793 }
794
795 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
796                                              SourceLocation AtLoc,
797                                              SourceLocation SelLoc,
798                                              SourceLocation LParenLoc,
799                                              SourceLocation RParenLoc) {
800   ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
801                              SourceRange(LParenLoc, RParenLoc), false, false);
802   if (!Method)
803     Method = LookupFactoryMethodInGlobalPool(Sel,
804                                           SourceRange(LParenLoc, RParenLoc));
805   if (!Method)
806     Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
807   
808   if (!Method ||
809       Method->getImplementationControl() != ObjCMethodDecl::Optional) {
810     llvm::DenseMap<Selector, SourceLocation>::iterator Pos
811       = ReferencedSelectors.find(Sel);
812     if (Pos == ReferencedSelectors.end())
813       ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
814   }
815
816   // In ARC, forbid the user from using @selector for 
817   // retain/release/autorelease/dealloc/retainCount.
818   if (getLangOpts().ObjCAutoRefCount) {
819     switch (Sel.getMethodFamily()) {
820     case OMF_retain:
821     case OMF_release:
822     case OMF_autorelease:
823     case OMF_retainCount:
824     case OMF_dealloc:
825       Diag(AtLoc, diag::err_arc_illegal_selector) << 
826         Sel << SourceRange(LParenLoc, RParenLoc);
827       break;
828
829     case OMF_None:
830     case OMF_alloc:
831     case OMF_copy:
832     case OMF_finalize:
833     case OMF_init:
834     case OMF_mutableCopy:
835     case OMF_new:
836     case OMF_self:
837     case OMF_performSelector:
838       break;
839     }
840   }
841   QualType Ty = Context.getObjCSelType();
842   return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
843 }
844
845 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
846                                              SourceLocation AtLoc,
847                                              SourceLocation ProtoLoc,
848                                              SourceLocation LParenLoc,
849                                              SourceLocation RParenLoc) {
850   ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
851   if (!PDecl) {
852     Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
853     return true;
854   }
855
856   QualType Ty = Context.getObjCProtoType();
857   if (Ty.isNull())
858     return true;
859   Ty = Context.getObjCObjectPointerType(Ty);
860   return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
861 }
862
863 /// Try to capture an implicit reference to 'self'.
864 ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
865   DeclContext *DC = getFunctionLevelDeclContext();
866
867   // If we're not in an ObjC method, error out.  Note that, unlike the
868   // C++ case, we don't require an instance method --- class methods
869   // still have a 'self', and we really do still need to capture it!
870   ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
871   if (!method)
872     return 0;
873
874   tryCaptureVariable(method->getSelfDecl(), Loc);
875
876   return method;
877 }
878
879 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
880   if (T == Context.getObjCInstanceType())
881     return Context.getObjCIdType();
882   
883   return T;
884 }
885
886 QualType Sema::getMessageSendResultType(QualType ReceiverType,
887                                         ObjCMethodDecl *Method,
888                                     bool isClassMessage, bool isSuperMessage) {
889   assert(Method && "Must have a method");
890   if (!Method->hasRelatedResultType())
891     return Method->getSendResultType();
892   
893   // If a method has a related return type:
894   //   - if the method found is an instance method, but the message send
895   //     was a class message send, T is the declared return type of the method
896   //     found
897   if (Method->isInstanceMethod() && isClassMessage)
898     return stripObjCInstanceType(Context, Method->getSendResultType());
899   
900   //   - if the receiver is super, T is a pointer to the class of the 
901   //     enclosing method definition
902   if (isSuperMessage) {
903     if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
904       if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
905         return Context.getObjCObjectPointerType(
906                                         Context.getObjCInterfaceType(Class));
907   }
908     
909   //   - if the receiver is the name of a class U, T is a pointer to U
910   if (ReceiverType->getAs<ObjCInterfaceType>() ||
911       ReceiverType->isObjCQualifiedInterfaceType())
912     return Context.getObjCObjectPointerType(ReceiverType);
913   //   - if the receiver is of type Class or qualified Class type, 
914   //     T is the declared return type of the method.
915   if (ReceiverType->isObjCClassType() ||
916       ReceiverType->isObjCQualifiedClassType())
917     return stripObjCInstanceType(Context, Method->getSendResultType());
918   
919   //   - if the receiver is id, qualified id, Class, or qualified Class, T
920   //     is the receiver type, otherwise
921   //   - T is the type of the receiver expression.
922   return ReceiverType;
923 }
924
925 void Sema::EmitRelatedResultTypeNote(const Expr *E) {
926   E = E->IgnoreParenImpCasts();
927   const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
928   if (!MsgSend)
929     return;
930   
931   const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
932   if (!Method)
933     return;
934   
935   if (!Method->hasRelatedResultType())
936     return;
937   
938   if (Context.hasSameUnqualifiedType(Method->getResultType()
939                                                         .getNonReferenceType(),
940                                      MsgSend->getType()))
941     return;
942   
943   if (!Context.hasSameUnqualifiedType(Method->getResultType(), 
944                                       Context.getObjCInstanceType()))
945     return;
946   
947   Diag(Method->getLocation(), diag::note_related_result_type_inferred)
948     << Method->isInstanceMethod() << Method->getSelector()
949     << MsgSend->getType();
950 }
951
952 bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
953                                      Expr **Args, unsigned NumArgs,
954                                      Selector Sel, ObjCMethodDecl *Method,
955                                      bool isClassMessage, bool isSuperMessage,
956                                      SourceLocation lbrac, SourceLocation rbrac,
957                                      QualType &ReturnType, ExprValueKind &VK) {
958   if (!Method) {
959     // Apply default argument promotion as for (C99 6.5.2.2p6).
960     for (unsigned i = 0; i != NumArgs; i++) {
961       if (Args[i]->isTypeDependent())
962         continue;
963
964       ExprResult Result = DefaultArgumentPromotion(Args[i]);
965       if (Result.isInvalid())
966         return true;
967       Args[i] = Result.take();
968     }
969
970     unsigned DiagID;
971     if (getLangOpts().ObjCAutoRefCount)
972       DiagID = diag::err_arc_method_not_found;
973     else
974       DiagID = isClassMessage ? diag::warn_class_method_not_found
975                               : diag::warn_inst_method_not_found;
976     if (!getLangOpts().DebuggerSupport)
977       Diag(lbrac, DiagID)
978         << Sel << isClassMessage << SourceRange(lbrac, rbrac);
979
980     // In debuggers, we want to use __unknown_anytype for these
981     // results so that clients can cast them.
982     if (getLangOpts().DebuggerSupport) {
983       ReturnType = Context.UnknownAnyTy;
984     } else {
985       ReturnType = Context.getObjCIdType();
986     }
987     VK = VK_RValue;
988     return false;
989   }
990
991   ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage, 
992                                         isSuperMessage);
993   VK = Expr::getValueKindForType(Method->getResultType());
994
995   unsigned NumNamedArgs = Sel.getNumArgs();
996   // Method might have more arguments than selector indicates. This is due
997   // to addition of c-style arguments in method.
998   if (Method->param_size() > Sel.getNumArgs())
999     NumNamedArgs = Method->param_size();
1000   // FIXME. This need be cleaned up.
1001   if (NumArgs < NumNamedArgs) {
1002     Diag(lbrac, diag::err_typecheck_call_too_few_args)
1003       << 2 << NumNamedArgs << NumArgs;
1004     return false;
1005   }
1006
1007   bool IsError = false;
1008   for (unsigned i = 0; i < NumNamedArgs; i++) {
1009     // We can't do any type-checking on a type-dependent argument.
1010     if (Args[i]->isTypeDependent())
1011       continue;
1012
1013     Expr *argExpr = Args[i];
1014
1015     ParmVarDecl *param = Method->param_begin()[i];
1016     assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
1017
1018     // Strip the unbridged-cast placeholder expression off unless it's
1019     // a consumed argument.
1020     if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1021         !param->hasAttr<CFConsumedAttr>())
1022       argExpr = stripARCUnbridgedCast(argExpr);
1023
1024     if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
1025                             param->getType(),
1026                             PDiag(diag::err_call_incomplete_argument)
1027                               << argExpr->getSourceRange()))
1028       return true;
1029
1030     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1031                                                                       param);
1032     ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
1033     if (ArgE.isInvalid())
1034       IsError = true;
1035     else
1036       Args[i] = ArgE.takeAs<Expr>();
1037   }
1038
1039   // Promote additional arguments to variadic methods.
1040   if (Method->isVariadic()) {
1041     for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
1042       if (Args[i]->isTypeDependent())
1043         continue;
1044
1045       ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
1046       IsError |= Arg.isInvalid();
1047       Args[i] = Arg.take();
1048     }
1049   } else {
1050     // Check for extra arguments to non-variadic methods.
1051     if (NumArgs != NumNamedArgs) {
1052       Diag(Args[NumNamedArgs]->getLocStart(),
1053            diag::err_typecheck_call_too_many_args)
1054         << 2 /*method*/ << NumNamedArgs << NumArgs
1055         << Method->getSourceRange()
1056         << SourceRange(Args[NumNamedArgs]->getLocStart(),
1057                        Args[NumArgs-1]->getLocEnd());
1058     }
1059   }
1060
1061   DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
1062
1063   // Do additional checkings on method.
1064   IsError |= CheckObjCMethodCall(Method, lbrac, Args, NumArgs);
1065
1066   return IsError;
1067 }
1068
1069 bool Sema::isSelfExpr(Expr *receiver) {
1070   // 'self' is objc 'self' in an objc method only.
1071   ObjCMethodDecl *method =
1072     dyn_cast<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1073   if (!method) return false;
1074
1075   receiver = receiver->IgnoreParenLValueCasts();
1076   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
1077     if (DRE->getDecl() == method->getSelfDecl())
1078       return true;
1079   return false;
1080 }
1081
1082 // Helper method for ActOnClassMethod/ActOnInstanceMethod.
1083 // Will search "local" class/category implementations for a method decl.
1084 // If failed, then we search in class's root for an instance method.
1085 // Returns 0 if no method is found.
1086 ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
1087                                           ObjCInterfaceDecl *ClassDecl) {
1088   ObjCMethodDecl *Method = 0;
1089   // lookup in class and all superclasses
1090   while (ClassDecl && !Method) {
1091     if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
1092       Method = ImpDecl->getClassMethod(Sel);
1093
1094     // Look through local category implementations associated with the class.
1095     if (!Method)
1096       Method = ClassDecl->getCategoryClassMethod(Sel);
1097
1098     // Before we give up, check if the selector is an instance method.
1099     // But only in the root. This matches gcc's behaviour and what the
1100     // runtime expects.
1101     if (!Method && !ClassDecl->getSuperClass()) {
1102       Method = ClassDecl->lookupInstanceMethod(Sel);
1103       // Look through local category implementations associated
1104       // with the root class.
1105       if (!Method)
1106         Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1107     }
1108
1109     ClassDecl = ClassDecl->getSuperClass();
1110   }
1111   return Method;
1112 }
1113
1114 ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
1115                                               ObjCInterfaceDecl *ClassDecl) {
1116   if (!ClassDecl->hasDefinition())
1117     return 0;
1118
1119   ObjCMethodDecl *Method = 0;
1120   while (ClassDecl && !Method) {
1121     // If we have implementations in scope, check "private" methods.
1122     if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
1123       Method = ImpDecl->getInstanceMethod(Sel);
1124
1125     // Look through local category implementations associated with the class.
1126     if (!Method)
1127       Method = ClassDecl->getCategoryInstanceMethod(Sel);
1128     ClassDecl = ClassDecl->getSuperClass();
1129   }
1130   return Method;
1131 }
1132
1133 /// LookupMethodInType - Look up a method in an ObjCObjectType.
1134 ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1135                                                bool isInstance) {
1136   const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1137   if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1138     // Look it up in the main interface (and categories, etc.)
1139     if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1140       return method;
1141
1142     // Okay, look for "private" methods declared in any
1143     // @implementations we've seen.
1144     if (isInstance) {
1145       if (ObjCMethodDecl *method = LookupPrivateInstanceMethod(sel, iface))
1146         return method;
1147     } else {
1148       if (ObjCMethodDecl *method = LookupPrivateClassMethod(sel, iface))
1149         return method;
1150     }
1151   }
1152
1153   // Check qualifiers.
1154   for (ObjCObjectType::qual_iterator
1155          i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i)
1156     if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance))
1157       return method;
1158
1159   return 0;
1160 }
1161
1162 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier 
1163 /// list of a qualified objective pointer type.
1164 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1165                                               const ObjCObjectPointerType *OPT,
1166                                               bool Instance)
1167 {
1168   ObjCMethodDecl *MD = 0;
1169   for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1170        E = OPT->qual_end(); I != E; ++I) {
1171     ObjCProtocolDecl *PROTO = (*I);
1172     if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1173       return MD;
1174     }
1175   }
1176   return 0;
1177 }
1178
1179 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1180 /// objective C interface.  This is a property reference expression.
1181 ExprResult Sema::
1182 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
1183                           Expr *BaseExpr, SourceLocation OpLoc,
1184                           DeclarationName MemberName,
1185                           SourceLocation MemberLoc,
1186                           SourceLocation SuperLoc, QualType SuperType,
1187                           bool Super) {
1188   const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1189   ObjCInterfaceDecl *IFace = IFaceT->getDecl();
1190   
1191   if (MemberName.getNameKind() != DeclarationName::Identifier) {
1192     Diag(MemberLoc, diag::err_invalid_property_name)
1193       << MemberName << QualType(OPT, 0);
1194     return ExprError();
1195   }
1196   
1197   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1198   SourceRange BaseRange = Super? SourceRange(SuperLoc)
1199                                : BaseExpr->getSourceRange();
1200   if (RequireCompleteType(MemberLoc, OPT->getPointeeType(), 
1201                           PDiag(diag::err_property_not_found_forward_class)
1202                             << MemberName << BaseRange))
1203     return ExprError();
1204   
1205   // Search for a declared property first.
1206   if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
1207     // Check whether we can reference this property.
1208     if (DiagnoseUseOfDecl(PD, MemberLoc))
1209       return ExprError();
1210              
1211     if (Super)
1212       return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
1213                                                      VK_LValue, OK_ObjCProperty,
1214                                                      MemberLoc, 
1215                                                      SuperLoc, SuperType));
1216     else
1217       return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
1218                                                      VK_LValue, OK_ObjCProperty,
1219                                                      MemberLoc, BaseExpr));
1220   }
1221   // Check protocols on qualified interfaces.
1222   for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1223        E = OPT->qual_end(); I != E; ++I)
1224     if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
1225       // Check whether we can reference this property.
1226       if (DiagnoseUseOfDecl(PD, MemberLoc))
1227         return ExprError();
1228       
1229       if (Super)
1230         return Owned(new (Context) ObjCPropertyRefExpr(PD,
1231                                                        Context.PseudoObjectTy,
1232                                                        VK_LValue,
1233                                                        OK_ObjCProperty,
1234                                                        MemberLoc, 
1235                                                        SuperLoc, SuperType));
1236       else
1237         return Owned(new (Context) ObjCPropertyRefExpr(PD,
1238                                                        Context.PseudoObjectTy,
1239                                                        VK_LValue,
1240                                                        OK_ObjCProperty,
1241                                                        MemberLoc,
1242                                                        BaseExpr));
1243     }
1244   // If that failed, look for an "implicit" property by seeing if the nullary
1245   // selector is implemented.
1246
1247   // FIXME: The logic for looking up nullary and unary selectors should be
1248   // shared with the code in ActOnInstanceMessage.
1249
1250   Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1251   ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1252   
1253   // May be founf in property's qualified list.
1254   if (!Getter)
1255     Getter = LookupMethodInQualifiedType(Sel, OPT, true);
1256
1257   // If this reference is in an @implementation, check for 'private' methods.
1258   if (!Getter)
1259     Getter = IFace->lookupPrivateMethod(Sel);
1260
1261   // Look through local category implementations associated with the class.
1262   if (!Getter)
1263     Getter = IFace->getCategoryInstanceMethod(Sel);
1264   if (Getter) {
1265     // Check if we can reference this property.
1266     if (DiagnoseUseOfDecl(Getter, MemberLoc))
1267       return ExprError();
1268   }
1269   // If we found a getter then this may be a valid dot-reference, we
1270   // will look for the matching setter, in case it is needed.
1271   Selector SetterSel =
1272     SelectorTable::constructSetterName(PP.getIdentifierTable(),
1273                                        PP.getSelectorTable(), Member);
1274   ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1275   
1276   // May be founf in property's qualified list.
1277   if (!Setter)
1278     Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1279   
1280   if (!Setter) {
1281     // If this reference is in an @implementation, also check for 'private'
1282     // methods.
1283     Setter = IFace->lookupPrivateMethod(SetterSel);
1284   }
1285   // Look through local category implementations associated with the class.
1286   if (!Setter)
1287     Setter = IFace->getCategoryInstanceMethod(SetterSel);
1288     
1289   if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1290     return ExprError();
1291
1292   if (Getter || Setter) {
1293     if (Super)
1294       return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1295                                                      Context.PseudoObjectTy,
1296                                                      VK_LValue, OK_ObjCProperty,
1297                                                      MemberLoc,
1298                                                      SuperLoc, SuperType));
1299     else
1300       return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1301                                                      Context.PseudoObjectTy,
1302                                                      VK_LValue, OK_ObjCProperty,
1303                                                      MemberLoc, BaseExpr));
1304
1305   }
1306
1307   // Attempt to correct for typos in property names.
1308   DeclFilterCCC<ObjCPropertyDecl> Validator;
1309   if (TypoCorrection Corrected = CorrectTypo(
1310       DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
1311       NULL, Validator, IFace, false, OPT)) {
1312     ObjCPropertyDecl *Property =
1313         Corrected.getCorrectionDeclAs<ObjCPropertyDecl>();
1314     DeclarationName TypoResult = Corrected.getCorrection();
1315     Diag(MemberLoc, diag::err_property_not_found_suggest)
1316       << MemberName << QualType(OPT, 0) << TypoResult
1317       << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
1318     Diag(Property->getLocation(), diag::note_previous_decl)
1319       << Property->getDeclName();
1320     return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1321                                      TypoResult, MemberLoc,
1322                                      SuperLoc, SuperType, Super);
1323   }
1324   ObjCInterfaceDecl *ClassDeclared;
1325   if (ObjCIvarDecl *Ivar = 
1326       IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1327     QualType T = Ivar->getType();
1328     if (const ObjCObjectPointerType * OBJPT = 
1329         T->getAsObjCInterfacePointerType()) {
1330       if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(), 
1331                               PDiag(diag::err_property_not_as_forward_class)
1332                                 << MemberName << BaseExpr->getSourceRange()))
1333         return ExprError();
1334     }
1335     Diag(MemberLoc, 
1336          diag::err_ivar_access_using_property_syntax_suggest)
1337     << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1338     << FixItHint::CreateReplacement(OpLoc, "->");
1339     return ExprError();
1340   }
1341   
1342   Diag(MemberLoc, diag::err_property_not_found)
1343     << MemberName << QualType(OPT, 0);
1344   if (Setter)
1345     Diag(Setter->getLocation(), diag::note_getter_unavailable)
1346           << MemberName << BaseExpr->getSourceRange();
1347   return ExprError();
1348 }
1349
1350
1351
1352 ExprResult Sema::
1353 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1354                           IdentifierInfo &propertyName,
1355                           SourceLocation receiverNameLoc,
1356                           SourceLocation propertyNameLoc) {
1357
1358   IdentifierInfo *receiverNamePtr = &receiverName;
1359   ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1360                                                   receiverNameLoc);
1361
1362   bool IsSuper = false;
1363   if (IFace == 0) {
1364     // If the "receiver" is 'super' in a method, handle it as an expression-like
1365     // property reference.
1366     if (receiverNamePtr->isStr("super")) {
1367       IsSuper = true;
1368
1369       if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
1370         if (CurMethod->isInstanceMethod()) {
1371           QualType T = 
1372             Context.getObjCInterfaceType(CurMethod->getClassInterface());
1373           T = Context.getObjCObjectPointerType(T);
1374         
1375           return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
1376                                            /*BaseExpr*/0, 
1377                                            SourceLocation()/*OpLoc*/, 
1378                                            &propertyName,
1379                                            propertyNameLoc,
1380                                            receiverNameLoc, T, true);
1381         }
1382
1383         // Otherwise, if this is a class method, try dispatching to our
1384         // superclass.
1385         IFace = CurMethod->getClassInterface()->getSuperClass();
1386       }
1387     }
1388     
1389     if (IFace == 0) {
1390       Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
1391       return ExprError();
1392     }
1393   }
1394
1395   // Search for a declared property first.
1396   Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
1397   ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
1398
1399   // If this reference is in an @implementation, check for 'private' methods.
1400   if (!Getter)
1401     if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1402       if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1403         if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
1404           Getter = ImpDecl->getClassMethod(Sel);
1405
1406   if (Getter) {
1407     // FIXME: refactor/share with ActOnMemberReference().
1408     // Check if we can reference this property.
1409     if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1410       return ExprError();
1411   }
1412
1413   // Look for the matching setter, in case it is needed.
1414   Selector SetterSel =
1415     SelectorTable::constructSetterName(PP.getIdentifierTable(),
1416                                        PP.getSelectorTable(), &propertyName);
1417
1418   ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1419   if (!Setter) {
1420     // If this reference is in an @implementation, also check for 'private'
1421     // methods.
1422     if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1423       if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1424         if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
1425           Setter = ImpDecl->getClassMethod(SetterSel);
1426   }
1427   // Look through local category implementations associated with the class.
1428   if (!Setter)
1429     Setter = IFace->getCategoryClassMethod(SetterSel);
1430
1431   if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1432     return ExprError();
1433
1434   if (Getter || Setter) {
1435     if (IsSuper)
1436     return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1437                                                    Context.PseudoObjectTy,
1438                                                    VK_LValue, OK_ObjCProperty,
1439                                                    propertyNameLoc,
1440                                                    receiverNameLoc, 
1441                                           Context.getObjCInterfaceType(IFace)));
1442
1443     return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1444                                                    Context.PseudoObjectTy,
1445                                                    VK_LValue, OK_ObjCProperty,
1446                                                    propertyNameLoc,
1447                                                    receiverNameLoc, IFace));
1448   }
1449   return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1450                      << &propertyName << Context.getObjCInterfaceType(IFace));
1451 }
1452
1453 namespace {
1454
1455 class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1456  public:
1457   ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1458     // Determine whether "super" is acceptable in the current context.
1459     if (Method && Method->getClassInterface())
1460       WantObjCSuper = Method->getClassInterface()->getSuperClass();
1461   }
1462
1463   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1464     return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1465         candidate.isKeyword("super");
1466   }
1467 };
1468
1469 }
1470
1471 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
1472                                                IdentifierInfo *Name,
1473                                                SourceLocation NameLoc,
1474                                                bool IsSuper,
1475                                                bool HasTrailingDot,
1476                                                ParsedType &ReceiverType) {
1477   ReceiverType = ParsedType();
1478
1479   // If the identifier is "super" and there is no trailing dot, we're
1480   // messaging super. If the identifier is "super" and there is a
1481   // trailing dot, it's an instance message.
1482   if (IsSuper && S->isInObjcMethodScope())
1483     return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
1484   
1485   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1486   LookupName(Result, S);
1487   
1488   switch (Result.getResultKind()) {
1489   case LookupResult::NotFound:
1490     // Normal name lookup didn't find anything. If we're in an
1491     // Objective-C method, look for ivars. If we find one, we're done!
1492     // FIXME: This is a hack. Ivar lookup should be part of normal
1493     // lookup.
1494     if (ObjCMethodDecl *Method = getCurMethodDecl()) {
1495       if (!Method->getClassInterface()) {
1496         // Fall back: let the parser try to parse it as an instance message.
1497         return ObjCInstanceMessage;
1498       }
1499
1500       ObjCInterfaceDecl *ClassDeclared;
1501       if (Method->getClassInterface()->lookupInstanceVariable(Name, 
1502                                                               ClassDeclared))
1503         return ObjCInstanceMessage;
1504     }
1505   
1506     // Break out; we'll perform typo correction below.
1507     break;
1508
1509   case LookupResult::NotFoundInCurrentInstantiation:
1510   case LookupResult::FoundOverloaded:
1511   case LookupResult::FoundUnresolvedValue:
1512   case LookupResult::Ambiguous:
1513     Result.suppressDiagnostics();
1514     return ObjCInstanceMessage;
1515
1516   case LookupResult::Found: {
1517     // If the identifier is a class or not, and there is a trailing dot,
1518     // it's an instance message.
1519     if (HasTrailingDot)
1520       return ObjCInstanceMessage;
1521     // We found something. If it's a type, then we have a class
1522     // message. Otherwise, it's an instance message.
1523     NamedDecl *ND = Result.getFoundDecl();
1524     QualType T;
1525     if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1526       T = Context.getObjCInterfaceType(Class);
1527     else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
1528       T = Context.getTypeDeclType(Type);
1529     else 
1530       return ObjCInstanceMessage;
1531
1532     //  We have a class message, and T is the type we're
1533     //  messaging. Build source-location information for it.
1534     TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1535     ReceiverType = CreateParsedType(T, TSInfo);
1536     return ObjCClassMessage;
1537   }
1538   }
1539
1540   ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
1541   if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
1542                                              Result.getLookupKind(), S, NULL,
1543                                              Validator)) {
1544     if (Corrected.isKeyword()) {
1545       // If we've found the keyword "super" (the only keyword that would be
1546       // returned by CorrectTypo), this is a send to super.
1547       Diag(NameLoc, diag::err_unknown_receiver_suggest)
1548         << Name << Corrected.getCorrection()
1549         << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
1550       return ObjCSuperMessage;
1551     } else if (ObjCInterfaceDecl *Class =
1552                Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1553       // If we found a declaration, correct when it refers to an Objective-C
1554       // class.
1555       Diag(NameLoc, diag::err_unknown_receiver_suggest)
1556         << Name << Corrected.getCorrection()
1557         << FixItHint::CreateReplacement(SourceRange(NameLoc),
1558                                         Class->getNameAsString());
1559       Diag(Class->getLocation(), diag::note_previous_decl)
1560         << Corrected.getCorrection();
1561
1562       QualType T = Context.getObjCInterfaceType(Class);
1563       TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1564       ReceiverType = CreateParsedType(T, TSInfo);
1565       return ObjCClassMessage;
1566     }
1567   }
1568   
1569   // Fall back: let the parser try to parse it as an instance message.
1570   return ObjCInstanceMessage;
1571 }
1572
1573 ExprResult Sema::ActOnSuperMessage(Scope *S, 
1574                                    SourceLocation SuperLoc,
1575                                    Selector Sel,
1576                                    SourceLocation LBracLoc,
1577                                    ArrayRef<SourceLocation> SelectorLocs,
1578                                    SourceLocation RBracLoc,
1579                                    MultiExprArg Args) {
1580   // Determine whether we are inside a method or not.
1581   ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
1582   if (!Method) {
1583     Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1584     return ExprError();
1585   }
1586
1587   ObjCInterfaceDecl *Class = Method->getClassInterface();
1588   if (!Class) {
1589     Diag(SuperLoc, diag::error_no_super_class_message)
1590       << Method->getDeclName();
1591     return ExprError();
1592   }
1593
1594   ObjCInterfaceDecl *Super = Class->getSuperClass();
1595   if (!Super) {
1596     // The current class does not have a superclass.
1597     Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1598       << Class->getIdentifier();
1599     return ExprError();
1600   }
1601
1602   // We are in a method whose class has a superclass, so 'super'
1603   // is acting as a keyword.
1604   if (Method->isInstanceMethod()) {
1605     if (Sel.getMethodFamily() == OMF_dealloc)
1606       ObjCShouldCallSuperDealloc = false;
1607     if (Sel.getMethodFamily() == OMF_finalize)
1608       ObjCShouldCallSuperFinalize = false;
1609
1610     // Since we are in an instance method, this is an instance
1611     // message to the superclass instance.
1612     QualType SuperTy = Context.getObjCInterfaceType(Super);
1613     SuperTy = Context.getObjCObjectPointerType(SuperTy);
1614     return BuildInstanceMessage(0, SuperTy, SuperLoc,
1615                                 Sel, /*Method=*/0,
1616                                 LBracLoc, SelectorLocs, RBracLoc, move(Args));
1617   }
1618   
1619   // Since we are in a class method, this is a class message to
1620   // the superclass.
1621   return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1622                            Context.getObjCInterfaceType(Super),
1623                            SuperLoc, Sel, /*Method=*/0,
1624                            LBracLoc, SelectorLocs, RBracLoc, move(Args));
1625 }
1626
1627
1628 ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1629                                            bool isSuperReceiver,
1630                                            SourceLocation Loc,
1631                                            Selector Sel,
1632                                            ObjCMethodDecl *Method,
1633                                            MultiExprArg Args) {
1634   TypeSourceInfo *receiverTypeInfo = 0;
1635   if (!ReceiverType.isNull())
1636     receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1637
1638   return BuildClassMessage(receiverTypeInfo, ReceiverType,
1639                           /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1640                            Sel, Method, Loc, Loc, Loc, Args,
1641                            /*isImplicit=*/true);
1642
1643 }
1644
1645 static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
1646                                unsigned DiagID,
1647                                bool (*refactor)(const ObjCMessageExpr *,
1648                                               const NSAPI &, edit::Commit &)) {
1649   SourceLocation MsgLoc = Msg->getExprLoc();
1650   if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
1651     return;
1652
1653   SourceManager &SM = S.SourceMgr;
1654   edit::Commit ECommit(SM, S.LangOpts);
1655   if (refactor(Msg,*S.NSAPIObj, ECommit)) {
1656     DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
1657                         << Msg->getSelector() << Msg->getSourceRange();
1658     // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
1659     if (!ECommit.isCommitable())
1660       return;
1661     for (edit::Commit::edit_iterator
1662            I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
1663       const edit::Commit::Edit &Edit = *I;
1664       switch (Edit.Kind) {
1665       case edit::Commit::Act_Insert:
1666         Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
1667                                                         Edit.Text,
1668                                                         Edit.BeforePrev));
1669         break;
1670       case edit::Commit::Act_InsertFromRange:
1671         Builder.AddFixItHint(
1672             FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
1673                                                 Edit.getInsertFromRange(SM),
1674                                                 Edit.BeforePrev));
1675         break;
1676       case edit::Commit::Act_Remove:
1677         Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
1678         break;
1679       }
1680     }
1681   }
1682 }
1683
1684 static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
1685   applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
1686                      edit::rewriteObjCRedundantCallWithLiteral);
1687 }
1688
1689 /// \brief Build an Objective-C class message expression.
1690 ///
1691 /// This routine takes care of both normal class messages and
1692 /// class messages to the superclass.
1693 ///
1694 /// \param ReceiverTypeInfo Type source information that describes the
1695 /// receiver of this message. This may be NULL, in which case we are
1696 /// sending to the superclass and \p SuperLoc must be a valid source
1697 /// location.
1698
1699 /// \param ReceiverType The type of the object receiving the
1700 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1701 /// type as that refers to. For a superclass send, this is the type of
1702 /// the superclass.
1703 ///
1704 /// \param SuperLoc The location of the "super" keyword in a
1705 /// superclass message.
1706 ///
1707 /// \param Sel The selector to which the message is being sent.
1708 ///
1709 /// \param Method The method that this class message is invoking, if
1710 /// already known.
1711 ///
1712 /// \param LBracLoc The location of the opening square bracket ']'.
1713 ///
1714 /// \param RBrac The location of the closing square bracket ']'.
1715 ///
1716 /// \param Args The message arguments.
1717 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
1718                                    QualType ReceiverType,
1719                                    SourceLocation SuperLoc,
1720                                    Selector Sel,
1721                                    ObjCMethodDecl *Method,
1722                                    SourceLocation LBracLoc, 
1723                                    ArrayRef<SourceLocation> SelectorLocs,
1724                                    SourceLocation RBracLoc,
1725                                    MultiExprArg ArgsIn,
1726                                    bool isImplicit) {
1727   SourceLocation Loc = SuperLoc.isValid()? SuperLoc
1728     : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
1729   if (LBracLoc.isInvalid()) {
1730     Diag(Loc, diag::err_missing_open_square_message_send)
1731       << FixItHint::CreateInsertion(Loc, "[");
1732     LBracLoc = Loc;
1733   }
1734   
1735   if (ReceiverType->isDependentType()) {
1736     // If the receiver type is dependent, we can't type-check anything
1737     // at this point. Build a dependent expression.
1738     unsigned NumArgs = ArgsIn.size();
1739     Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1740     assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1741     return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1742                                          VK_RValue, LBracLoc, ReceiverTypeInfo,
1743                                          Sel, SelectorLocs, /*Method=*/0,
1744                                          makeArrayRef(Args, NumArgs),RBracLoc,
1745                                          isImplicit));
1746   }
1747   
1748   // Find the class to which we are sending this message.
1749   ObjCInterfaceDecl *Class = 0;
1750   const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1751   if (!ClassType || !(Class = ClassType->getInterface())) {
1752     Diag(Loc, diag::err_invalid_receiver_class_message)
1753       << ReceiverType;
1754     return ExprError();
1755   }
1756   assert(Class && "We don't know which class we're messaging?");
1757   // objc++ diagnoses during typename annotation.
1758   if (!getLangOpts().CPlusPlus)
1759     (void)DiagnoseUseOfDecl(Class, Loc);
1760   // Find the method we are messaging.
1761   if (!Method) {
1762     SourceRange TypeRange 
1763       = SuperLoc.isValid()? SourceRange(SuperLoc)
1764                           : ReceiverTypeInfo->getTypeLoc().getSourceRange();
1765     if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class), 
1766                             (getLangOpts().ObjCAutoRefCount
1767                                ? PDiag(diag::err_arc_receiver_forward_class)
1768                                : PDiag(diag::warn_receiver_forward_class))
1769                                    << TypeRange)) {
1770       // A forward class used in messaging is treated as a 'Class'
1771       Method = LookupFactoryMethodInGlobalPool(Sel, 
1772                                                SourceRange(LBracLoc, RBracLoc));
1773       if (Method && !getLangOpts().ObjCAutoRefCount)
1774         Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1775           << Method->getDeclName();
1776     }
1777     if (!Method)
1778       Method = Class->lookupClassMethod(Sel);
1779
1780     // If we have an implementation in scope, check "private" methods.
1781     if (!Method)
1782       Method = LookupPrivateClassMethod(Sel, Class);
1783
1784     if (Method && DiagnoseUseOfDecl(Method, Loc))
1785       return ExprError();
1786   }
1787
1788   // Check the argument types and determine the result type.
1789   QualType ReturnType;
1790   ExprValueKind VK = VK_RValue;
1791
1792   unsigned NumArgs = ArgsIn.size();
1793   Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1794   if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1795                                 SuperLoc.isValid(), LBracLoc, RBracLoc, 
1796                                 ReturnType, VK))
1797     return ExprError();
1798
1799   if (Method && !Method->getResultType()->isVoidType() &&
1800       RequireCompleteType(LBracLoc, Method->getResultType(), 
1801                           diag::err_illegal_message_expr_incomplete_type))
1802     return ExprError();
1803
1804   // Construct the appropriate ObjCMessageExpr.
1805   ObjCMessageExpr *Result;
1806   if (SuperLoc.isValid())
1807     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 
1808                                      SuperLoc, /*IsInstanceSuper=*/false, 
1809                                      ReceiverType, Sel, SelectorLocs,
1810                                      Method, makeArrayRef(Args, NumArgs),
1811                                      RBracLoc, isImplicit);
1812   else {
1813     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 
1814                                      ReceiverTypeInfo, Sel, SelectorLocs,
1815                                      Method, makeArrayRef(Args, NumArgs),
1816                                      RBracLoc, isImplicit);
1817     if (!isImplicit)
1818       checkCocoaAPI(*this, Result);
1819   }
1820   return MaybeBindToTemporary(Result);
1821 }
1822
1823 // ActOnClassMessage - used for both unary and keyword messages.
1824 // ArgExprs is optional - if it is present, the number of expressions
1825 // is obtained from Sel.getNumArgs().
1826 ExprResult Sema::ActOnClassMessage(Scope *S, 
1827                                    ParsedType Receiver,
1828                                    Selector Sel,
1829                                    SourceLocation LBracLoc,
1830                                    ArrayRef<SourceLocation> SelectorLocs,
1831                                    SourceLocation RBracLoc,
1832                                    MultiExprArg Args) {
1833   TypeSourceInfo *ReceiverTypeInfo;
1834   QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1835   if (ReceiverType.isNull())
1836     return ExprError();
1837
1838
1839   if (!ReceiverTypeInfo)
1840     ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1841
1842   return BuildClassMessage(ReceiverTypeInfo, ReceiverType, 
1843                            /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
1844                            LBracLoc, SelectorLocs, RBracLoc, move(Args));
1845 }
1846
1847 ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
1848                                               QualType ReceiverType,
1849                                               SourceLocation Loc,
1850                                               Selector Sel,
1851                                               ObjCMethodDecl *Method,
1852                                               MultiExprArg Args) {
1853   return BuildInstanceMessage(Receiver, ReceiverType,
1854                               /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
1855                               Sel, Method, Loc, Loc, Loc, Args,
1856                               /*isImplicit=*/true);
1857 }
1858
1859 /// \brief Build an Objective-C instance message expression.
1860 ///
1861 /// This routine takes care of both normal instance messages and
1862 /// instance messages to the superclass instance.
1863 ///
1864 /// \param Receiver The expression that computes the object that will
1865 /// receive this message. This may be empty, in which case we are
1866 /// sending to the superclass instance and \p SuperLoc must be a valid
1867 /// source location.
1868 ///
1869 /// \param ReceiverType The (static) type of the object receiving the
1870 /// message. When a \p Receiver expression is provided, this is the
1871 /// same type as that expression. For a superclass instance send, this
1872 /// is a pointer to the type of the superclass.
1873 ///
1874 /// \param SuperLoc The location of the "super" keyword in a
1875 /// superclass instance message.
1876 ///
1877 /// \param Sel The selector to which the message is being sent.
1878 ///
1879 /// \param Method The method that this instance message is invoking, if
1880 /// already known.
1881 ///
1882 /// \param LBracLoc The location of the opening square bracket ']'.
1883 ///
1884 /// \param RBrac The location of the closing square bracket ']'.
1885 ///
1886 /// \param Args The message arguments.
1887 ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
1888                                       QualType ReceiverType,
1889                                       SourceLocation SuperLoc,
1890                                       Selector Sel,
1891                                       ObjCMethodDecl *Method,
1892                                       SourceLocation LBracLoc, 
1893                                       ArrayRef<SourceLocation> SelectorLocs,
1894                                       SourceLocation RBracLoc,
1895                                       MultiExprArg ArgsIn,
1896                                       bool isImplicit) {
1897   // The location of the receiver.
1898   SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1899   
1900   if (LBracLoc.isInvalid()) {
1901     Diag(Loc, diag::err_missing_open_square_message_send)
1902       << FixItHint::CreateInsertion(Loc, "[");
1903     LBracLoc = Loc;
1904   }
1905
1906   // If we have a receiver expression, perform appropriate promotions
1907   // and determine receiver type.
1908   if (Receiver) {
1909     if (Receiver->hasPlaceholderType()) {
1910       ExprResult Result;
1911       if (Receiver->getType() == Context.UnknownAnyTy)
1912         Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
1913       else
1914         Result = CheckPlaceholderExpr(Receiver);
1915       if (Result.isInvalid()) return ExprError();
1916       Receiver = Result.take();
1917     }
1918
1919     if (Receiver->isTypeDependent()) {
1920       // If the receiver is type-dependent, we can't type-check anything
1921       // at this point. Build a dependent expression.
1922       unsigned NumArgs = ArgsIn.size();
1923       Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1924       assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1925       return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
1926                                            VK_RValue, LBracLoc, Receiver, Sel, 
1927                                            SelectorLocs, /*Method=*/0,
1928                                            makeArrayRef(Args, NumArgs),
1929                                            RBracLoc, isImplicit));
1930     }
1931
1932     // If necessary, apply function/array conversion to the receiver.
1933     // C99 6.7.5.3p[7,8].
1934     ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1935     if (Result.isInvalid())
1936       return ExprError();
1937     Receiver = Result.take();
1938     ReceiverType = Receiver->getType();
1939   }
1940
1941   if (!Method) {
1942     // Handle messages to id.
1943     bool receiverIsId = ReceiverType->isObjCIdType();
1944     if (receiverIsId || ReceiverType->isBlockPointerType() ||
1945         (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1946       Method = LookupInstanceMethodInGlobalPool(Sel, 
1947                                                 SourceRange(LBracLoc, RBracLoc),
1948                                                 receiverIsId);
1949       if (!Method)
1950         Method = LookupFactoryMethodInGlobalPool(Sel, 
1951                                                  SourceRange(LBracLoc, RBracLoc),
1952                                                  receiverIsId);
1953     } else if (ReceiverType->isObjCClassType() ||
1954                ReceiverType->isObjCQualifiedClassType()) {
1955       // Handle messages to Class.
1956       // We allow sending a message to a qualified Class ("Class<foo>"), which 
1957       // is ok as long as one of the protocols implements the selector (if not, warn).
1958       if (const ObjCObjectPointerType *QClassTy 
1959             = ReceiverType->getAsObjCQualifiedClassType()) {
1960         // Search protocols for class methods.
1961         Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1962         if (!Method) {
1963           Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1964           // warn if instance method found for a Class message.
1965           if (Method) {
1966             Diag(Loc, diag::warn_instance_method_on_class_found)
1967               << Method->getSelector() << Sel;
1968             Diag(Method->getLocation(), diag::note_method_declared_at)
1969               << Method->getDeclName();
1970           }
1971         }
1972       } else {
1973         if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1974           if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1975             // First check the public methods in the class interface.
1976             Method = ClassDecl->lookupClassMethod(Sel);
1977
1978             if (!Method)
1979               Method = LookupPrivateClassMethod(Sel, ClassDecl);
1980           }
1981           if (Method && DiagnoseUseOfDecl(Method, Loc))
1982             return ExprError();
1983         }
1984         if (!Method) {
1985           // If not messaging 'self', look for any factory method named 'Sel'.
1986           if (!Receiver || !isSelfExpr(Receiver)) {
1987             Method = LookupFactoryMethodInGlobalPool(Sel, 
1988                                                 SourceRange(LBracLoc, RBracLoc),
1989                                                      true);
1990             if (!Method) {
1991               // If no class (factory) method was found, check if an _instance_
1992               // method of the same name exists in the root class only.
1993               Method = LookupInstanceMethodInGlobalPool(Sel,
1994                                                SourceRange(LBracLoc, RBracLoc),
1995                                                         true);
1996               if (Method)
1997                   if (const ObjCInterfaceDecl *ID =
1998                       dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1999                     if (ID->getSuperClass())
2000                       Diag(Loc, diag::warn_root_inst_method_not_found)
2001                       << Sel << SourceRange(LBracLoc, RBracLoc);
2002                   }
2003             }
2004           }
2005         }
2006       }
2007     } else {
2008       ObjCInterfaceDecl* ClassDecl = 0;
2009
2010       // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2011       // long as one of the protocols implements the selector (if not, warn).
2012       if (const ObjCObjectPointerType *QIdTy 
2013                                    = ReceiverType->getAsObjCQualifiedIdType()) {
2014         // Search protocols for instance methods.
2015         Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2016         if (!Method)
2017           Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
2018       } else if (const ObjCObjectPointerType *OCIType
2019                    = ReceiverType->getAsObjCInterfacePointerType()) {
2020         // We allow sending a message to a pointer to an interface (an object).
2021         ClassDecl = OCIType->getInterfaceDecl();
2022
2023         // Try to complete the type. Under ARC, this is a hard error from which
2024         // we don't try to recover.
2025         const ObjCInterfaceDecl *forwardClass = 0;
2026         if (RequireCompleteType(Loc, OCIType->getPointeeType(),
2027               getLangOpts().ObjCAutoRefCount
2028                 ? PDiag(diag::err_arc_receiver_forward_instance)
2029                     << (Receiver ? Receiver->getSourceRange() 
2030                                  : SourceRange(SuperLoc))
2031                 : PDiag(diag::warn_receiver_forward_instance)
2032                     << (Receiver ? Receiver->getSourceRange() 
2033                                  : SourceRange(SuperLoc)))) {
2034           if (getLangOpts().ObjCAutoRefCount)
2035             return ExprError();
2036           
2037           forwardClass = OCIType->getInterfaceDecl();
2038           Diag(Receiver ? Receiver->getLocStart() 
2039                         : SuperLoc, diag::note_receiver_is_id);
2040           Method = 0;
2041         } else {
2042           Method = ClassDecl->lookupInstanceMethod(Sel);
2043         }
2044
2045         if (!Method)
2046           // Search protocol qualifiers.
2047           Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2048         
2049         if (!Method) {
2050           // If we have implementations in scope, check "private" methods.
2051           Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
2052
2053           if (!Method && getLangOpts().ObjCAutoRefCount) {
2054             Diag(Loc, diag::err_arc_may_not_respond)
2055               << OCIType->getPointeeType() << Sel;
2056             return ExprError();
2057           }
2058
2059           if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
2060             // If we still haven't found a method, look in the global pool. This
2061             // behavior isn't very desirable, however we need it for GCC
2062             // compatibility. FIXME: should we deviate??
2063             if (OCIType->qual_empty()) {
2064               Method = LookupInstanceMethodInGlobalPool(Sel,
2065                                                  SourceRange(LBracLoc, RBracLoc));
2066               if (Method && !forwardClass)
2067                 Diag(Loc, diag::warn_maynot_respond)
2068                   << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
2069             }
2070           }
2071         }
2072         if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
2073           return ExprError();
2074       } else if (!getLangOpts().ObjCAutoRefCount &&
2075                  !Context.getObjCIdType().isNull() &&
2076                  (ReceiverType->isPointerType() || 
2077                   ReceiverType->isIntegerType())) {
2078         // Implicitly convert integers and pointers to 'id' but emit a warning.
2079         // But not in ARC.
2080         Diag(Loc, diag::warn_bad_receiver_type)
2081           << ReceiverType 
2082           << Receiver->getSourceRange();
2083         if (ReceiverType->isPointerType())
2084           Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(), 
2085                             CK_CPointerToObjCPointerCast).take();
2086         else {
2087           // TODO: specialized warning on null receivers?
2088           bool IsNull = Receiver->isNullPointerConstant(Context,
2089                                               Expr::NPC_ValueDependentIsNull);
2090           Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2091                             IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
2092         }
2093         ReceiverType = Receiver->getType();
2094       } else {
2095         ExprResult ReceiverRes;
2096         if (getLangOpts().CPlusPlus)
2097           ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
2098         if (ReceiverRes.isUsable()) {
2099           Receiver = ReceiverRes.take();
2100           return BuildInstanceMessage(Receiver,
2101                                       ReceiverType,
2102                                       SuperLoc,
2103                                       Sel,
2104                                       Method,
2105                                       LBracLoc,
2106                                       SelectorLocs,
2107                                       RBracLoc,
2108                                       move(ArgsIn));
2109         } else {
2110           // Reject other random receiver types (e.g. structs).
2111           Diag(Loc, diag::err_bad_receiver_type)
2112             << ReceiverType << Receiver->getSourceRange();
2113           return ExprError();
2114         }
2115       }
2116     }
2117   }
2118
2119   // Check the message arguments.
2120   unsigned NumArgs = ArgsIn.size();
2121   Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
2122   QualType ReturnType;
2123   ExprValueKind VK = VK_RValue;
2124   bool ClassMessage = (ReceiverType->isObjCClassType() ||
2125                        ReceiverType->isObjCQualifiedClassType());
2126   if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, 
2127                                 ClassMessage, SuperLoc.isValid(), 
2128                                 LBracLoc, RBracLoc, ReturnType, VK))
2129     return ExprError();
2130   
2131   if (Method && !Method->getResultType()->isVoidType() &&
2132       RequireCompleteType(LBracLoc, Method->getResultType(), 
2133                           diag::err_illegal_message_expr_incomplete_type))
2134     return ExprError();
2135
2136   SourceLocation SelLoc = SelectorLocs.front();
2137
2138   // In ARC, forbid the user from sending messages to 
2139   // retain/release/autorelease/dealloc/retainCount explicitly.
2140   if (getLangOpts().ObjCAutoRefCount) {
2141     ObjCMethodFamily family =
2142       (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2143     switch (family) {
2144     case OMF_init:
2145       if (Method)
2146         checkInitMethod(Method, ReceiverType);
2147
2148     case OMF_None:
2149     case OMF_alloc:
2150     case OMF_copy:
2151     case OMF_finalize:
2152     case OMF_mutableCopy:
2153     case OMF_new:
2154     case OMF_self:
2155       break;
2156
2157     case OMF_dealloc:
2158     case OMF_retain:
2159     case OMF_release:
2160     case OMF_autorelease:
2161     case OMF_retainCount:
2162       Diag(Loc, diag::err_arc_illegal_explicit_message)
2163         << Sel << SelLoc;
2164       break;
2165     
2166     case OMF_performSelector:
2167       if (Method && NumArgs >= 1) {
2168         if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2169           Selector ArgSel = SelExp->getSelector();
2170           ObjCMethodDecl *SelMethod = 
2171             LookupInstanceMethodInGlobalPool(ArgSel,
2172                                              SelExp->getSourceRange());
2173           if (!SelMethod)
2174             SelMethod =
2175               LookupFactoryMethodInGlobalPool(ArgSel,
2176                                               SelExp->getSourceRange());
2177           if (SelMethod) {
2178             ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2179             switch (SelFamily) {
2180               case OMF_alloc:
2181               case OMF_copy:
2182               case OMF_mutableCopy:
2183               case OMF_new:
2184               case OMF_self:
2185               case OMF_init:
2186                 // Issue error, unless ns_returns_not_retained.
2187                 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2188                   // selector names a +1 method 
2189                   Diag(SelLoc, 
2190                        diag::err_arc_perform_selector_retains);
2191                   Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2192                     << SelMethod->getDeclName();
2193                 }
2194                 break;
2195               default:
2196                 // +0 call. OK. unless ns_returns_retained.
2197                 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2198                   // selector names a +1 method
2199                   Diag(SelLoc, 
2200                        diag::err_arc_perform_selector_retains);
2201                   Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2202                     << SelMethod->getDeclName();
2203                 }
2204                 break;
2205             }
2206           }
2207         } else {
2208           // error (may leak).
2209           Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
2210           Diag(Args[0]->getExprLoc(), diag::note_used_here);
2211         }
2212       }
2213       break;
2214     }
2215   }
2216
2217   // Construct the appropriate ObjCMessageExpr instance.
2218   ObjCMessageExpr *Result;
2219   if (SuperLoc.isValid())
2220     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2221                                      SuperLoc,  /*IsInstanceSuper=*/true,
2222                                      ReceiverType, Sel, SelectorLocs, Method, 
2223                                      makeArrayRef(Args, NumArgs), RBracLoc,
2224                                      isImplicit);
2225   else {
2226     Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2227                                      Receiver, Sel, SelectorLocs, Method,
2228                                      makeArrayRef(Args, NumArgs), RBracLoc,
2229                                      isImplicit);
2230     if (!isImplicit)
2231       checkCocoaAPI(*this, Result);
2232   }
2233
2234   if (getLangOpts().ObjCAutoRefCount) {
2235     if (Receiver &&
2236         (Receiver->IgnoreParenImpCasts()->getType().getObjCLifetime() 
2237           == Qualifiers::OCL_Weak))
2238       Diag(Receiver->getLocStart(), diag::warn_receiver_is_weak);
2239     
2240     // In ARC, annotate delegate init calls.
2241     if (Result->getMethodFamily() == OMF_init &&
2242         (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2243       // Only consider init calls *directly* in init implementations,
2244       // not within blocks.
2245       ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2246       if (method && method->getMethodFamily() == OMF_init) {
2247         // The implicit assignment to self means we also don't want to
2248         // consume the result.
2249         Result->setDelegateInitCall(true);
2250         return Owned(Result);
2251       }
2252     }
2253
2254     // In ARC, check for message sends which are likely to introduce
2255     // retain cycles.
2256     checkRetainCycles(Result);
2257   }
2258       
2259   return MaybeBindToTemporary(Result);
2260 }
2261
2262 // ActOnInstanceMessage - used for both unary and keyword messages.
2263 // ArgExprs is optional - if it is present, the number of expressions
2264 // is obtained from Sel.getNumArgs().
2265 ExprResult Sema::ActOnInstanceMessage(Scope *S,
2266                                       Expr *Receiver, 
2267                                       Selector Sel,
2268                                       SourceLocation LBracLoc,
2269                                       ArrayRef<SourceLocation> SelectorLocs,
2270                                       SourceLocation RBracLoc,
2271                                       MultiExprArg Args) {
2272   if (!Receiver)
2273     return ExprError();
2274
2275   return BuildInstanceMessage(Receiver, Receiver->getType(),
2276                               /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0, 
2277                               LBracLoc, SelectorLocs, RBracLoc, move(Args));
2278 }
2279
2280 enum ARCConversionTypeClass {
2281   /// int, void, struct A
2282   ACTC_none,
2283
2284   /// id, void (^)()
2285   ACTC_retainable,
2286
2287   /// id*, id***, void (^*)(),
2288   ACTC_indirectRetainable,
2289
2290   /// void* might be a normal C type, or it might a CF type.
2291   ACTC_voidPtr,
2292
2293   /// struct A*
2294   ACTC_coreFoundation
2295 };
2296 static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2297   return (ACTC == ACTC_retainable ||
2298           ACTC == ACTC_coreFoundation ||
2299           ACTC == ACTC_voidPtr);
2300 }
2301 static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2302   return ACTC == ACTC_none ||
2303          ACTC == ACTC_voidPtr ||
2304          ACTC == ACTC_coreFoundation;
2305 }
2306
2307 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
2308   bool isIndirect = false;
2309   
2310   // Ignore an outermost reference type.
2311   if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
2312     type = ref->getPointeeType();
2313     isIndirect = true;
2314   }
2315   
2316   // Drill through pointers and arrays recursively.
2317   while (true) {
2318     if (const PointerType *ptr = type->getAs<PointerType>()) {
2319       type = ptr->getPointeeType();
2320
2321       // The first level of pointer may be the innermost pointer on a CF type.
2322       if (!isIndirect) {
2323         if (type->isVoidType()) return ACTC_voidPtr;
2324         if (type->isRecordType()) return ACTC_coreFoundation;
2325       }
2326     } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2327       type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2328     } else {
2329       break;
2330     }
2331     isIndirect = true;
2332   }
2333   
2334   if (isIndirect) {
2335     if (type->isObjCARCBridgableType())
2336       return ACTC_indirectRetainable;
2337     return ACTC_none;
2338   }
2339
2340   if (type->isObjCARCBridgableType())
2341     return ACTC_retainable;
2342
2343   return ACTC_none;
2344 }
2345
2346 namespace {
2347   /// A result from the cast checker.
2348   enum ACCResult {
2349     /// Cannot be casted.
2350     ACC_invalid,
2351
2352     /// Can be safely retained or not retained.
2353     ACC_bottom,
2354
2355     /// Can be casted at +0.
2356     ACC_plusZero,
2357
2358     /// Can be casted at +1.
2359     ACC_plusOne
2360   };
2361   ACCResult merge(ACCResult left, ACCResult right) {
2362     if (left == right) return left;
2363     if (left == ACC_bottom) return right;
2364     if (right == ACC_bottom) return left;
2365     return ACC_invalid;
2366   }
2367
2368   /// A checker which white-lists certain expressions whose conversion
2369   /// to or from retainable type would otherwise be forbidden in ARC.
2370   class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2371     typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2372
2373     ASTContext &Context;
2374     ARCConversionTypeClass SourceClass;
2375     ARCConversionTypeClass TargetClass;
2376
2377     static bool isCFType(QualType type) {
2378       // Someday this can use ns_bridged.  For now, it has to do this.
2379       return type->isCARCBridgableType();
2380     }
2381
2382   public:
2383     ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
2384                    ARCConversionTypeClass target)
2385       : Context(Context), SourceClass(source), TargetClass(target) {}
2386
2387     using super::Visit;
2388     ACCResult Visit(Expr *e) {
2389       return super::Visit(e->IgnoreParens());
2390     }
2391
2392     ACCResult VisitStmt(Stmt *s) {
2393       return ACC_invalid;
2394     }
2395
2396     /// Null pointer constants can be casted however you please.
2397     ACCResult VisitExpr(Expr *e) {
2398       if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2399         return ACC_bottom;
2400       return ACC_invalid;
2401     }
2402
2403     /// Objective-C string literals can be safely casted.
2404     ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2405       // If we're casting to any retainable type, go ahead.  Global
2406       // strings are immune to retains, so this is bottom.
2407       if (isAnyRetainable(TargetClass)) return ACC_bottom;
2408
2409       return ACC_invalid;
2410     }
2411     
2412     /// Look through certain implicit and explicit casts.
2413     ACCResult VisitCastExpr(CastExpr *e) {
2414       switch (e->getCastKind()) {
2415         case CK_NullToPointer:
2416           return ACC_bottom;
2417
2418         case CK_NoOp:
2419         case CK_LValueToRValue:
2420         case CK_BitCast:
2421         case CK_CPointerToObjCPointerCast:
2422         case CK_BlockPointerToObjCPointerCast:
2423         case CK_AnyPointerToBlockPointerCast:
2424           return Visit(e->getSubExpr());
2425
2426         default:
2427           return ACC_invalid;
2428       }
2429     }
2430
2431     /// Look through unary extension.
2432     ACCResult VisitUnaryExtension(UnaryOperator *e) {
2433       return Visit(e->getSubExpr());
2434     }
2435
2436     /// Ignore the LHS of a comma operator.
2437     ACCResult VisitBinComma(BinaryOperator *e) {
2438       return Visit(e->getRHS());
2439     }
2440
2441     /// Conditional operators are okay if both sides are okay.
2442     ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2443       ACCResult left = Visit(e->getTrueExpr());
2444       if (left == ACC_invalid) return ACC_invalid;
2445       return merge(left, Visit(e->getFalseExpr()));
2446     }
2447
2448     /// Look through pseudo-objects.
2449     ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2450       // If we're getting here, we should always have a result.
2451       return Visit(e->getResultExpr());
2452     }
2453
2454     /// Statement expressions are okay if their result expression is okay.
2455     ACCResult VisitStmtExpr(StmtExpr *e) {
2456       return Visit(e->getSubStmt()->body_back());
2457     }
2458
2459     /// Some declaration references are okay.
2460     ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2461       // References to global constants from system headers are okay.
2462       // These are things like 'kCFStringTransformToLatin'.  They are
2463       // can also be assumed to be immune to retains.
2464       VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2465       if (isAnyRetainable(TargetClass) &&
2466           isAnyRetainable(SourceClass) &&
2467           var &&
2468           var->getStorageClass() == SC_Extern &&
2469           var->getType().isConstQualified() &&
2470           Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2471         return ACC_bottom;
2472       }
2473
2474       // Nothing else.
2475       return ACC_invalid;
2476     }
2477
2478     /// Some calls are okay.
2479     ACCResult VisitCallExpr(CallExpr *e) {
2480       if (FunctionDecl *fn = e->getDirectCallee())
2481         if (ACCResult result = checkCallToFunction(fn))
2482           return result;
2483
2484       return super::VisitCallExpr(e);
2485     }
2486
2487     ACCResult checkCallToFunction(FunctionDecl *fn) {
2488       // Require a CF*Ref return type.
2489       if (!isCFType(fn->getResultType()))
2490         return ACC_invalid;
2491
2492       if (!isAnyRetainable(TargetClass))
2493         return ACC_invalid;
2494
2495       // Honor an explicit 'not retained' attribute.
2496       if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2497         return ACC_plusZero;
2498
2499       // Honor an explicit 'retained' attribute, except that for
2500       // now we're not going to permit implicit handling of +1 results,
2501       // because it's a bit frightening.
2502       if (fn->hasAttr<CFReturnsRetainedAttr>())
2503         return ACC_invalid; // ACC_plusOne if we start accepting this
2504
2505       // Recognize this specific builtin function, which is used by CFSTR.
2506       unsigned builtinID = fn->getBuiltinID();
2507       if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2508         return ACC_bottom;
2509
2510       // Otherwise, don't do anything implicit with an unaudited function.
2511       if (!fn->hasAttr<CFAuditedTransferAttr>())
2512         return ACC_invalid;
2513
2514       // Otherwise, it's +0 unless it follows the create convention.
2515       if (ento::coreFoundation::followsCreateRule(fn))
2516         return ACC_invalid; // ACC_plusOne if we start accepting this
2517
2518       return ACC_plusZero;
2519     }
2520
2521     ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
2522       return checkCallToMethod(e->getMethodDecl());
2523     }
2524
2525     ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
2526       ObjCMethodDecl *method;
2527       if (e->isExplicitProperty())
2528         method = e->getExplicitProperty()->getGetterMethodDecl();
2529       else
2530         method = e->getImplicitPropertyGetter();
2531       return checkCallToMethod(method);
2532     }
2533
2534     ACCResult checkCallToMethod(ObjCMethodDecl *method) {
2535       if (!method) return ACC_invalid;
2536
2537       // Check for message sends to functions returning CF types.  We
2538       // just obey the Cocoa conventions with these, even though the
2539       // return type is CF.
2540       if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
2541         return ACC_invalid;
2542       
2543       // If the method is explicitly marked not-retained, it's +0.
2544       if (method->hasAttr<CFReturnsNotRetainedAttr>())
2545         return ACC_plusZero;
2546
2547       // If the method is explicitly marked as returning retained, or its
2548       // selector follows a +1 Cocoa convention, treat it as +1.
2549       if (method->hasAttr<CFReturnsRetainedAttr>())
2550         return ACC_plusOne;
2551
2552       switch (method->getSelector().getMethodFamily()) {
2553       case OMF_alloc:
2554       case OMF_copy:
2555       case OMF_mutableCopy:
2556       case OMF_new:
2557         return ACC_plusOne;
2558
2559       default:
2560         // Otherwise, treat it as +0.
2561         return ACC_plusZero;
2562       }
2563     }
2564   };
2565 }
2566
2567 static bool
2568 KnownName(Sema &S, const char *name) {
2569   LookupResult R(S, &S.Context.Idents.get(name), SourceLocation(),
2570                  Sema::LookupOrdinaryName);
2571   return S.LookupName(R, S.TUScope, false);
2572 }
2573
2574 static void addFixitForObjCARCConversion(Sema &S,
2575                                          DiagnosticBuilder &DiagB,
2576                                          Sema::CheckedConversionKind CCK,
2577                                          SourceLocation afterLParen,
2578                                          QualType castType,
2579                                          Expr *castExpr,
2580                                          const char *bridgeKeyword,
2581                                          const char *CFBridgeName) {
2582   // We handle C-style and implicit casts here.
2583   switch (CCK) {
2584   case Sema::CCK_ImplicitConversion:
2585   case Sema::CCK_CStyleCast:
2586     break;
2587   case Sema::CCK_FunctionalCast:
2588   case Sema::CCK_OtherCast:
2589     return;
2590   }
2591
2592   if (CFBridgeName) {
2593     Expr *castedE = castExpr;
2594     if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
2595       castedE = CCE->getSubExpr();
2596     castedE = castedE->IgnoreImpCasts();
2597     SourceRange range = castedE->getSourceRange();
2598     if (isa<ParenExpr>(castedE)) {
2599       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2600                          CFBridgeName));
2601     } else {
2602       std::string namePlusParen = CFBridgeName;
2603       namePlusParen += "(";
2604       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2605                                                     namePlusParen));
2606       DiagB.AddFixItHint(FixItHint::CreateInsertion(
2607                                        S.PP.getLocForEndOfToken(range.getEnd()),
2608                                        ")"));
2609     }
2610     return;
2611   }
2612
2613   if (CCK == Sema::CCK_CStyleCast) {
2614     DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
2615   } else {
2616     std::string castCode = "(";
2617     castCode += bridgeKeyword;
2618     castCode += castType.getAsString();
2619     castCode += ")";
2620     Expr *castedE = castExpr->IgnoreImpCasts();
2621     SourceRange range = castedE->getSourceRange();
2622     if (isa<ParenExpr>(castedE)) {
2623       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2624                          castCode));
2625     } else {
2626       castCode += "(";
2627       DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2628                                                     castCode));
2629       DiagB.AddFixItHint(FixItHint::CreateInsertion(
2630                                        S.PP.getLocForEndOfToken(range.getEnd()),
2631                                        ")"));
2632     }
2633   }
2634 }
2635
2636 static void
2637 diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
2638                           QualType castType, ARCConversionTypeClass castACTC,
2639                           Expr *castExpr, ARCConversionTypeClass exprACTC,
2640                           Sema::CheckedConversionKind CCK) {
2641   SourceLocation loc =
2642     (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
2643   
2644   if (S.makeUnavailableInSystemHeader(loc,
2645                 "converts between Objective-C and C pointers in -fobjc-arc"))
2646     return;
2647
2648   QualType castExprType = castExpr->getType();
2649   
2650   unsigned srcKind = 0;
2651   switch (exprACTC) {
2652   case ACTC_none:
2653   case ACTC_coreFoundation:
2654   case ACTC_voidPtr:
2655     srcKind = (castExprType->isPointerType() ? 1 : 0);
2656     break;
2657   case ACTC_retainable:
2658     srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
2659     break;
2660   case ACTC_indirectRetainable:
2661     srcKind = 4;
2662     break;
2663   }
2664   
2665   // Check whether this could be fixed with a bridge cast.
2666   SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
2667   SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
2668
2669   // Bridge from an ARC type to a CF type.
2670   if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
2671
2672     S.Diag(loc, diag::err_arc_cast_requires_bridge)
2673       << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2674       << 2 // of C pointer type
2675       << castExprType
2676       << unsigned(castType->isBlockPointerType()) // to ObjC|block type
2677       << castType
2678       << castRange
2679       << castExpr->getSourceRange();
2680     bool br = KnownName(S, "CFBridgingRelease");
2681     {
2682       DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2683       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2684                                    castType, castExpr, "__bridge ", 0);
2685     }
2686     {
2687       DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_transfer)
2688         << castExprType << br;
2689       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2690                                    castType, castExpr, "__bridge_transfer ",
2691                                    br ? "CFBridgingRelease" : 0);
2692     }
2693
2694     return;
2695   }
2696     
2697   // Bridge from a CF type to an ARC type.
2698   if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
2699     bool br = KnownName(S, "CFBridgingRetain");
2700     S.Diag(loc, diag::err_arc_cast_requires_bridge)
2701       << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2702       << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
2703       << castExprType
2704       << 2 // to C pointer type
2705       << castType
2706       << castRange
2707       << castExpr->getSourceRange();
2708
2709     {
2710       DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2711       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2712                                    castType, castExpr, "__bridge ", 0);
2713     }
2714     {
2715       DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_retained)
2716         << castType << br;
2717       addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2718                                    castType, castExpr, "__bridge_retained ",
2719                                    br ? "CFBridgingRetain" : 0);
2720     }
2721
2722     return;
2723   }
2724   
2725   S.Diag(loc, diag::err_arc_mismatched_cast)
2726     << (CCK != Sema::CCK_ImplicitConversion)
2727     << srcKind << castExprType << castType
2728     << castRange << castExpr->getSourceRange();
2729 }
2730
2731 Sema::ARCConversionResult
2732 Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
2733                              Expr *&castExpr, CheckedConversionKind CCK) {
2734   QualType castExprType = castExpr->getType();
2735
2736   // For the purposes of the classification, we assume reference types
2737   // will bind to temporaries.
2738   QualType effCastType = castType;
2739   if (const ReferenceType *ref = castType->getAs<ReferenceType>())
2740     effCastType = ref->getPointeeType();
2741   
2742   ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
2743   ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
2744   if (exprACTC == castACTC) {
2745     // check for viablity and report error if casting an rvalue to a
2746     // life-time qualifier.
2747     if ((castACTC == ACTC_retainable) &&
2748         (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
2749         (castType != castExprType)) {
2750       const Type *DT = castType.getTypePtr();
2751       QualType QDT = castType;
2752       // We desugar some types but not others. We ignore those
2753       // that cannot happen in a cast; i.e. auto, and those which
2754       // should not be de-sugared; i.e typedef.
2755       if (const ParenType *PT = dyn_cast<ParenType>(DT))
2756         QDT = PT->desugar();
2757       else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
2758         QDT = TP->desugar();
2759       else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
2760         QDT = AT->desugar();
2761       if (QDT != castType &&
2762           QDT.getObjCLifetime() !=  Qualifiers::OCL_None) {
2763         SourceLocation loc =
2764           (castRange.isValid() ? castRange.getBegin() 
2765                               : castExpr->getExprLoc());
2766         Diag(loc, diag::err_arc_nolifetime_behavior);
2767       }
2768     }
2769     return ACR_okay;
2770   }
2771   
2772   if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
2773
2774   // Allow all of these types to be cast to integer types (but not
2775   // vice-versa).
2776   if (castACTC == ACTC_none && castType->isIntegralType(Context))
2777     return ACR_okay;
2778   
2779   // Allow casts between pointers to lifetime types (e.g., __strong id*)
2780   // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
2781   // must be explicit.
2782   if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
2783     return ACR_okay;
2784   if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
2785       CCK != CCK_ImplicitConversion)
2786     return ACR_okay;
2787
2788   switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
2789   // For invalid casts, fall through.
2790   case ACC_invalid:
2791     break;
2792
2793   // Do nothing for both bottom and +0.
2794   case ACC_bottom:
2795   case ACC_plusZero:
2796     return ACR_okay;
2797
2798   // If the result is +1, consume it here.
2799   case ACC_plusOne:
2800     castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
2801                                         CK_ARCConsumeObject, castExpr,
2802                                         0, VK_RValue);
2803     ExprNeedsCleanups = true;
2804     return ACR_okay;
2805   }
2806
2807   // If this is a non-implicit cast from id or block type to a
2808   // CoreFoundation type, delay complaining in case the cast is used
2809   // in an acceptable context.
2810   if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
2811       CCK != CCK_ImplicitConversion)
2812     return ACR_unbridged;
2813
2814   diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
2815                             castExpr, exprACTC, CCK);
2816   return ACR_okay;
2817 }
2818
2819 /// Given that we saw an expression with the ARCUnbridgedCastTy
2820 /// placeholder type, complain bitterly.
2821 void Sema::diagnoseARCUnbridgedCast(Expr *e) {
2822   // We expect the spurious ImplicitCastExpr to already have been stripped.
2823   assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
2824   CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
2825
2826   SourceRange castRange;
2827   QualType castType;
2828   CheckedConversionKind CCK;
2829
2830   if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
2831     castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
2832     castType = cast->getTypeAsWritten();
2833     CCK = CCK_CStyleCast;
2834   } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
2835     castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
2836     castType = cast->getTypeAsWritten();
2837     CCK = CCK_OtherCast;
2838   } else {
2839     castType = cast->getType();
2840     CCK = CCK_ImplicitConversion;
2841   }
2842
2843   ARCConversionTypeClass castACTC =
2844     classifyTypeForARCConversion(castType.getNonReferenceType());
2845
2846   Expr *castExpr = realCast->getSubExpr();
2847   assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
2848
2849   diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
2850                             castExpr, ACTC_retainable, CCK);
2851 }
2852
2853 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
2854 /// type, remove the placeholder cast.
2855 Expr *Sema::stripARCUnbridgedCast(Expr *e) {
2856   assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
2857
2858   if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
2859     Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
2860     return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
2861   } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
2862     assert(uo->getOpcode() == UO_Extension);
2863     Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
2864     return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
2865                                    sub->getValueKind(), sub->getObjectKind(),
2866                                        uo->getOperatorLoc());
2867   } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
2868     assert(!gse->isResultDependent());
2869
2870     unsigned n = gse->getNumAssocs();
2871     SmallVector<Expr*, 4> subExprs(n);
2872     SmallVector<TypeSourceInfo*, 4> subTypes(n);
2873     for (unsigned i = 0; i != n; ++i) {
2874       subTypes[i] = gse->getAssocTypeSourceInfo(i);
2875       Expr *sub = gse->getAssocExpr(i);
2876       if (i == gse->getResultIndex())
2877         sub = stripARCUnbridgedCast(sub);
2878       subExprs[i] = sub;
2879     }
2880
2881     return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
2882                                               gse->getControllingExpr(),
2883                                               subTypes.data(), subExprs.data(),
2884                                               n, gse->getDefaultLoc(),
2885                                               gse->getRParenLoc(),
2886                                        gse->containsUnexpandedParameterPack(),
2887                                               gse->getResultIndex());
2888   } else {
2889     assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
2890     return cast<ImplicitCastExpr>(e)->getSubExpr();
2891   }
2892 }
2893
2894 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
2895                                                  QualType exprType) {
2896   QualType canCastType = 
2897     Context.getCanonicalType(castType).getUnqualifiedType();
2898   QualType canExprType = 
2899     Context.getCanonicalType(exprType).getUnqualifiedType();
2900   if (isa<ObjCObjectPointerType>(canCastType) &&
2901       castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
2902       canExprType->isObjCObjectPointerType()) {
2903     if (const ObjCObjectPointerType *ObjT =
2904         canExprType->getAs<ObjCObjectPointerType>())
2905       if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
2906         return false;
2907   }
2908   return true;
2909 }
2910
2911 /// Look for an ObjCReclaimReturnedObject cast and destroy it.
2912 static Expr *maybeUndoReclaimObject(Expr *e) {
2913   // For now, we just undo operands that are *immediately* reclaim
2914   // expressions, which prevents the vast majority of potential
2915   // problems here.  To catch them all, we'd need to rebuild arbitrary
2916   // value-propagating subexpressions --- we can't reliably rebuild
2917   // in-place because of expression sharing.
2918   if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2919     if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
2920       return ice->getSubExpr();
2921
2922   return e;
2923 }
2924
2925 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
2926                                       ObjCBridgeCastKind Kind,
2927                                       SourceLocation BridgeKeywordLoc,
2928                                       TypeSourceInfo *TSInfo,
2929                                       Expr *SubExpr) {
2930   ExprResult SubResult = UsualUnaryConversions(SubExpr);
2931   if (SubResult.isInvalid()) return ExprError();
2932   SubExpr = SubResult.take();
2933
2934   QualType T = TSInfo->getType();
2935   QualType FromType = SubExpr->getType();
2936
2937   CastKind CK;
2938
2939   bool MustConsume = false;
2940   if (T->isDependentType() || SubExpr->isTypeDependent()) {
2941     // Okay: we'll build a dependent expression type.
2942     CK = CK_Dependent;
2943   } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
2944     // Casting CF -> id
2945     CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
2946                                   : CK_CPointerToObjCPointerCast);
2947     switch (Kind) {
2948     case OBC_Bridge:
2949       break;
2950       
2951     case OBC_BridgeRetained: {
2952       bool br = KnownName(*this, "CFBridgingRelease");
2953       Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2954         << 2
2955         << FromType
2956         << (T->isBlockPointerType()? 1 : 0)
2957         << T
2958         << SubExpr->getSourceRange()
2959         << Kind;
2960       Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2961         << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
2962       Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
2963         << FromType << br
2964         << FixItHint::CreateReplacement(BridgeKeywordLoc, 
2965                                         br ? "CFBridgingRelease " 
2966                                            : "__bridge_transfer ");
2967
2968       Kind = OBC_Bridge;
2969       break;
2970     }
2971       
2972     case OBC_BridgeTransfer:
2973       // We must consume the Objective-C object produced by the cast.
2974       MustConsume = true;
2975       break;
2976     }
2977   } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
2978     // Okay: id -> CF
2979     CK = CK_BitCast;
2980     switch (Kind) {
2981     case OBC_Bridge:
2982       // Reclaiming a value that's going to be __bridge-casted to CF
2983       // is very dangerous, so we don't do it.
2984       SubExpr = maybeUndoReclaimObject(SubExpr);
2985       break;
2986       
2987     case OBC_BridgeRetained:        
2988       // Produce the object before casting it.
2989       SubExpr = ImplicitCastExpr::Create(Context, FromType,
2990                                          CK_ARCProduceObject,
2991                                          SubExpr, 0, VK_RValue);
2992       break;
2993       
2994     case OBC_BridgeTransfer: {
2995       bool br = KnownName(*this, "CFBridgingRetain");
2996       Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2997         << (FromType->isBlockPointerType()? 1 : 0)
2998         << FromType
2999         << 2
3000         << T
3001         << SubExpr->getSourceRange()
3002         << Kind;
3003         
3004       Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3005         << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3006       Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
3007         << T << br
3008         << FixItHint::CreateReplacement(BridgeKeywordLoc, 
3009                           br ? "CFBridgingRetain " : "__bridge_retained");
3010         
3011       Kind = OBC_Bridge;
3012       break;
3013     }
3014     }
3015   } else {
3016     Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3017       << FromType << T << Kind
3018       << SubExpr->getSourceRange()
3019       << TSInfo->getTypeLoc().getSourceRange();
3020     return ExprError();
3021   }
3022
3023   Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
3024                                                    BridgeKeywordLoc,
3025                                                    TSInfo, SubExpr);
3026   
3027   if (MustConsume) {
3028     ExprNeedsCleanups = true;
3029     Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result, 
3030                                       0, VK_RValue);    
3031   }
3032   
3033   return Result;
3034 }
3035
3036 ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
3037                                       SourceLocation LParenLoc,
3038                                       ObjCBridgeCastKind Kind,
3039                                       SourceLocation BridgeKeywordLoc,
3040                                       ParsedType Type,
3041                                       SourceLocation RParenLoc,
3042                                       Expr *SubExpr) {
3043   TypeSourceInfo *TSInfo = 0;
3044   QualType T = GetTypeFromParser(Type, &TSInfo);
3045   if (!TSInfo)
3046     TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3047   return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo, 
3048                               SubExpr);
3049 }