SemaObjCProperty.cpp revision e859fbf5938fc0f8ca5aa115c35c66732174f513
1//===--- SemaObjCProperty.cpp - Semantic Analysis for ObjC @property ------===//
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 @property and
11//  @synthesize declarations.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Sema/SemaInternal.h"
16#include "clang/Sema/Initialization.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/ExprObjC.h"
19#include "clang/AST/ExprCXX.h"
20#include "llvm/ADT/DenseSet.h"
21
22using namespace clang;
23
24//===----------------------------------------------------------------------===//
25// Grammar actions.
26//===----------------------------------------------------------------------===//
27
28/// getImpliedARCOwnership - Given a set of property attributes and a
29/// type, infer an expected lifetime.  The type's ownership qualification
30/// is not considered.
31///
32/// Returns OCL_None if the attributes as stated do not imply an ownership.
33/// Never returns OCL_Autoreleasing.
34static Qualifiers::ObjCLifetime getImpliedARCOwnership(
35                               ObjCPropertyDecl::PropertyAttributeKind attrs,
36                                                QualType type) {
37  // retain, strong, copy, weak, and unsafe_unretained are only legal
38  // on properties of retainable pointer type.
39  if (attrs & (ObjCPropertyDecl::OBJC_PR_retain |
40               ObjCPropertyDecl::OBJC_PR_strong |
41               ObjCPropertyDecl::OBJC_PR_copy)) {
42    return type->getObjCARCImplicitLifetime();
43  } else if (attrs & ObjCPropertyDecl::OBJC_PR_weak) {
44    return Qualifiers::OCL_Weak;
45  } else if (attrs & ObjCPropertyDecl::OBJC_PR_unsafe_unretained) {
46    return Qualifiers::OCL_ExplicitNone;
47  }
48
49  // assign can appear on other types, so we have to check the
50  // property type.
51  if (attrs & ObjCPropertyDecl::OBJC_PR_assign &&
52      type->isObjCRetainableType()) {
53    return Qualifiers::OCL_ExplicitNone;
54  }
55
56  return Qualifiers::OCL_None;
57}
58
59/// Check the internal consistency of a property declaration.
60static void checkARCPropertyDecl(Sema &S, ObjCPropertyDecl *property) {
61  if (property->isInvalidDecl()) return;
62
63  ObjCPropertyDecl::PropertyAttributeKind propertyKind
64    = property->getPropertyAttributes();
65  Qualifiers::ObjCLifetime propertyLifetime
66    = property->getType().getObjCLifetime();
67
68  // Nothing to do if we don't have a lifetime.
69  if (propertyLifetime == Qualifiers::OCL_None) return;
70
71  Qualifiers::ObjCLifetime expectedLifetime
72    = getImpliedARCOwnership(propertyKind, property->getType());
73  if (!expectedLifetime) {
74    // We have a lifetime qualifier but no dominating property
75    // attribute.  That's okay, but restore reasonable invariants by
76    // setting the property attribute according to the lifetime
77    // qualifier.
78    ObjCPropertyDecl::PropertyAttributeKind attr;
79    if (propertyLifetime == Qualifiers::OCL_Strong) {
80      attr = ObjCPropertyDecl::OBJC_PR_strong;
81    } else if (propertyLifetime == Qualifiers::OCL_Weak) {
82      attr = ObjCPropertyDecl::OBJC_PR_weak;
83    } else {
84      assert(propertyLifetime == Qualifiers::OCL_ExplicitNone);
85      attr = ObjCPropertyDecl::OBJC_PR_unsafe_unretained;
86    }
87    property->setPropertyAttributes(attr);
88    return;
89  }
90
91  if (propertyLifetime == expectedLifetime) return;
92
93  property->setInvalidDecl();
94  S.Diag(property->getLocation(),
95         diag::err_arc_inconsistent_property_ownership)
96    << property->getDeclName()
97    << expectedLifetime
98    << propertyLifetime;
99}
100
101Decl *Sema::ActOnProperty(Scope *S, SourceLocation AtLoc,
102                          FieldDeclarator &FD,
103                          ObjCDeclSpec &ODS,
104                          Selector GetterSel,
105                          Selector SetterSel,
106                          bool *isOverridingProperty,
107                          tok::ObjCKeywordKind MethodImplKind,
108                          DeclContext *lexicalDC) {
109  unsigned Attributes = ODS.getPropertyAttributes();
110  TypeSourceInfo *TSI = GetTypeForDeclarator(FD.D, S);
111  QualType T = TSI->getType();
112  if ((getLangOptions().getGC() != LangOptions::NonGC &&
113       T.isObjCGCWeak()) ||
114      (getLangOptions().ObjCAutoRefCount &&
115       T.getObjCLifetime() == Qualifiers::OCL_Weak))
116    Attributes |= ObjCDeclSpec::DQ_PR_weak;
117
118  bool isReadWrite = ((Attributes & ObjCDeclSpec::DQ_PR_readwrite) ||
119                      // default is readwrite!
120                      !(Attributes & ObjCDeclSpec::DQ_PR_readonly));
121  // property is defaulted to 'assign' if it is readwrite and is
122  // not retain or copy
123  bool isAssign = ((Attributes & ObjCDeclSpec::DQ_PR_assign) ||
124                   (isReadWrite &&
125                    !(Attributes & ObjCDeclSpec::DQ_PR_retain) &&
126                    !(Attributes & ObjCDeclSpec::DQ_PR_strong) &&
127                    !(Attributes & ObjCDeclSpec::DQ_PR_copy) &&
128                    !(Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) &&
129                    !(Attributes & ObjCDeclSpec::DQ_PR_weak)));
130
131  // Proceed with constructing the ObjCPropertDecls.
132  ObjCContainerDecl *ClassDecl = cast<ObjCContainerDecl>(CurContext);
133
134  if (ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl))
135    if (CDecl->IsClassExtension()) {
136      Decl *Res = HandlePropertyInClassExtension(S, AtLoc,
137                                           FD, GetterSel, SetterSel,
138                                           isAssign, isReadWrite,
139                                           Attributes,
140                                           isOverridingProperty, TSI,
141                                           MethodImplKind);
142      if (Res) {
143        CheckObjCPropertyAttributes(Res, AtLoc, Attributes);
144        if (getLangOptions().ObjCAutoRefCount)
145          checkARCPropertyDecl(*this, cast<ObjCPropertyDecl>(Res));
146      }
147      return Res;
148    }
149
150  ObjCPropertyDecl *Res = CreatePropertyDecl(S, ClassDecl, AtLoc, FD,
151                                             GetterSel, SetterSel,
152                                             isAssign, isReadWrite,
153                                             Attributes, TSI, MethodImplKind);
154  if (lexicalDC)
155    Res->setLexicalDeclContext(lexicalDC);
156
157  // Validate the attributes on the @property.
158  CheckObjCPropertyAttributes(Res, AtLoc, Attributes);
159
160  if (getLangOptions().ObjCAutoRefCount)
161    checkARCPropertyDecl(*this, Res);
162
163  return Res;
164}
165
166static ObjCPropertyDecl::PropertyAttributeKind
167makePropertyAttributesAsWritten(unsigned Attributes) {
168  unsigned attributesAsWritten = 0;
169  if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
170    attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_readonly;
171  if (Attributes & ObjCDeclSpec::DQ_PR_readwrite)
172    attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_readwrite;
173  if (Attributes & ObjCDeclSpec::DQ_PR_getter)
174    attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_getter;
175  if (Attributes & ObjCDeclSpec::DQ_PR_setter)
176    attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_setter;
177  if (Attributes & ObjCDeclSpec::DQ_PR_assign)
178    attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_assign;
179  if (Attributes & ObjCDeclSpec::DQ_PR_retain)
180    attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_retain;
181  if (Attributes & ObjCDeclSpec::DQ_PR_strong)
182    attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_strong;
183  if (Attributes & ObjCDeclSpec::DQ_PR_weak)
184    attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_weak;
185  if (Attributes & ObjCDeclSpec::DQ_PR_copy)
186    attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_copy;
187  if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained)
188    attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_unsafe_unretained;
189  if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)
190    attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_nonatomic;
191  if (Attributes & ObjCDeclSpec::DQ_PR_atomic)
192    attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_atomic;
193
194  return (ObjCPropertyDecl::PropertyAttributeKind)attributesAsWritten;
195}
196
197Decl *
198Sema::HandlePropertyInClassExtension(Scope *S,
199                                     SourceLocation AtLoc, FieldDeclarator &FD,
200                                     Selector GetterSel, Selector SetterSel,
201                                     const bool isAssign,
202                                     const bool isReadWrite,
203                                     const unsigned Attributes,
204                                     bool *isOverridingProperty,
205                                     TypeSourceInfo *T,
206                                     tok::ObjCKeywordKind MethodImplKind) {
207  ObjCCategoryDecl *CDecl = cast<ObjCCategoryDecl>(CurContext);
208  // Diagnose if this property is already in continuation class.
209  DeclContext *DC = CurContext;
210  IdentifierInfo *PropertyId = FD.D.getIdentifier();
211  ObjCInterfaceDecl *CCPrimary = CDecl->getClassInterface();
212
213  if (CCPrimary)
214    // Check for duplicate declaration of this property in current and
215    // other class extensions.
216    for (const ObjCCategoryDecl *ClsExtDecl =
217         CCPrimary->getFirstClassExtension();
218         ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
219      if (ObjCPropertyDecl *prevDecl =
220          ObjCPropertyDecl::findPropertyDecl(ClsExtDecl, PropertyId)) {
221        Diag(AtLoc, diag::err_duplicate_property);
222        Diag(prevDecl->getLocation(), diag::note_property_declare);
223        return 0;
224      }
225    }
226
227  // Create a new ObjCPropertyDecl with the DeclContext being
228  // the class extension.
229  // FIXME. We should really be using CreatePropertyDecl for this.
230  ObjCPropertyDecl *PDecl =
231    ObjCPropertyDecl::Create(Context, DC, FD.D.getIdentifierLoc(),
232                             PropertyId, AtLoc, T);
233  PDecl->setPropertyAttributesAsWritten(
234                                   makePropertyAttributesAsWritten(Attributes));
235  if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
236    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly);
237  if (Attributes & ObjCDeclSpec::DQ_PR_readwrite)
238    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite);
239  // Set setter/getter selector name. Needed later.
240  PDecl->setGetterName(GetterSel);
241  PDecl->setSetterName(SetterSel);
242  ProcessDeclAttributes(S, PDecl, FD.D);
243  DC->addDecl(PDecl);
244
245  // We need to look in the @interface to see if the @property was
246  // already declared.
247  if (!CCPrimary) {
248    Diag(CDecl->getLocation(), diag::err_continuation_class);
249    *isOverridingProperty = true;
250    return 0;
251  }
252
253  // Find the property in continuation class's primary class only.
254  ObjCPropertyDecl *PIDecl =
255    CCPrimary->FindPropertyVisibleInPrimaryClass(PropertyId);
256
257  if (!PIDecl) {
258    // No matching property found in the primary class. Just fall thru
259    // and add property to continuation class's primary class.
260    ObjCPropertyDecl *PDecl =
261      CreatePropertyDecl(S, CCPrimary, AtLoc,
262                         FD, GetterSel, SetterSel, isAssign, isReadWrite,
263                         Attributes, T, MethodImplKind, DC);
264
265    // A case of continuation class adding a new property in the class. This
266    // is not what it was meant for. However, gcc supports it and so should we.
267    // Make sure setter/getters are declared here.
268    ProcessPropertyDecl(PDecl, CCPrimary, /* redeclaredProperty = */ 0,
269                        /* lexicalDC = */ CDecl);
270    return PDecl;
271  }
272  if (PIDecl->getType().getCanonicalType()
273      != PDecl->getType().getCanonicalType()) {
274    Diag(AtLoc,
275         diag::warn_type_mismatch_continuation_class) << PDecl->getType();
276    Diag(PIDecl->getLocation(), diag::note_property_declare);
277  }
278
279  // The property 'PIDecl's readonly attribute will be over-ridden
280  // with continuation class's readwrite property attribute!
281  unsigned PIkind = PIDecl->getPropertyAttributesAsWritten();
282  if (isReadWrite && (PIkind & ObjCPropertyDecl::OBJC_PR_readonly)) {
283    unsigned retainCopyNonatomic =
284    (ObjCPropertyDecl::OBJC_PR_retain |
285     ObjCPropertyDecl::OBJC_PR_strong |
286     ObjCPropertyDecl::OBJC_PR_copy |
287     ObjCPropertyDecl::OBJC_PR_nonatomic);
288    if ((Attributes & retainCopyNonatomic) !=
289        (PIkind & retainCopyNonatomic)) {
290      Diag(AtLoc, diag::warn_property_attr_mismatch);
291      Diag(PIDecl->getLocation(), diag::note_property_declare);
292    }
293    DeclContext *DC = cast<DeclContext>(CCPrimary);
294    if (!ObjCPropertyDecl::findPropertyDecl(DC,
295                                 PIDecl->getDeclName().getAsIdentifierInfo())) {
296      // Protocol is not in the primary class. Must build one for it.
297      ObjCDeclSpec ProtocolPropertyODS;
298      // FIXME. Assuming that ObjCDeclSpec::ObjCPropertyAttributeKind
299      // and ObjCPropertyDecl::PropertyAttributeKind have identical
300      // values.  Should consolidate both into one enum type.
301      ProtocolPropertyODS.
302      setPropertyAttributes((ObjCDeclSpec::ObjCPropertyAttributeKind)
303                            PIkind);
304      // Must re-establish the context from class extension to primary
305      // class context.
306      ContextRAII SavedContext(*this, CCPrimary);
307
308      Decl *ProtocolPtrTy =
309        ActOnProperty(S, AtLoc, FD, ProtocolPropertyODS,
310                      PIDecl->getGetterName(),
311                      PIDecl->getSetterName(),
312                      isOverridingProperty,
313                      MethodImplKind,
314                      /* lexicalDC = */ CDecl);
315      PIDecl = cast<ObjCPropertyDecl>(ProtocolPtrTy);
316    }
317    PIDecl->makeitReadWriteAttribute();
318    if (Attributes & ObjCDeclSpec::DQ_PR_retain)
319      PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
320    if (Attributes & ObjCDeclSpec::DQ_PR_strong)
321      PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong);
322    if (Attributes & ObjCDeclSpec::DQ_PR_copy)
323      PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
324    PIDecl->setSetterName(SetterSel);
325  } else {
326    // Tailor the diagnostics for the common case where a readwrite
327    // property is declared both in the @interface and the continuation.
328    // This is a common error where the user often intended the original
329    // declaration to be readonly.
330    unsigned diag =
331      (Attributes & ObjCDeclSpec::DQ_PR_readwrite) &&
332      (PIkind & ObjCPropertyDecl::OBJC_PR_readwrite)
333      ? diag::err_use_continuation_class_redeclaration_readwrite
334      : diag::err_use_continuation_class;
335    Diag(AtLoc, diag)
336      << CCPrimary->getDeclName();
337    Diag(PIDecl->getLocation(), diag::note_property_declare);
338  }
339  *isOverridingProperty = true;
340  // Make sure setter decl is synthesized, and added to primary class's list.
341  ProcessPropertyDecl(PIDecl, CCPrimary, PDecl, CDecl);
342  return 0;
343}
344
345ObjCPropertyDecl *Sema::CreatePropertyDecl(Scope *S,
346                                           ObjCContainerDecl *CDecl,
347                                           SourceLocation AtLoc,
348                                           FieldDeclarator &FD,
349                                           Selector GetterSel,
350                                           Selector SetterSel,
351                                           const bool isAssign,
352                                           const bool isReadWrite,
353                                           const unsigned Attributes,
354                                           TypeSourceInfo *TInfo,
355                                           tok::ObjCKeywordKind MethodImplKind,
356                                           DeclContext *lexicalDC){
357  IdentifierInfo *PropertyId = FD.D.getIdentifier();
358  QualType T = TInfo->getType();
359
360  // Issue a warning if property is 'assign' as default and its object, which is
361  // gc'able conforms to NSCopying protocol
362  if (getLangOptions().getGC() != LangOptions::NonGC &&
363      isAssign && !(Attributes & ObjCDeclSpec::DQ_PR_assign))
364    if (const ObjCObjectPointerType *ObjPtrTy =
365          T->getAs<ObjCObjectPointerType>()) {
366      ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
367      if (IDecl)
368        if (ObjCProtocolDecl* PNSCopying =
369            LookupProtocol(&Context.Idents.get("NSCopying"), AtLoc))
370          if (IDecl->ClassImplementsProtocol(PNSCopying, true))
371            Diag(AtLoc, diag::warn_implements_nscopying) << PropertyId;
372    }
373  if (T->isObjCObjectType())
374    Diag(FD.D.getIdentifierLoc(), diag::err_statically_allocated_object);
375
376  DeclContext *DC = cast<DeclContext>(CDecl);
377  ObjCPropertyDecl *PDecl = ObjCPropertyDecl::Create(Context, DC,
378                                                     FD.D.getIdentifierLoc(),
379                                                     PropertyId, AtLoc, TInfo);
380
381  if (ObjCPropertyDecl *prevDecl =
382        ObjCPropertyDecl::findPropertyDecl(DC, PropertyId)) {
383    Diag(PDecl->getLocation(), diag::err_duplicate_property);
384    Diag(prevDecl->getLocation(), diag::note_property_declare);
385    PDecl->setInvalidDecl();
386  }
387  else {
388    DC->addDecl(PDecl);
389    if (lexicalDC)
390      PDecl->setLexicalDeclContext(lexicalDC);
391  }
392
393  if (T->isArrayType() || T->isFunctionType()) {
394    Diag(AtLoc, diag::err_property_type) << T;
395    PDecl->setInvalidDecl();
396  }
397
398  ProcessDeclAttributes(S, PDecl, FD.D);
399
400  // Regardless of setter/getter attribute, we save the default getter/setter
401  // selector names in anticipation of declaration of setter/getter methods.
402  PDecl->setGetterName(GetterSel);
403  PDecl->setSetterName(SetterSel);
404  PDecl->setPropertyAttributesAsWritten(
405                                   makePropertyAttributesAsWritten(Attributes));
406
407  if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
408    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly);
409
410  if (Attributes & ObjCDeclSpec::DQ_PR_getter)
411    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_getter);
412
413  if (Attributes & ObjCDeclSpec::DQ_PR_setter)
414    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_setter);
415
416  if (isReadWrite)
417    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite);
418
419  if (Attributes & ObjCDeclSpec::DQ_PR_retain)
420    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
421
422  if (Attributes & ObjCDeclSpec::DQ_PR_strong)
423    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong);
424
425  if (Attributes & ObjCDeclSpec::DQ_PR_weak)
426    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_weak);
427
428  if (Attributes & ObjCDeclSpec::DQ_PR_copy)
429    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
430
431  if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained)
432    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_unsafe_unretained);
433
434  if (isAssign)
435    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign);
436
437  // In the semantic attributes, one of nonatomic or atomic is always set.
438  if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)
439    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nonatomic);
440  else
441    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_atomic);
442
443  // 'unsafe_unretained' is alias for 'assign'.
444  if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained)
445    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign);
446  if (isAssign)
447    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_unsafe_unretained);
448
449  if (MethodImplKind == tok::objc_required)
450    PDecl->setPropertyImplementation(ObjCPropertyDecl::Required);
451  else if (MethodImplKind == tok::objc_optional)
452    PDecl->setPropertyImplementation(ObjCPropertyDecl::Optional);
453
454  return PDecl;
455}
456
457static void checkARCPropertyImpl(Sema &S, SourceLocation propertyImplLoc,
458                                 ObjCPropertyDecl *property,
459                                 ObjCIvarDecl *ivar) {
460  if (property->isInvalidDecl() || ivar->isInvalidDecl()) return;
461
462  QualType ivarType = ivar->getType();
463  Qualifiers::ObjCLifetime ivarLifetime = ivarType.getObjCLifetime();
464
465  // The lifetime implied by the property's attributes.
466  Qualifiers::ObjCLifetime propertyLifetime =
467    getImpliedARCOwnership(property->getPropertyAttributes(),
468                           property->getType());
469
470  // We're fine if they match.
471  if (propertyLifetime == ivarLifetime) return;
472
473  // These aren't valid lifetimes for object ivars;  don't diagnose twice.
474  if (ivarLifetime == Qualifiers::OCL_None ||
475      ivarLifetime == Qualifiers::OCL_Autoreleasing)
476    return;
477
478  switch (propertyLifetime) {
479  case Qualifiers::OCL_Strong:
480    S.Diag(propertyImplLoc, diag::err_arc_strong_property_ownership)
481      << property->getDeclName()
482      << ivar->getDeclName()
483      << ivarLifetime;
484    break;
485
486  case Qualifiers::OCL_Weak:
487    S.Diag(propertyImplLoc, diag::error_weak_property)
488      << property->getDeclName()
489      << ivar->getDeclName();
490    break;
491
492  case Qualifiers::OCL_ExplicitNone:
493    S.Diag(propertyImplLoc, diag::err_arc_assign_property_ownership)
494      << property->getDeclName()
495      << ivar->getDeclName()
496      << ((property->getPropertyAttributesAsWritten()
497           & ObjCPropertyDecl::OBJC_PR_assign) != 0);
498    break;
499
500  case Qualifiers::OCL_Autoreleasing:
501    llvm_unreachable("properties cannot be autoreleasing");
502
503  case Qualifiers::OCL_None:
504    // Any other property should be ignored.
505    return;
506  }
507
508  S.Diag(property->getLocation(), diag::note_property_declare);
509}
510
511
512/// ActOnPropertyImplDecl - This routine performs semantic checks and
513/// builds the AST node for a property implementation declaration; declared
514/// as @synthesize or @dynamic.
515///
516Decl *Sema::ActOnPropertyImplDecl(Scope *S,
517                                  SourceLocation AtLoc,
518                                  SourceLocation PropertyLoc,
519                                  bool Synthesize,
520                                  IdentifierInfo *PropertyId,
521                                  IdentifierInfo *PropertyIvar,
522                                  SourceLocation PropertyIvarLoc) {
523  ObjCContainerDecl *ClassImpDecl =
524    dyn_cast<ObjCContainerDecl>(CurContext);
525  // Make sure we have a context for the property implementation declaration.
526  if (!ClassImpDecl) {
527    Diag(AtLoc, diag::error_missing_property_context);
528    return 0;
529  }
530  ObjCPropertyDecl *property = 0;
531  ObjCInterfaceDecl* IDecl = 0;
532  // Find the class or category class where this property must have
533  // a declaration.
534  ObjCImplementationDecl *IC = 0;
535  ObjCCategoryImplDecl* CatImplClass = 0;
536  if ((IC = dyn_cast<ObjCImplementationDecl>(ClassImpDecl))) {
537    IDecl = IC->getClassInterface();
538    // We always synthesize an interface for an implementation
539    // without an interface decl. So, IDecl is always non-zero.
540    assert(IDecl &&
541           "ActOnPropertyImplDecl - @implementation without @interface");
542
543    // Look for this property declaration in the @implementation's @interface
544    property = IDecl->FindPropertyDeclaration(PropertyId);
545    if (!property) {
546      Diag(PropertyLoc, diag::error_bad_property_decl) << IDecl->getDeclName();
547      return 0;
548    }
549    unsigned PIkind = property->getPropertyAttributesAsWritten();
550    if ((PIkind & (ObjCPropertyDecl::OBJC_PR_atomic |
551                   ObjCPropertyDecl::OBJC_PR_nonatomic) ) == 0) {
552      if (AtLoc.isValid())
553        Diag(AtLoc, diag::warn_implicit_atomic_property);
554      else
555        Diag(IC->getLocation(), diag::warn_auto_implicit_atomic_property);
556      Diag(property->getLocation(), diag::note_property_declare);
557    }
558
559    if (const ObjCCategoryDecl *CD =
560        dyn_cast<ObjCCategoryDecl>(property->getDeclContext())) {
561      if (!CD->IsClassExtension()) {
562        Diag(PropertyLoc, diag::error_category_property) << CD->getDeclName();
563        Diag(property->getLocation(), diag::note_property_declare);
564        return 0;
565      }
566    }
567  } else if ((CatImplClass = dyn_cast<ObjCCategoryImplDecl>(ClassImpDecl))) {
568    if (Synthesize) {
569      Diag(AtLoc, diag::error_synthesize_category_decl);
570      return 0;
571    }
572    IDecl = CatImplClass->getClassInterface();
573    if (!IDecl) {
574      Diag(AtLoc, diag::error_missing_property_interface);
575      return 0;
576    }
577    ObjCCategoryDecl *Category =
578    IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier());
579
580    // If category for this implementation not found, it is an error which
581    // has already been reported eralier.
582    if (!Category)
583      return 0;
584    // Look for this property declaration in @implementation's category
585    property = Category->FindPropertyDeclaration(PropertyId);
586    if (!property) {
587      Diag(PropertyLoc, diag::error_bad_category_property_decl)
588      << Category->getDeclName();
589      return 0;
590    }
591  } else {
592    Diag(AtLoc, diag::error_bad_property_context);
593    return 0;
594  }
595  ObjCIvarDecl *Ivar = 0;
596  // Check that we have a valid, previously declared ivar for @synthesize
597  if (Synthesize) {
598    // @synthesize
599    if (!PropertyIvar)
600      PropertyIvar = PropertyId;
601    ObjCPropertyDecl::PropertyAttributeKind kind
602      = property->getPropertyAttributes();
603    QualType PropType = property->getType();
604
605    QualType PropertyIvarType = PropType.getNonReferenceType();
606
607    // Add GC __weak to the ivar type if the property is weak.
608    if ((kind & ObjCPropertyDecl::OBJC_PR_weak) &&
609        getLangOptions().getGC() != LangOptions::NonGC) {
610      assert(!getLangOptions().ObjCAutoRefCount);
611      if (PropertyIvarType.isObjCGCStrong()) {
612        Diag(PropertyLoc, diag::err_gc_weak_property_strong_type);
613        Diag(property->getLocation(), diag::note_property_declare);
614      } else {
615        PropertyIvarType =
616          Context.getObjCGCQualType(PropertyIvarType, Qualifiers::Weak);
617      }
618    }
619
620    // Check that this is a previously declared 'ivar' in 'IDecl' interface
621    ObjCInterfaceDecl *ClassDeclared;
622    Ivar = IDecl->lookupInstanceVariable(PropertyIvar, ClassDeclared);
623    if (!Ivar) {
624      // In ARC, give the ivar a lifetime qualifier based on the
625      // property attributes.
626      if (getLangOptions().ObjCAutoRefCount &&
627          !PropertyIvarType.getObjCLifetime() &&
628          PropertyIvarType->isObjCRetainableType()) {
629
630        // It's an error if we have to do this and the user didn't
631        // explicitly write an ownership attribute on the property.
632        if (!property->hasWrittenStorageAttribute() &&
633            !(kind & ObjCPropertyDecl::OBJC_PR_strong)) {
634          Diag(PropertyLoc,
635               diag::err_arc_objc_property_default_assign_on_object);
636          Diag(property->getLocation(), diag::note_property_declare);
637        } else {
638          Qualifiers::ObjCLifetime lifetime =
639            getImpliedARCOwnership(kind, PropertyIvarType);
640          assert(lifetime && "no lifetime for property?");
641
642          if (lifetime == Qualifiers::OCL_Weak &&
643              !getLangOptions().ObjCRuntimeHasWeak) {
644            Diag(PropertyLoc, diag::err_arc_weak_no_runtime);
645            Diag(property->getLocation(), diag::note_property_declare);
646          }
647
648          Qualifiers qs;
649          qs.addObjCLifetime(lifetime);
650          PropertyIvarType = Context.getQualifiedType(PropertyIvarType, qs);
651        }
652      }
653
654      if (kind & ObjCPropertyDecl::OBJC_PR_weak &&
655          !getLangOptions().ObjCAutoRefCount &&
656          getLangOptions().getGC() == LangOptions::NonGC) {
657        Diag(PropertyLoc, diag::error_synthesize_weak_non_arc_or_gc);
658        Diag(property->getLocation(), diag::note_property_declare);
659      }
660
661      Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
662                                  PropertyLoc, PropertyLoc, PropertyIvar,
663                                  PropertyIvarType, /*Dinfo=*/0,
664                                  ObjCIvarDecl::Private,
665                                  (Expr *)0, true);
666      ClassImpDecl->addDecl(Ivar);
667      IDecl->makeDeclVisibleInContext(Ivar, false);
668      property->setPropertyIvarDecl(Ivar);
669
670      if (!getLangOptions().ObjCNonFragileABI)
671        Diag(PropertyLoc, diag::error_missing_property_ivar_decl) << PropertyId;
672      // Note! I deliberately want it to fall thru so, we have a
673      // a property implementation and to avoid future warnings.
674    } else if (getLangOptions().ObjCNonFragileABI &&
675               ClassDeclared != IDecl) {
676      Diag(PropertyLoc, diag::error_ivar_in_superclass_use)
677      << property->getDeclName() << Ivar->getDeclName()
678      << ClassDeclared->getDeclName();
679      Diag(Ivar->getLocation(), diag::note_previous_access_declaration)
680      << Ivar << Ivar->getName();
681      // Note! I deliberately want it to fall thru so more errors are caught.
682    }
683    QualType IvarType = Context.getCanonicalType(Ivar->getType());
684
685    // Check that type of property and its ivar are type compatible.
686    if (Context.getCanonicalType(PropertyIvarType) != IvarType) {
687      bool compat = false;
688      if (isa<ObjCObjectPointerType>(PropertyIvarType)
689          && isa<ObjCObjectPointerType>(IvarType))
690        compat =
691          Context.canAssignObjCInterfaces(
692                                  PropertyIvarType->getAs<ObjCObjectPointerType>(),
693                                  IvarType->getAs<ObjCObjectPointerType>());
694      else {
695        SourceLocation Loc = PropertyIvarLoc;
696        if (Loc.isInvalid())
697          Loc = PropertyLoc;
698        compat = (CheckAssignmentConstraints(Loc, PropertyIvarType, IvarType)
699                    == Compatible);
700      }
701      if (!compat) {
702        Diag(PropertyLoc, diag::error_property_ivar_type)
703          << property->getDeclName() << PropType
704          << Ivar->getDeclName() << IvarType;
705        Diag(Ivar->getLocation(), diag::note_ivar_decl);
706        // Note! I deliberately want it to fall thru so, we have a
707        // a property implementation and to avoid future warnings.
708      }
709
710      // FIXME! Rules for properties are somewhat different that those
711      // for assignments. Use a new routine to consolidate all cases;
712      // specifically for property redeclarations as well as for ivars.
713      QualType lhsType =Context.getCanonicalType(PropertyIvarType).getUnqualifiedType();
714      QualType rhsType =Context.getCanonicalType(IvarType).getUnqualifiedType();
715      if (lhsType != rhsType &&
716          lhsType->isArithmeticType()) {
717        Diag(PropertyLoc, diag::error_property_ivar_type)
718          << property->getDeclName() << PropType
719          << Ivar->getDeclName() << IvarType;
720        Diag(Ivar->getLocation(), diag::note_ivar_decl);
721        // Fall thru - see previous comment
722      }
723      // __weak is explicit. So it works on Canonical type.
724      if ((PropType.isObjCGCWeak() && !IvarType.isObjCGCWeak() &&
725           getLangOptions().getGC() != LangOptions::NonGC)) {
726        Diag(PropertyLoc, diag::error_weak_property)
727        << property->getDeclName() << Ivar->getDeclName();
728        Diag(Ivar->getLocation(), diag::note_ivar_decl);
729        // Fall thru - see previous comment
730      }
731      // Fall thru - see previous comment
732      if ((property->getType()->isObjCObjectPointerType() ||
733           PropType.isObjCGCStrong()) && IvarType.isObjCGCWeak() &&
734          getLangOptions().getGC() != LangOptions::NonGC) {
735        Diag(PropertyLoc, diag::error_strong_property)
736        << property->getDeclName() << Ivar->getDeclName();
737        // Fall thru - see previous comment
738      }
739    }
740    if (getLangOptions().ObjCAutoRefCount)
741      checkARCPropertyImpl(*this, PropertyLoc, property, Ivar);
742  } else if (PropertyIvar)
743    // @dynamic
744    Diag(PropertyLoc, diag::error_dynamic_property_ivar_decl);
745
746  assert (property && "ActOnPropertyImplDecl - property declaration missing");
747  ObjCPropertyImplDecl *PIDecl =
748  ObjCPropertyImplDecl::Create(Context, CurContext, AtLoc, PropertyLoc,
749                               property,
750                               (Synthesize ?
751                                ObjCPropertyImplDecl::Synthesize
752                                : ObjCPropertyImplDecl::Dynamic),
753                               Ivar, PropertyIvarLoc);
754  if (ObjCMethodDecl *getterMethod = property->getGetterMethodDecl()) {
755    getterMethod->createImplicitParams(Context, IDecl);
756    if (getLangOptions().CPlusPlus && Synthesize &&
757        Ivar->getType()->isRecordType()) {
758      // For Objective-C++, need to synthesize the AST for the IVAR object to be
759      // returned by the getter as it must conform to C++'s copy-return rules.
760      // FIXME. Eventually we want to do this for Objective-C as well.
761      ImplicitParamDecl *SelfDecl = getterMethod->getSelfDecl();
762      DeclRefExpr *SelfExpr =
763        new (Context) DeclRefExpr(SelfDecl, SelfDecl->getType(),
764                                  VK_RValue, SourceLocation());
765      Expr *IvarRefExpr =
766        new (Context) ObjCIvarRefExpr(Ivar, Ivar->getType(), AtLoc,
767                                      SelfExpr, true, true);
768      ExprResult Res =
769        PerformCopyInitialization(InitializedEntity::InitializeResult(
770                                    SourceLocation(),
771                                    getterMethod->getResultType(),
772                                    /*NRVO=*/false),
773                                  SourceLocation(),
774                                  Owned(IvarRefExpr));
775      if (!Res.isInvalid()) {
776        Expr *ResExpr = Res.takeAs<Expr>();
777        if (ResExpr)
778          ResExpr = MaybeCreateExprWithCleanups(ResExpr);
779        PIDecl->setGetterCXXConstructor(ResExpr);
780      }
781    }
782    if (property->hasAttr<NSReturnsNotRetainedAttr>() &&
783        !getterMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
784      Diag(getterMethod->getLocation(),
785           diag::warn_property_getter_owning_mismatch);
786      Diag(property->getLocation(), diag::note_property_declare);
787    }
788  }
789  if (ObjCMethodDecl *setterMethod = property->getSetterMethodDecl()) {
790    setterMethod->createImplicitParams(Context, IDecl);
791    if (getLangOptions().CPlusPlus && Synthesize
792        && Ivar->getType()->isRecordType()) {
793      // FIXME. Eventually we want to do this for Objective-C as well.
794      ImplicitParamDecl *SelfDecl = setterMethod->getSelfDecl();
795      DeclRefExpr *SelfExpr =
796        new (Context) DeclRefExpr(SelfDecl, SelfDecl->getType(),
797                                  VK_RValue, SourceLocation());
798      Expr *lhs =
799        new (Context) ObjCIvarRefExpr(Ivar, Ivar->getType(), AtLoc,
800                                      SelfExpr, true, true);
801      ObjCMethodDecl::param_iterator P = setterMethod->param_begin();
802      ParmVarDecl *Param = (*P);
803      QualType T = Param->getType().getNonReferenceType();
804      Expr *rhs = new (Context) DeclRefExpr(Param, T,
805                                            VK_LValue, SourceLocation());
806      ExprResult Res = BuildBinOp(S, lhs->getLocEnd(),
807                                  BO_Assign, lhs, rhs);
808      if (property->getPropertyAttributes() &
809          ObjCPropertyDecl::OBJC_PR_atomic) {
810        Expr *callExpr = Res.takeAs<Expr>();
811        if (const CXXOperatorCallExpr *CXXCE =
812              dyn_cast_or_null<CXXOperatorCallExpr>(callExpr))
813          if (const FunctionDecl *FuncDecl = CXXCE->getDirectCallee())
814            if (!FuncDecl->isTrivial())
815              Diag(PropertyLoc,
816                   diag::warn_atomic_property_nontrivial_assign_op)
817                    << property->getType();
818      }
819      PIDecl->setSetterCXXAssignment(Res.takeAs<Expr>());
820    }
821  }
822
823  if (IC) {
824    if (Synthesize)
825      if (ObjCPropertyImplDecl *PPIDecl =
826          IC->FindPropertyImplIvarDecl(PropertyIvar)) {
827        Diag(PropertyLoc, diag::error_duplicate_ivar_use)
828        << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
829        << PropertyIvar;
830        Diag(PPIDecl->getLocation(), diag::note_previous_use);
831      }
832
833    if (ObjCPropertyImplDecl *PPIDecl
834        = IC->FindPropertyImplDecl(PropertyId)) {
835      Diag(PropertyLoc, diag::error_property_implemented) << PropertyId;
836      Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
837      return 0;
838    }
839    IC->addPropertyImplementation(PIDecl);
840    if (getLangOptions().ObjCDefaultSynthProperties &&
841        getLangOptions().ObjCNonFragileABI2) {
842      // Diagnose if an ivar was lazily synthesdized due to a previous
843      // use and if 1) property is @dynamic or 2) property is synthesized
844      // but it requires an ivar of different name.
845      ObjCInterfaceDecl *ClassDeclared=0;
846      ObjCIvarDecl *Ivar = 0;
847      if (!Synthesize)
848        Ivar = IDecl->lookupInstanceVariable(PropertyId, ClassDeclared);
849      else {
850        if (PropertyIvar && PropertyIvar != PropertyId)
851          Ivar = IDecl->lookupInstanceVariable(PropertyId, ClassDeclared);
852      }
853      // Issue diagnostics only if Ivar belongs to current class.
854      if (Ivar && Ivar->getSynthesize() &&
855          IC->getClassInterface() == ClassDeclared) {
856        Diag(Ivar->getLocation(), diag::err_undeclared_var_use)
857        << PropertyId;
858        Ivar->setInvalidDecl();
859      }
860    }
861  } else {
862    if (Synthesize)
863      if (ObjCPropertyImplDecl *PPIDecl =
864          CatImplClass->FindPropertyImplIvarDecl(PropertyIvar)) {
865        Diag(PropertyLoc, diag::error_duplicate_ivar_use)
866        << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
867        << PropertyIvar;
868        Diag(PPIDecl->getLocation(), diag::note_previous_use);
869      }
870
871    if (ObjCPropertyImplDecl *PPIDecl =
872        CatImplClass->FindPropertyImplDecl(PropertyId)) {
873      Diag(PropertyLoc, diag::error_property_implemented) << PropertyId;
874      Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
875      return 0;
876    }
877    CatImplClass->addPropertyImplementation(PIDecl);
878  }
879
880  return PIDecl;
881}
882
883//===----------------------------------------------------------------------===//
884// Helper methods.
885//===----------------------------------------------------------------------===//
886
887/// DiagnosePropertyMismatch - Compares two properties for their
888/// attributes and types and warns on a variety of inconsistencies.
889///
890void
891Sema::DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
892                               ObjCPropertyDecl *SuperProperty,
893                               const IdentifierInfo *inheritedName) {
894  ObjCPropertyDecl::PropertyAttributeKind CAttr =
895  Property->getPropertyAttributes();
896  ObjCPropertyDecl::PropertyAttributeKind SAttr =
897  SuperProperty->getPropertyAttributes();
898  if ((CAttr & ObjCPropertyDecl::OBJC_PR_readonly)
899      && (SAttr & ObjCPropertyDecl::OBJC_PR_readwrite))
900    Diag(Property->getLocation(), diag::warn_readonly_property)
901      << Property->getDeclName() << inheritedName;
902  if ((CAttr & ObjCPropertyDecl::OBJC_PR_copy)
903      != (SAttr & ObjCPropertyDecl::OBJC_PR_copy))
904    Diag(Property->getLocation(), diag::warn_property_attribute)
905      << Property->getDeclName() << "copy" << inheritedName;
906  else if (!(SAttr & ObjCPropertyDecl::OBJC_PR_readonly)){
907    unsigned CAttrRetain =
908      (CAttr &
909       (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_strong));
910    unsigned SAttrRetain =
911      (SAttr &
912       (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_strong));
913    bool CStrong = (CAttrRetain != 0);
914    bool SStrong = (SAttrRetain != 0);
915    if (CStrong != SStrong)
916      Diag(Property->getLocation(), diag::warn_property_attribute)
917        << Property->getDeclName() << "retain (or strong)" << inheritedName;
918  }
919
920  if ((CAttr & ObjCPropertyDecl::OBJC_PR_nonatomic)
921      != (SAttr & ObjCPropertyDecl::OBJC_PR_nonatomic))
922    Diag(Property->getLocation(), diag::warn_property_attribute)
923      << Property->getDeclName() << "atomic" << inheritedName;
924  if (Property->getSetterName() != SuperProperty->getSetterName())
925    Diag(Property->getLocation(), diag::warn_property_attribute)
926      << Property->getDeclName() << "setter" << inheritedName;
927  if (Property->getGetterName() != SuperProperty->getGetterName())
928    Diag(Property->getLocation(), diag::warn_property_attribute)
929      << Property->getDeclName() << "getter" << inheritedName;
930
931  QualType LHSType =
932    Context.getCanonicalType(SuperProperty->getType());
933  QualType RHSType =
934    Context.getCanonicalType(Property->getType());
935
936  if (!Context.propertyTypesAreCompatible(LHSType, RHSType)) {
937    // Do cases not handled in above.
938    // FIXME. For future support of covariant property types, revisit this.
939    bool IncompatibleObjC = false;
940    QualType ConvertedType;
941    if (!isObjCPointerConversion(RHSType, LHSType,
942                                 ConvertedType, IncompatibleObjC) ||
943        IncompatibleObjC) {
944        Diag(Property->getLocation(), diag::warn_property_types_are_incompatible)
945        << Property->getType() << SuperProperty->getType() << inheritedName;
946      Diag(SuperProperty->getLocation(), diag::note_property_declare);
947    }
948  }
949}
950
951bool Sema::DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *property,
952                                            ObjCMethodDecl *GetterMethod,
953                                            SourceLocation Loc) {
954  if (GetterMethod &&
955      !Context.hasSameType(GetterMethod->getResultType().getNonReferenceType(),
956                           property->getType().getNonReferenceType())) {
957    AssignConvertType result = Incompatible;
958    if (property->getType()->isObjCObjectPointerType())
959      result = CheckAssignmentConstraints(Loc, GetterMethod->getResultType(),
960                                          property->getType());
961    if (result != Compatible) {
962      Diag(Loc, diag::warn_accessor_property_type_mismatch)
963      << property->getDeclName()
964      << GetterMethod->getSelector();
965      Diag(GetterMethod->getLocation(), diag::note_declared_at);
966      return true;
967    }
968  }
969  return false;
970}
971
972/// ComparePropertiesInBaseAndSuper - This routine compares property
973/// declarations in base and its super class, if any, and issues
974/// diagnostics in a variety of inconsistent situations.
975///
976void Sema::ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl) {
977  ObjCInterfaceDecl *SDecl = IDecl->getSuperClass();
978  if (!SDecl)
979    return;
980  // FIXME: O(N^2)
981  for (ObjCInterfaceDecl::prop_iterator S = SDecl->prop_begin(),
982       E = SDecl->prop_end(); S != E; ++S) {
983    ObjCPropertyDecl *SuperPDecl = (*S);
984    // Does property in super class has declaration in current class?
985    for (ObjCInterfaceDecl::prop_iterator I = IDecl->prop_begin(),
986         E = IDecl->prop_end(); I != E; ++I) {
987      ObjCPropertyDecl *PDecl = (*I);
988      if (SuperPDecl->getIdentifier() == PDecl->getIdentifier())
989          DiagnosePropertyMismatch(PDecl, SuperPDecl,
990                                   SDecl->getIdentifier());
991    }
992  }
993}
994
995/// MatchOneProtocolPropertiesInClass - This routine goes thru the list
996/// of properties declared in a protocol and compares their attribute against
997/// the same property declared in the class or category.
998void
999Sema::MatchOneProtocolPropertiesInClass(Decl *CDecl,
1000                                          ObjCProtocolDecl *PDecl) {
1001  ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDecl);
1002  if (!IDecl) {
1003    // Category
1004    ObjCCategoryDecl *CatDecl = static_cast<ObjCCategoryDecl*>(CDecl);
1005    assert (CatDecl && "MatchOneProtocolPropertiesInClass");
1006    if (!CatDecl->IsClassExtension())
1007      for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
1008           E = PDecl->prop_end(); P != E; ++P) {
1009        ObjCPropertyDecl *Pr = (*P);
1010        ObjCCategoryDecl::prop_iterator CP, CE;
1011        // Is this property already in  category's list of properties?
1012        for (CP = CatDecl->prop_begin(), CE = CatDecl->prop_end(); CP!=CE; ++CP)
1013          if ((*CP)->getIdentifier() == Pr->getIdentifier())
1014            break;
1015        if (CP != CE)
1016          // Property protocol already exist in class. Diagnose any mismatch.
1017          DiagnosePropertyMismatch((*CP), Pr, PDecl->getIdentifier());
1018      }
1019    return;
1020  }
1021  for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
1022       E = PDecl->prop_end(); P != E; ++P) {
1023    ObjCPropertyDecl *Pr = (*P);
1024    ObjCInterfaceDecl::prop_iterator CP, CE;
1025    // Is this property already in  class's list of properties?
1026    for (CP = IDecl->prop_begin(), CE = IDecl->prop_end(); CP != CE; ++CP)
1027      if ((*CP)->getIdentifier() == Pr->getIdentifier())
1028        break;
1029    if (CP != CE)
1030      // Property protocol already exist in class. Diagnose any mismatch.
1031      DiagnosePropertyMismatch((*CP), Pr, PDecl->getIdentifier());
1032    }
1033}
1034
1035/// CompareProperties - This routine compares properties
1036/// declared in 'ClassOrProtocol' objects (which can be a class or an
1037/// inherited protocol with the list of properties for class/category 'CDecl'
1038///
1039void Sema::CompareProperties(Decl *CDecl, Decl *ClassOrProtocol) {
1040  Decl *ClassDecl = ClassOrProtocol;
1041  ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDecl);
1042
1043  if (!IDecl) {
1044    // Category
1045    ObjCCategoryDecl *CatDecl = static_cast<ObjCCategoryDecl*>(CDecl);
1046    assert (CatDecl && "CompareProperties");
1047    if (ObjCCategoryDecl *MDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
1048      for (ObjCCategoryDecl::protocol_iterator P = MDecl->protocol_begin(),
1049           E = MDecl->protocol_end(); P != E; ++P)
1050      // Match properties of category with those of protocol (*P)
1051      MatchOneProtocolPropertiesInClass(CatDecl, *P);
1052
1053      // Go thru the list of protocols for this category and recursively match
1054      // their properties with those in the category.
1055      for (ObjCCategoryDecl::protocol_iterator P = CatDecl->protocol_begin(),
1056           E = CatDecl->protocol_end(); P != E; ++P)
1057        CompareProperties(CatDecl, *P);
1058    } else {
1059      ObjCProtocolDecl *MD = cast<ObjCProtocolDecl>(ClassDecl);
1060      for (ObjCProtocolDecl::protocol_iterator P = MD->protocol_begin(),
1061           E = MD->protocol_end(); P != E; ++P)
1062        MatchOneProtocolPropertiesInClass(CatDecl, *P);
1063    }
1064    return;
1065  }
1066
1067  if (ObjCInterfaceDecl *MDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
1068    for (ObjCInterfaceDecl::all_protocol_iterator
1069          P = MDecl->all_referenced_protocol_begin(),
1070          E = MDecl->all_referenced_protocol_end(); P != E; ++P)
1071      // Match properties of class IDecl with those of protocol (*P).
1072      MatchOneProtocolPropertiesInClass(IDecl, *P);
1073
1074    // Go thru the list of protocols for this class and recursively match
1075    // their properties with those declared in the class.
1076    for (ObjCInterfaceDecl::all_protocol_iterator
1077          P = IDecl->all_referenced_protocol_begin(),
1078          E = IDecl->all_referenced_protocol_end(); P != E; ++P)
1079      CompareProperties(IDecl, *P);
1080  } else {
1081    ObjCProtocolDecl *MD = cast<ObjCProtocolDecl>(ClassDecl);
1082    for (ObjCProtocolDecl::protocol_iterator P = MD->protocol_begin(),
1083         E = MD->protocol_end(); P != E; ++P)
1084      MatchOneProtocolPropertiesInClass(IDecl, *P);
1085  }
1086}
1087
1088/// isPropertyReadonly - Return true if property is readonly, by searching
1089/// for the property in the class and in its categories and implementations
1090///
1091bool Sema::isPropertyReadonly(ObjCPropertyDecl *PDecl,
1092                              ObjCInterfaceDecl *IDecl) {
1093  // by far the most common case.
1094  if (!PDecl->isReadOnly())
1095    return false;
1096  // Even if property is ready only, if interface has a user defined setter,
1097  // it is not considered read only.
1098  if (IDecl->getInstanceMethod(PDecl->getSetterName()))
1099    return false;
1100
1101  // Main class has the property as 'readonly'. Must search
1102  // through the category list to see if the property's
1103  // attribute has been over-ridden to 'readwrite'.
1104  for (ObjCCategoryDecl *Category = IDecl->getCategoryList();
1105       Category; Category = Category->getNextClassCategory()) {
1106    // Even if property is ready only, if a category has a user defined setter,
1107    // it is not considered read only.
1108    if (Category->getInstanceMethod(PDecl->getSetterName()))
1109      return false;
1110    ObjCPropertyDecl *P =
1111      Category->FindPropertyDeclaration(PDecl->getIdentifier());
1112    if (P && !P->isReadOnly())
1113      return false;
1114  }
1115
1116  // Also, check for definition of a setter method in the implementation if
1117  // all else failed.
1118  if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(CurContext)) {
1119    if (ObjCImplementationDecl *IMD =
1120        dyn_cast<ObjCImplementationDecl>(OMD->getDeclContext())) {
1121      if (IMD->getInstanceMethod(PDecl->getSetterName()))
1122        return false;
1123    } else if (ObjCCategoryImplDecl *CIMD =
1124               dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1125      if (CIMD->getInstanceMethod(PDecl->getSetterName()))
1126        return false;
1127    }
1128  }
1129  // Lastly, look through the implementation (if one is in scope).
1130  if (ObjCImplementationDecl *ImpDecl = IDecl->getImplementation())
1131    if (ImpDecl->getInstanceMethod(PDecl->getSetterName()))
1132      return false;
1133  // If all fails, look at the super class.
1134  if (ObjCInterfaceDecl *SIDecl = IDecl->getSuperClass())
1135    return isPropertyReadonly(PDecl, SIDecl);
1136  return true;
1137}
1138
1139/// CollectImmediateProperties - This routine collects all properties in
1140/// the class and its conforming protocols; but not those it its super class.
1141void Sema::CollectImmediateProperties(ObjCContainerDecl *CDecl,
1142            llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap,
1143            llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& SuperPropMap) {
1144  if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1145    for (ObjCContainerDecl::prop_iterator P = IDecl->prop_begin(),
1146         E = IDecl->prop_end(); P != E; ++P) {
1147      ObjCPropertyDecl *Prop = (*P);
1148      PropMap[Prop->getIdentifier()] = Prop;
1149    }
1150    // scan through class's protocols.
1151    for (ObjCInterfaceDecl::all_protocol_iterator
1152         PI = IDecl->all_referenced_protocol_begin(),
1153         E = IDecl->all_referenced_protocol_end(); PI != E; ++PI)
1154        CollectImmediateProperties((*PI), PropMap, SuperPropMap);
1155  }
1156  if (ObjCCategoryDecl *CATDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1157    if (!CATDecl->IsClassExtension())
1158      for (ObjCContainerDecl::prop_iterator P = CATDecl->prop_begin(),
1159           E = CATDecl->prop_end(); P != E; ++P) {
1160        ObjCPropertyDecl *Prop = (*P);
1161        PropMap[Prop->getIdentifier()] = Prop;
1162      }
1163    // scan through class's protocols.
1164    for (ObjCCategoryDecl::protocol_iterator PI = CATDecl->protocol_begin(),
1165         E = CATDecl->protocol_end(); PI != E; ++PI)
1166      CollectImmediateProperties((*PI), PropMap, SuperPropMap);
1167  }
1168  else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1169    for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
1170         E = PDecl->prop_end(); P != E; ++P) {
1171      ObjCPropertyDecl *Prop = (*P);
1172      ObjCPropertyDecl *PropertyFromSuper = SuperPropMap[Prop->getIdentifier()];
1173      // Exclude property for protocols which conform to class's super-class,
1174      // as super-class has to implement the property.
1175      if (!PropertyFromSuper ||
1176          PropertyFromSuper->getIdentifier() != Prop->getIdentifier()) {
1177        ObjCPropertyDecl *&PropEntry = PropMap[Prop->getIdentifier()];
1178        if (!PropEntry)
1179          PropEntry = Prop;
1180      }
1181    }
1182    // scan through protocol's protocols.
1183    for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
1184         E = PDecl->protocol_end(); PI != E; ++PI)
1185      CollectImmediateProperties((*PI), PropMap, SuperPropMap);
1186  }
1187}
1188
1189/// CollectClassPropertyImplementations - This routine collects list of
1190/// properties to be implemented in the class. This includes, class's
1191/// and its conforming protocols' properties.
1192static void CollectClassPropertyImplementations(ObjCContainerDecl *CDecl,
1193                llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap) {
1194  if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1195    for (ObjCContainerDecl::prop_iterator P = IDecl->prop_begin(),
1196         E = IDecl->prop_end(); P != E; ++P) {
1197      ObjCPropertyDecl *Prop = (*P);
1198      PropMap[Prop->getIdentifier()] = Prop;
1199    }
1200    for (ObjCInterfaceDecl::all_protocol_iterator
1201         PI = IDecl->all_referenced_protocol_begin(),
1202         E = IDecl->all_referenced_protocol_end(); PI != E; ++PI)
1203      CollectClassPropertyImplementations((*PI), PropMap);
1204  }
1205  else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1206    for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
1207         E = PDecl->prop_end(); P != E; ++P) {
1208      ObjCPropertyDecl *Prop = (*P);
1209      PropMap[Prop->getIdentifier()] = Prop;
1210    }
1211    // scan through protocol's protocols.
1212    for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
1213         E = PDecl->protocol_end(); PI != E; ++PI)
1214      CollectClassPropertyImplementations((*PI), PropMap);
1215  }
1216}
1217
1218/// CollectSuperClassPropertyImplementations - This routine collects list of
1219/// properties to be implemented in super class(s) and also coming from their
1220/// conforming protocols.
1221static void CollectSuperClassPropertyImplementations(ObjCInterfaceDecl *CDecl,
1222                llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap) {
1223  if (ObjCInterfaceDecl *SDecl = CDecl->getSuperClass()) {
1224    while (SDecl) {
1225      CollectClassPropertyImplementations(SDecl, PropMap);
1226      SDecl = SDecl->getSuperClass();
1227    }
1228  }
1229}
1230
1231/// LookupPropertyDecl - Looks up a property in the current class and all
1232/// its protocols.
1233ObjCPropertyDecl *Sema::LookupPropertyDecl(const ObjCContainerDecl *CDecl,
1234                                     IdentifierInfo *II) {
1235  if (const ObjCInterfaceDecl *IDecl =
1236        dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1237    for (ObjCContainerDecl::prop_iterator P = IDecl->prop_begin(),
1238         E = IDecl->prop_end(); P != E; ++P) {
1239      ObjCPropertyDecl *Prop = (*P);
1240      if (Prop->getIdentifier() == II)
1241        return Prop;
1242    }
1243    // scan through class's protocols.
1244    for (ObjCInterfaceDecl::all_protocol_iterator
1245         PI = IDecl->all_referenced_protocol_begin(),
1246         E = IDecl->all_referenced_protocol_end(); PI != E; ++PI) {
1247      ObjCPropertyDecl *Prop = LookupPropertyDecl((*PI), II);
1248      if (Prop)
1249        return Prop;
1250    }
1251  }
1252  else if (const ObjCProtocolDecl *PDecl =
1253            dyn_cast<ObjCProtocolDecl>(CDecl)) {
1254    for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
1255         E = PDecl->prop_end(); P != E; ++P) {
1256      ObjCPropertyDecl *Prop = (*P);
1257      if (Prop->getIdentifier() == II)
1258        return Prop;
1259    }
1260    // scan through protocol's protocols.
1261    for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
1262         E = PDecl->protocol_end(); PI != E; ++PI) {
1263      ObjCPropertyDecl *Prop = LookupPropertyDecl((*PI), II);
1264      if (Prop)
1265        return Prop;
1266    }
1267  }
1268  return 0;
1269}
1270
1271static IdentifierInfo * getDefaultSynthIvarName(ObjCPropertyDecl *Prop,
1272                                                ASTContext &Ctx) {
1273  llvm::SmallString<128> ivarName;
1274  {
1275    llvm::raw_svector_ostream os(ivarName);
1276    os << '_' << Prop->getIdentifier()->getName();
1277  }
1278  return &Ctx.Idents.get(ivarName.str());
1279}
1280
1281/// DefaultSynthesizeProperties - This routine default synthesizes all
1282/// properties which must be synthesized in class's @implementation.
1283void Sema::DefaultSynthesizeProperties(Scope *S, ObjCImplDecl* IMPDecl,
1284                                       ObjCInterfaceDecl *IDecl) {
1285
1286  llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*> PropMap;
1287  CollectClassPropertyImplementations(IDecl, PropMap);
1288  if (PropMap.empty())
1289    return;
1290  llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*> SuperPropMap;
1291  CollectSuperClassPropertyImplementations(IDecl, SuperPropMap);
1292
1293  for (llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>::iterator
1294       P = PropMap.begin(), E = PropMap.end(); P != E; ++P) {
1295    ObjCPropertyDecl *Prop = P->second;
1296    // If property to be implemented in the super class, ignore.
1297    if (SuperPropMap[Prop->getIdentifier()])
1298      continue;
1299    // Is there a matching propery synthesize/dynamic?
1300    if (Prop->isInvalidDecl() ||
1301        Prop->getPropertyImplementation() == ObjCPropertyDecl::Optional ||
1302        IMPDecl->FindPropertyImplIvarDecl(Prop->getIdentifier()))
1303      continue;
1304    // Property may have been synthesized by user.
1305    if (IMPDecl->FindPropertyImplDecl(Prop->getIdentifier()))
1306      continue;
1307    if (IMPDecl->getInstanceMethod(Prop->getGetterName())) {
1308      if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readonly)
1309        continue;
1310      if (IMPDecl->getInstanceMethod(Prop->getSetterName()))
1311        continue;
1312    }
1313
1314
1315    // We use invalid SourceLocations for the synthesized ivars since they
1316    // aren't really synthesized at a particular location; they just exist.
1317    // Saying that they are located at the @implementation isn't really going
1318    // to help users.
1319    ActOnPropertyImplDecl(S, SourceLocation(), SourceLocation(),
1320                          true,
1321                          /* property = */ Prop->getIdentifier(),
1322                          /* ivar = */ getDefaultSynthIvarName(Prop, Context),
1323                          SourceLocation());
1324  }
1325}
1326
1327void Sema::DefaultSynthesizeProperties(Scope *S, Decl *D) {
1328  if (!LangOpts.ObjCDefaultSynthProperties || !LangOpts.ObjCNonFragileABI2)
1329    return;
1330  ObjCImplementationDecl *IC=dyn_cast_or_null<ObjCImplementationDecl>(D);
1331  if (!IC)
1332    return;
1333  if (ObjCInterfaceDecl* IDecl = IC->getClassInterface())
1334    DefaultSynthesizeProperties(S, IC, IDecl);
1335}
1336
1337void Sema::DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
1338                                      ObjCContainerDecl *CDecl,
1339                                      const llvm::DenseSet<Selector>& InsMap) {
1340  llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*> SuperPropMap;
1341  if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl))
1342    CollectSuperClassPropertyImplementations(IDecl, SuperPropMap);
1343
1344  llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*> PropMap;
1345  CollectImmediateProperties(CDecl, PropMap, SuperPropMap);
1346  if (PropMap.empty())
1347    return;
1348
1349  llvm::DenseSet<ObjCPropertyDecl *> PropImplMap;
1350  for (ObjCImplDecl::propimpl_iterator
1351       I = IMPDecl->propimpl_begin(),
1352       EI = IMPDecl->propimpl_end(); I != EI; ++I)
1353    PropImplMap.insert((*I)->getPropertyDecl());
1354
1355  for (llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>::iterator
1356       P = PropMap.begin(), E = PropMap.end(); P != E; ++P) {
1357    ObjCPropertyDecl *Prop = P->second;
1358    // Is there a matching propery synthesize/dynamic?
1359    if (Prop->isInvalidDecl() ||
1360        Prop->getPropertyImplementation() == ObjCPropertyDecl::Optional ||
1361        PropImplMap.count(Prop) || Prop->hasAttr<UnavailableAttr>())
1362      continue;
1363    if (!InsMap.count(Prop->getGetterName())) {
1364      Diag(IMPDecl->getLocation(),
1365           isa<ObjCCategoryDecl>(CDecl) ?
1366            diag::warn_setter_getter_impl_required_in_category :
1367            diag::warn_setter_getter_impl_required)
1368      << Prop->getDeclName() << Prop->getGetterName();
1369      Diag(Prop->getLocation(),
1370           diag::note_property_declare);
1371    }
1372
1373    if (!Prop->isReadOnly() && !InsMap.count(Prop->getSetterName())) {
1374      Diag(IMPDecl->getLocation(),
1375           isa<ObjCCategoryDecl>(CDecl) ?
1376           diag::warn_setter_getter_impl_required_in_category :
1377           diag::warn_setter_getter_impl_required)
1378      << Prop->getDeclName() << Prop->getSetterName();
1379      Diag(Prop->getLocation(),
1380           diag::note_property_declare);
1381    }
1382  }
1383}
1384
1385void
1386Sema::AtomicPropertySetterGetterRules (ObjCImplDecl* IMPDecl,
1387                                       ObjCContainerDecl* IDecl) {
1388  // Rules apply in non-GC mode only
1389  if (getLangOptions().getGC() != LangOptions::NonGC)
1390    return;
1391  for (ObjCContainerDecl::prop_iterator I = IDecl->prop_begin(),
1392       E = IDecl->prop_end();
1393       I != E; ++I) {
1394    ObjCPropertyDecl *Property = (*I);
1395    ObjCMethodDecl *GetterMethod = 0;
1396    ObjCMethodDecl *SetterMethod = 0;
1397    bool LookedUpGetterSetter = false;
1398
1399    unsigned Attributes = Property->getPropertyAttributes();
1400    unsigned AttributesAsWritten = Property->getPropertyAttributesAsWritten();
1401
1402    if (!(AttributesAsWritten & ObjCPropertyDecl::OBJC_PR_atomic) &&
1403        !(AttributesAsWritten & ObjCPropertyDecl::OBJC_PR_nonatomic)) {
1404      GetterMethod = IMPDecl->getInstanceMethod(Property->getGetterName());
1405      SetterMethod = IMPDecl->getInstanceMethod(Property->getSetterName());
1406      LookedUpGetterSetter = true;
1407      if (GetterMethod) {
1408        Diag(GetterMethod->getLocation(),
1409             diag::warn_default_atomic_custom_getter_setter)
1410          << Property->getIdentifier() << 0;
1411        Diag(Property->getLocation(), diag::note_property_declare);
1412      }
1413      if (SetterMethod) {
1414        Diag(SetterMethod->getLocation(),
1415             diag::warn_default_atomic_custom_getter_setter)
1416          << Property->getIdentifier() << 1;
1417        Diag(Property->getLocation(), diag::note_property_declare);
1418      }
1419    }
1420
1421    // We only care about readwrite atomic property.
1422    if ((Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) ||
1423        !(Attributes & ObjCPropertyDecl::OBJC_PR_readwrite))
1424      continue;
1425    if (const ObjCPropertyImplDecl *PIDecl
1426         = IMPDecl->FindPropertyImplDecl(Property->getIdentifier())) {
1427      if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
1428        continue;
1429      if (!LookedUpGetterSetter) {
1430        GetterMethod = IMPDecl->getInstanceMethod(Property->getGetterName());
1431        SetterMethod = IMPDecl->getInstanceMethod(Property->getSetterName());
1432        LookedUpGetterSetter = true;
1433      }
1434      if ((GetterMethod && !SetterMethod) || (!GetterMethod && SetterMethod)) {
1435        SourceLocation MethodLoc =
1436          (GetterMethod ? GetterMethod->getLocation()
1437                        : SetterMethod->getLocation());
1438        Diag(MethodLoc, diag::warn_atomic_property_rule)
1439          << Property->getIdentifier() << (GetterMethod != 0)
1440          << (SetterMethod != 0);
1441        Diag(MethodLoc, diag::note_atomic_property_fixup_suggest);
1442        Diag(Property->getLocation(), diag::note_property_declare);
1443      }
1444    }
1445  }
1446}
1447
1448void Sema::DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D) {
1449  if (getLangOptions().getGC() == LangOptions::GCOnly)
1450    return;
1451
1452  for (ObjCImplementationDecl::propimpl_iterator
1453         i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
1454    ObjCPropertyImplDecl *PID = *i;
1455    if (PID->getPropertyImplementation() != ObjCPropertyImplDecl::Synthesize)
1456      continue;
1457
1458    const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1459    if (PD && !PD->hasAttr<NSReturnsNotRetainedAttr>() &&
1460        !D->getInstanceMethod(PD->getGetterName())) {
1461      ObjCMethodDecl *method = PD->getGetterMethodDecl();
1462      if (!method)
1463        continue;
1464      ObjCMethodFamily family = method->getMethodFamily();
1465      if (family == OMF_alloc || family == OMF_copy ||
1466          family == OMF_mutableCopy || family == OMF_new) {
1467        if (getLangOptions().ObjCAutoRefCount)
1468          Diag(PID->getLocation(), diag::err_ownin_getter_rule);
1469        else
1470          Diag(PID->getLocation(), diag::warn_owning_getter_rule);
1471        Diag(PD->getLocation(), diag::note_property_declare);
1472      }
1473    }
1474  }
1475}
1476
1477/// AddPropertyAttrs - Propagates attributes from a property to the
1478/// implicitly-declared getter or setter for that property.
1479static void AddPropertyAttrs(Sema &S, ObjCMethodDecl *PropertyMethod,
1480                             ObjCPropertyDecl *Property) {
1481  // Should we just clone all attributes over?
1482  for (Decl::attr_iterator A = Property->attr_begin(),
1483                        AEnd = Property->attr_end();
1484       A != AEnd; ++A) {
1485    if (isa<DeprecatedAttr>(*A) ||
1486        isa<UnavailableAttr>(*A) ||
1487        isa<AvailabilityAttr>(*A))
1488      PropertyMethod->addAttr((*A)->clone(S.Context));
1489  }
1490}
1491
1492/// ProcessPropertyDecl - Make sure that any user-defined setter/getter methods
1493/// have the property type and issue diagnostics if they don't.
1494/// Also synthesize a getter/setter method if none exist (and update the
1495/// appropriate lookup tables. FIXME: Should reconsider if adding synthesized
1496/// methods is the "right" thing to do.
1497void Sema::ProcessPropertyDecl(ObjCPropertyDecl *property,
1498                               ObjCContainerDecl *CD,
1499                               ObjCPropertyDecl *redeclaredProperty,
1500                               ObjCContainerDecl *lexicalDC) {
1501
1502  ObjCMethodDecl *GetterMethod, *SetterMethod;
1503
1504  GetterMethod = CD->getInstanceMethod(property->getGetterName());
1505  SetterMethod = CD->getInstanceMethod(property->getSetterName());
1506  DiagnosePropertyAccessorMismatch(property, GetterMethod,
1507                                   property->getLocation());
1508
1509  if (SetterMethod) {
1510    ObjCPropertyDecl::PropertyAttributeKind CAttr =
1511      property->getPropertyAttributes();
1512    if ((!(CAttr & ObjCPropertyDecl::OBJC_PR_readonly)) &&
1513        Context.getCanonicalType(SetterMethod->getResultType()) !=
1514          Context.VoidTy)
1515      Diag(SetterMethod->getLocation(), diag::err_setter_type_void);
1516    if (SetterMethod->param_size() != 1 ||
1517        !Context.hasSameUnqualifiedType(
1518          (*SetterMethod->param_begin())->getType().getNonReferenceType(),
1519          property->getType().getNonReferenceType())) {
1520      Diag(property->getLocation(),
1521           diag::warn_accessor_property_type_mismatch)
1522        << property->getDeclName()
1523        << SetterMethod->getSelector();
1524      Diag(SetterMethod->getLocation(), diag::note_declared_at);
1525    }
1526  }
1527
1528  // Synthesize getter/setter methods if none exist.
1529  // Find the default getter and if one not found, add one.
1530  // FIXME: The synthesized property we set here is misleading. We almost always
1531  // synthesize these methods unless the user explicitly provided prototypes
1532  // (which is odd, but allowed). Sema should be typechecking that the
1533  // declarations jive in that situation (which it is not currently).
1534  if (!GetterMethod) {
1535    // No instance method of same name as property getter name was found.
1536    // Declare a getter method and add it to the list of methods
1537    // for this class.
1538    SourceLocation Loc = redeclaredProperty ?
1539      redeclaredProperty->getLocation() :
1540      property->getLocation();
1541
1542    GetterMethod = ObjCMethodDecl::Create(Context, Loc, Loc,
1543                             property->getGetterName(),
1544                             property->getType(), 0, CD, /*isInstance=*/true,
1545                             /*isVariadic=*/false, /*isSynthesized=*/true,
1546                             /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1547                             (property->getPropertyImplementation() ==
1548                              ObjCPropertyDecl::Optional) ?
1549                             ObjCMethodDecl::Optional :
1550                             ObjCMethodDecl::Required);
1551    CD->addDecl(GetterMethod);
1552
1553    AddPropertyAttrs(*this, GetterMethod, property);
1554
1555    // FIXME: Eventually this shouldn't be needed, as the lexical context
1556    // and the real context should be the same.
1557    if (lexicalDC)
1558      GetterMethod->setLexicalDeclContext(lexicalDC);
1559    if (property->hasAttr<NSReturnsNotRetainedAttr>())
1560      GetterMethod->addAttr(
1561        ::new (Context) NSReturnsNotRetainedAttr(Loc, Context));
1562  } else
1563    // A user declared getter will be synthesize when @synthesize of
1564    // the property with the same name is seen in the @implementation
1565    GetterMethod->setSynthesized(true);
1566  property->setGetterMethodDecl(GetterMethod);
1567
1568  // Skip setter if property is read-only.
1569  if (!property->isReadOnly()) {
1570    // Find the default setter and if one not found, add one.
1571    if (!SetterMethod) {
1572      // No instance method of same name as property setter name was found.
1573      // Declare a setter method and add it to the list of methods
1574      // for this class.
1575      SourceLocation Loc = redeclaredProperty ?
1576        redeclaredProperty->getLocation() :
1577        property->getLocation();
1578
1579      SetterMethod =
1580        ObjCMethodDecl::Create(Context, Loc, Loc,
1581                               property->getSetterName(), Context.VoidTy, 0,
1582                               CD, /*isInstance=*/true, /*isVariadic=*/false,
1583                               /*isSynthesized=*/true,
1584                               /*isImplicitlyDeclared=*/true,
1585                               /*isDefined=*/false,
1586                               (property->getPropertyImplementation() ==
1587                                ObjCPropertyDecl::Optional) ?
1588                                ObjCMethodDecl::Optional :
1589                                ObjCMethodDecl::Required);
1590
1591      // Invent the arguments for the setter. We don't bother making a
1592      // nice name for the argument.
1593      ParmVarDecl *Argument = ParmVarDecl::Create(Context, SetterMethod,
1594                                                  Loc, Loc,
1595                                                  property->getIdentifier(),
1596                                    property->getType().getUnqualifiedType(),
1597                                                  /*TInfo=*/0,
1598                                                  SC_None,
1599                                                  SC_None,
1600                                                  0);
1601      SetterMethod->setMethodParams(Context, Argument,
1602                                    ArrayRef<SourceLocation>());
1603
1604      AddPropertyAttrs(*this, SetterMethod, property);
1605
1606      CD->addDecl(SetterMethod);
1607      // FIXME: Eventually this shouldn't be needed, as the lexical context
1608      // and the real context should be the same.
1609      if (lexicalDC)
1610        SetterMethod->setLexicalDeclContext(lexicalDC);
1611    } else
1612      // A user declared setter will be synthesize when @synthesize of
1613      // the property with the same name is seen in the @implementation
1614      SetterMethod->setSynthesized(true);
1615    property->setSetterMethodDecl(SetterMethod);
1616  }
1617  // Add any synthesized methods to the global pool. This allows us to
1618  // handle the following, which is supported by GCC (and part of the design).
1619  //
1620  // @interface Foo
1621  // @property double bar;
1622  // @end
1623  //
1624  // void thisIsUnfortunate() {
1625  //   id foo;
1626  //   double bar = [foo bar];
1627  // }
1628  //
1629  if (GetterMethod)
1630    AddInstanceMethodToGlobalPool(GetterMethod);
1631  if (SetterMethod)
1632    AddInstanceMethodToGlobalPool(SetterMethod);
1633}
1634
1635void Sema::CheckObjCPropertyAttributes(Decl *PDecl,
1636                                       SourceLocation Loc,
1637                                       unsigned &Attributes) {
1638  // FIXME: Improve the reported location.
1639  if (!PDecl || PDecl->isInvalidDecl())
1640    return;
1641
1642  ObjCPropertyDecl *PropertyDecl = cast<ObjCPropertyDecl>(PDecl);
1643  QualType PropertyTy = PropertyDecl->getType();
1644
1645  // readonly and readwrite/assign/retain/copy conflict.
1646  if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1647      (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
1648                     ObjCDeclSpec::DQ_PR_assign |
1649                     ObjCDeclSpec::DQ_PR_unsafe_unretained |
1650                     ObjCDeclSpec::DQ_PR_copy |
1651                     ObjCDeclSpec::DQ_PR_retain |
1652                     ObjCDeclSpec::DQ_PR_strong))) {
1653    const char * which = (Attributes & ObjCDeclSpec::DQ_PR_readwrite) ?
1654                          "readwrite" :
1655                         (Attributes & ObjCDeclSpec::DQ_PR_assign) ?
1656                          "assign" :
1657                         (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) ?
1658                          "unsafe_unretained" :
1659                         (Attributes & ObjCDeclSpec::DQ_PR_copy) ?
1660                          "copy" : "retain";
1661
1662    Diag(Loc, (Attributes & (ObjCDeclSpec::DQ_PR_readwrite)) ?
1663                 diag::err_objc_property_attr_mutually_exclusive :
1664                 diag::warn_objc_property_attr_mutually_exclusive)
1665      << "readonly" << which;
1666  }
1667
1668  // Check for copy or retain on non-object types.
1669  if ((Attributes & (ObjCDeclSpec::DQ_PR_weak | ObjCDeclSpec::DQ_PR_copy |
1670                    ObjCDeclSpec::DQ_PR_retain | ObjCDeclSpec::DQ_PR_strong)) &&
1671      !PropertyTy->isObjCRetainableType() &&
1672      !PropertyDecl->getAttr<ObjCNSObjectAttr>()) {
1673    Diag(Loc, diag::err_objc_property_requires_object)
1674      << (Attributes & ObjCDeclSpec::DQ_PR_weak ? "weak" :
1675          Attributes & ObjCDeclSpec::DQ_PR_copy ? "copy" : "retain (or strong)");
1676    Attributes &= ~(ObjCDeclSpec::DQ_PR_weak   | ObjCDeclSpec::DQ_PR_copy |
1677                    ObjCDeclSpec::DQ_PR_retain | ObjCDeclSpec::DQ_PR_strong);
1678  }
1679
1680  // Check for more than one of { assign, copy, retain }.
1681  if (Attributes & ObjCDeclSpec::DQ_PR_assign) {
1682    if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
1683      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1684        << "assign" << "copy";
1685      Attributes &= ~ObjCDeclSpec::DQ_PR_copy;
1686    }
1687    if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
1688      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1689        << "assign" << "retain";
1690      Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
1691    }
1692    if (Attributes & ObjCDeclSpec::DQ_PR_strong) {
1693      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1694        << "assign" << "strong";
1695      Attributes &= ~ObjCDeclSpec::DQ_PR_strong;
1696    }
1697    if (getLangOptions().ObjCAutoRefCount  &&
1698        (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
1699      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1700        << "assign" << "weak";
1701      Attributes &= ~ObjCDeclSpec::DQ_PR_weak;
1702    }
1703  } else if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) {
1704    if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
1705      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1706        << "unsafe_unretained" << "copy";
1707      Attributes &= ~ObjCDeclSpec::DQ_PR_copy;
1708    }
1709    if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
1710      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1711        << "unsafe_unretained" << "retain";
1712      Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
1713    }
1714    if (Attributes & ObjCDeclSpec::DQ_PR_strong) {
1715      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1716        << "unsafe_unretained" << "strong";
1717      Attributes &= ~ObjCDeclSpec::DQ_PR_strong;
1718    }
1719    if (getLangOptions().ObjCAutoRefCount  &&
1720        (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
1721      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1722        << "unsafe_unretained" << "weak";
1723      Attributes &= ~ObjCDeclSpec::DQ_PR_weak;
1724    }
1725  } else if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
1726    if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
1727      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1728        << "copy" << "retain";
1729      Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
1730    }
1731    if (Attributes & ObjCDeclSpec::DQ_PR_strong) {
1732      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1733        << "copy" << "strong";
1734      Attributes &= ~ObjCDeclSpec::DQ_PR_strong;
1735    }
1736    if (Attributes & ObjCDeclSpec::DQ_PR_weak) {
1737      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1738        << "copy" << "weak";
1739      Attributes &= ~ObjCDeclSpec::DQ_PR_weak;
1740    }
1741  }
1742  else if ((Attributes & ObjCDeclSpec::DQ_PR_retain) &&
1743           (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
1744      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1745        << "retain" << "weak";
1746      Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
1747  }
1748  else if ((Attributes & ObjCDeclSpec::DQ_PR_strong) &&
1749           (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
1750      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1751        << "strong" << "weak";
1752      Attributes &= ~ObjCDeclSpec::DQ_PR_weak;
1753  }
1754
1755  if ((Attributes & ObjCDeclSpec::DQ_PR_atomic) &&
1756      (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)) {
1757      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1758        << "atomic" << "nonatomic";
1759      Attributes &= ~ObjCDeclSpec::DQ_PR_atomic;
1760  }
1761
1762  // Warn if user supplied no assignment attribute, property is
1763  // readwrite, and this is an object type.
1764  if (!(Attributes & (ObjCDeclSpec::DQ_PR_assign | ObjCDeclSpec::DQ_PR_copy |
1765                      ObjCDeclSpec::DQ_PR_unsafe_unretained |
1766                      ObjCDeclSpec::DQ_PR_retain | ObjCDeclSpec::DQ_PR_strong |
1767                      ObjCDeclSpec::DQ_PR_weak)) &&
1768      !(Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1769      PropertyTy->isObjCObjectPointerType()) {
1770      if (getLangOptions().ObjCAutoRefCount)
1771        // With arc,  @property definitions should default to (strong) when
1772        // not specified
1773        PropertyDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong);
1774      else {
1775          // Skip this warning in gc-only mode.
1776          if (getLangOptions().getGC() != LangOptions::GCOnly)
1777            Diag(Loc, diag::warn_objc_property_no_assignment_attribute);
1778
1779          // If non-gc code warn that this is likely inappropriate.
1780          if (getLangOptions().getGC() == LangOptions::NonGC)
1781            Diag(Loc, diag::warn_objc_property_default_assign_on_object);
1782      }
1783
1784    // FIXME: Implement warning dependent on NSCopying being
1785    // implemented. See also:
1786    // <rdar://5168496&4855821&5607453&5096644&4947311&5698469&4947014&5168496>
1787    // (please trim this list while you are at it).
1788  }
1789
1790  if (!(Attributes & ObjCDeclSpec::DQ_PR_copy)
1791      &&!(Attributes & ObjCDeclSpec::DQ_PR_readonly)
1792      && getLangOptions().getGC() == LangOptions::GCOnly
1793      && PropertyTy->isBlockPointerType())
1794    Diag(Loc, diag::warn_objc_property_copy_missing_on_block);
1795  else if (getLangOptions().ObjCAutoRefCount &&
1796           (Attributes & ObjCDeclSpec::DQ_PR_retain) &&
1797           !(Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1798           !(Attributes & ObjCDeclSpec::DQ_PR_strong) &&
1799           PropertyTy->isBlockPointerType())
1800      Diag(Loc, diag::warn_objc_property_retain_of_block);
1801}
1802