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/AST/ASTMutationListener.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Lex/Lexer.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "clang/Sema/Initialization.h"
24 #include "llvm/ADT/DenseSet.h"
25 #include "llvm/ADT/SmallString.h"
26 
27 using namespace clang;
28 
29 //===----------------------------------------------------------------------===//
30 // Grammar actions.
31 //===----------------------------------------------------------------------===//
32 
33 /// getImpliedARCOwnership - Given a set of property attributes and a
34 /// type, infer an expected lifetime.  The type's ownership qualification
35 /// is not considered.
36 ///
37 /// Returns OCL_None if the attributes as stated do not imply an ownership.
38 /// Never returns OCL_Autoreleasing.
39 static Qualifiers::ObjCLifetime getImpliedARCOwnership(
40                                ObjCPropertyDecl::PropertyAttributeKind attrs,
41                                                 QualType type) {
42   // retain, strong, copy, weak, and unsafe_unretained are only legal
43   // on properties of retainable pointer type.
44   if (attrs & (ObjCPropertyDecl::OBJC_PR_retain |
45                ObjCPropertyDecl::OBJC_PR_strong |
46                ObjCPropertyDecl::OBJC_PR_copy)) {
47     return Qualifiers::OCL_Strong;
48   } else if (attrs & ObjCPropertyDecl::OBJC_PR_weak) {
49     return Qualifiers::OCL_Weak;
50   } else if (attrs & ObjCPropertyDecl::OBJC_PR_unsafe_unretained) {
51     return Qualifiers::OCL_ExplicitNone;
52   }
53 
54   // assign can appear on other types, so we have to check the
55   // property type.
56   if (attrs & ObjCPropertyDecl::OBJC_PR_assign &&
57       type->isObjCRetainableType()) {
58     return Qualifiers::OCL_ExplicitNone;
59   }
60 
61   return Qualifiers::OCL_None;
62 }
63 
64 /// Check the internal consistency of a property declaration.
65 static void checkARCPropertyDecl(Sema &S, ObjCPropertyDecl *property) {
66   if (property->isInvalidDecl()) return;
67 
68   ObjCPropertyDecl::PropertyAttributeKind propertyKind
69     = property->getPropertyAttributes();
70   Qualifiers::ObjCLifetime propertyLifetime
71     = property->getType().getObjCLifetime();
72 
73   // Nothing to do if we don't have a lifetime.
74   if (propertyLifetime == Qualifiers::OCL_None) return;
75 
76   Qualifiers::ObjCLifetime expectedLifetime
77     = getImpliedARCOwnership(propertyKind, property->getType());
78   if (!expectedLifetime) {
79     // We have a lifetime qualifier but no dominating property
80     // attribute.  That's okay, but restore reasonable invariants by
81     // setting the property attribute according to the lifetime
82     // qualifier.
83     ObjCPropertyDecl::PropertyAttributeKind attr;
84     if (propertyLifetime == Qualifiers::OCL_Strong) {
85       attr = ObjCPropertyDecl::OBJC_PR_strong;
86     } else if (propertyLifetime == Qualifiers::OCL_Weak) {
87       attr = ObjCPropertyDecl::OBJC_PR_weak;
88     } else {
89       assert(propertyLifetime == Qualifiers::OCL_ExplicitNone);
90       attr = ObjCPropertyDecl::OBJC_PR_unsafe_unretained;
91     }
92     property->setPropertyAttributes(attr);
93     return;
94   }
95 
96   if (propertyLifetime == expectedLifetime) return;
97 
98   property->setInvalidDecl();
99   S.Diag(property->getLocation(),
100          diag::err_arc_inconsistent_property_ownership)
101     << property->getDeclName()
102     << expectedLifetime
103     << propertyLifetime;
104 }
105 
106 static unsigned deduceWeakPropertyFromType(Sema &S, QualType T) {
107   if ((S.getLangOpts().getGC() != LangOptions::NonGC &&
108        T.isObjCGCWeak()) ||
109       (S.getLangOpts().ObjCAutoRefCount &&
110        T.getObjCLifetime() == Qualifiers::OCL_Weak))
111     return ObjCDeclSpec::DQ_PR_weak;
112   return 0;
113 }
114 
115 /// \brief Check this Objective-C property against a property declared in the
116 /// given protocol.
117 static void
118 CheckPropertyAgainstProtocol(Sema &S, ObjCPropertyDecl *Prop,
119                              ObjCProtocolDecl *Proto,
120                              llvm::SmallPtrSet<ObjCProtocolDecl *, 16> &Known) {
121   // Have we seen this protocol before?
122   if (!Known.insert(Proto))
123     return;
124 
125   // Look for a property with the same name.
126   DeclContext::lookup_result R = Proto->lookup(Prop->getDeclName());
127   for (unsigned I = 0, N = R.size(); I != N; ++I) {
128     if (ObjCPropertyDecl *ProtoProp = dyn_cast<ObjCPropertyDecl>(R[I])) {
129       S.DiagnosePropertyMismatch(Prop, ProtoProp, Proto->getIdentifier(), true);
130       return;
131     }
132   }
133 
134   // Check this property against any protocols we inherit.
135   for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
136                                         PEnd = Proto->protocol_end();
137        P != PEnd; ++P) {
138     CheckPropertyAgainstProtocol(S, Prop, *P, Known);
139   }
140 }
141 
142 Decl *Sema::ActOnProperty(Scope *S, SourceLocation AtLoc,
143                           SourceLocation LParenLoc,
144                           FieldDeclarator &FD,
145                           ObjCDeclSpec &ODS,
146                           Selector GetterSel,
147                           Selector SetterSel,
148                           bool *isOverridingProperty,
149                           tok::ObjCKeywordKind MethodImplKind,
150                           DeclContext *lexicalDC) {
151   unsigned Attributes = ODS.getPropertyAttributes();
152   TypeSourceInfo *TSI = GetTypeForDeclarator(FD.D, S);
153   QualType T = TSI->getType();
154   Attributes |= deduceWeakPropertyFromType(*this, T);
155 
156   bool isReadWrite = ((Attributes & ObjCDeclSpec::DQ_PR_readwrite) ||
157                       // default is readwrite!
158                       !(Attributes & ObjCDeclSpec::DQ_PR_readonly));
159   // property is defaulted to 'assign' if it is readwrite and is
160   // not retain or copy
161   bool isAssign = ((Attributes & ObjCDeclSpec::DQ_PR_assign) ||
162                    (isReadWrite &&
163                     !(Attributes & ObjCDeclSpec::DQ_PR_retain) &&
164                     !(Attributes & ObjCDeclSpec::DQ_PR_strong) &&
165                     !(Attributes & ObjCDeclSpec::DQ_PR_copy) &&
166                     !(Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) &&
167                     !(Attributes & ObjCDeclSpec::DQ_PR_weak)));
168 
169   // Proceed with constructing the ObjCPropertyDecls.
170   ObjCContainerDecl *ClassDecl = cast<ObjCContainerDecl>(CurContext);
171   ObjCPropertyDecl *Res = 0;
172   if (ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
173     if (CDecl->IsClassExtension()) {
174       Res = HandlePropertyInClassExtension(S, AtLoc, LParenLoc,
175                                            FD, GetterSel, SetterSel,
176                                            isAssign, isReadWrite,
177                                            Attributes,
178                                            ODS.getPropertyAttributes(),
179                                            isOverridingProperty, TSI,
180                                            MethodImplKind);
181       if (!Res)
182         return 0;
183     }
184   }
185 
186   if (!Res) {
187     Res = CreatePropertyDecl(S, ClassDecl, AtLoc, LParenLoc, FD,
188                              GetterSel, SetterSel, isAssign, isReadWrite,
189                              Attributes, ODS.getPropertyAttributes(),
190                              TSI, MethodImplKind);
191     if (lexicalDC)
192       Res->setLexicalDeclContext(lexicalDC);
193   }
194 
195   // Validate the attributes on the @property.
196   CheckObjCPropertyAttributes(Res, AtLoc, Attributes,
197                               (isa<ObjCInterfaceDecl>(ClassDecl) ||
198                                isa<ObjCProtocolDecl>(ClassDecl)));
199 
200   if (getLangOpts().ObjCAutoRefCount)
201     checkARCPropertyDecl(*this, Res);
202 
203   llvm::SmallPtrSet<ObjCProtocolDecl *, 16> KnownProtos;
204   if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
205     // For a class, compare the property against a property in our superclass.
206     bool FoundInSuper = false;
207     if (ObjCInterfaceDecl *Super = IFace->getSuperClass()) {
208       DeclContext::lookup_result R = Super->lookup(Res->getDeclName());
209       for (unsigned I = 0, N = R.size(); I != N; ++I) {
210         if (ObjCPropertyDecl *SuperProp = dyn_cast<ObjCPropertyDecl>(R[I])) {
211           DiagnosePropertyMismatch(Res, SuperProp, Super->getIdentifier(), false);
212           FoundInSuper = true;
213           break;
214         }
215       }
216     }
217 
218     if (FoundInSuper) {
219       // Also compare the property against a property in our protocols.
220       for (ObjCInterfaceDecl::protocol_iterator P = IFace->protocol_begin(),
221                                              PEnd = IFace->protocol_end();
222            P != PEnd; ++P) {
223         CheckPropertyAgainstProtocol(*this, Res, *P, KnownProtos);
224       }
225     } else {
226       // Slower path: look in all protocols we referenced.
227       for (ObjCInterfaceDecl::all_protocol_iterator
228              P = IFace->all_referenced_protocol_begin(),
229              PEnd = IFace->all_referenced_protocol_end();
230            P != PEnd; ++P) {
231         CheckPropertyAgainstProtocol(*this, Res, *P, KnownProtos);
232       }
233     }
234   } else if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
235     for (ObjCCategoryDecl::protocol_iterator P = Cat->protocol_begin(),
236                                           PEnd = Cat->protocol_end();
237          P != PEnd; ++P) {
238       CheckPropertyAgainstProtocol(*this, Res, *P, KnownProtos);
239     }
240   } else {
241     ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(ClassDecl);
242     for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
243                                           PEnd = Proto->protocol_end();
244          P != PEnd; ++P) {
245       CheckPropertyAgainstProtocol(*this, Res, *P, KnownProtos);
246     }
247   }
248 
249   ActOnDocumentableDecl(Res);
250   return Res;
251 }
252 
253 static ObjCPropertyDecl::PropertyAttributeKind
254 makePropertyAttributesAsWritten(unsigned Attributes) {
255   unsigned attributesAsWritten = 0;
256   if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
257     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_readonly;
258   if (Attributes & ObjCDeclSpec::DQ_PR_readwrite)
259     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_readwrite;
260   if (Attributes & ObjCDeclSpec::DQ_PR_getter)
261     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_getter;
262   if (Attributes & ObjCDeclSpec::DQ_PR_setter)
263     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_setter;
264   if (Attributes & ObjCDeclSpec::DQ_PR_assign)
265     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_assign;
266   if (Attributes & ObjCDeclSpec::DQ_PR_retain)
267     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_retain;
268   if (Attributes & ObjCDeclSpec::DQ_PR_strong)
269     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_strong;
270   if (Attributes & ObjCDeclSpec::DQ_PR_weak)
271     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_weak;
272   if (Attributes & ObjCDeclSpec::DQ_PR_copy)
273     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_copy;
274   if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained)
275     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_unsafe_unretained;
276   if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)
277     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_nonatomic;
278   if (Attributes & ObjCDeclSpec::DQ_PR_atomic)
279     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_atomic;
280 
281   return (ObjCPropertyDecl::PropertyAttributeKind)attributesAsWritten;
282 }
283 
284 static bool LocPropertyAttribute( ASTContext &Context, const char *attrName,
285                                  SourceLocation LParenLoc, SourceLocation &Loc) {
286   if (LParenLoc.isMacroID())
287     return false;
288 
289   SourceManager &SM = Context.getSourceManager();
290   std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(LParenLoc);
291   // Try to load the file buffer.
292   bool invalidTemp = false;
293   StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
294   if (invalidTemp)
295     return false;
296   const char *tokenBegin = file.data() + locInfo.second;
297 
298   // Lex from the start of the given location.
299   Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
300               Context.getLangOpts(),
301               file.begin(), tokenBegin, file.end());
302   Token Tok;
303   do {
304     lexer.LexFromRawLexer(Tok);
305     if (Tok.is(tok::raw_identifier) &&
306         StringRef(Tok.getRawIdentifierData(), Tok.getLength()) == attrName) {
307       Loc = Tok.getLocation();
308       return true;
309     }
310   } while (Tok.isNot(tok::r_paren));
311   return false;
312 
313 }
314 
315 static unsigned getOwnershipRule(unsigned attr) {
316   return attr & (ObjCPropertyDecl::OBJC_PR_assign |
317                  ObjCPropertyDecl::OBJC_PR_retain |
318                  ObjCPropertyDecl::OBJC_PR_copy   |
319                  ObjCPropertyDecl::OBJC_PR_weak   |
320                  ObjCPropertyDecl::OBJC_PR_strong |
321                  ObjCPropertyDecl::OBJC_PR_unsafe_unretained);
322 }
323 
324 ObjCPropertyDecl *
325 Sema::HandlePropertyInClassExtension(Scope *S,
326                                      SourceLocation AtLoc,
327                                      SourceLocation LParenLoc,
328                                      FieldDeclarator &FD,
329                                      Selector GetterSel, Selector SetterSel,
330                                      const bool isAssign,
331                                      const bool isReadWrite,
332                                      const unsigned Attributes,
333                                      const unsigned AttributesAsWritten,
334                                      bool *isOverridingProperty,
335                                      TypeSourceInfo *T,
336                                      tok::ObjCKeywordKind MethodImplKind) {
337   ObjCCategoryDecl *CDecl = cast<ObjCCategoryDecl>(CurContext);
338   // Diagnose if this property is already in continuation class.
339   DeclContext *DC = CurContext;
340   IdentifierInfo *PropertyId = FD.D.getIdentifier();
341   ObjCInterfaceDecl *CCPrimary = CDecl->getClassInterface();
342 
343   if (CCPrimary) {
344     // Check for duplicate declaration of this property in current and
345     // other class extensions.
346     for (ObjCInterfaceDecl::known_extensions_iterator
347            Ext = CCPrimary->known_extensions_begin(),
348            ExtEnd = CCPrimary->known_extensions_end();
349          Ext != ExtEnd; ++Ext) {
350       if (ObjCPropertyDecl *prevDecl
351             = ObjCPropertyDecl::findPropertyDecl(*Ext, PropertyId)) {
352         Diag(AtLoc, diag::err_duplicate_property);
353         Diag(prevDecl->getLocation(), diag::note_property_declare);
354         return 0;
355       }
356     }
357   }
358 
359   // Create a new ObjCPropertyDecl with the DeclContext being
360   // the class extension.
361   // FIXME. We should really be using CreatePropertyDecl for this.
362   ObjCPropertyDecl *PDecl =
363     ObjCPropertyDecl::Create(Context, DC, FD.D.getIdentifierLoc(),
364                              PropertyId, AtLoc, LParenLoc, T);
365   PDecl->setPropertyAttributesAsWritten(
366                           makePropertyAttributesAsWritten(AttributesAsWritten));
367   if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
368     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly);
369   if (Attributes & ObjCDeclSpec::DQ_PR_readwrite)
370     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite);
371   if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)
372     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nonatomic);
373   if (Attributes & ObjCDeclSpec::DQ_PR_atomic)
374     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_atomic);
375   // Set setter/getter selector name. Needed later.
376   PDecl->setGetterName(GetterSel);
377   PDecl->setSetterName(SetterSel);
378   ProcessDeclAttributes(S, PDecl, FD.D);
379   DC->addDecl(PDecl);
380 
381   // We need to look in the @interface to see if the @property was
382   // already declared.
383   if (!CCPrimary) {
384     Diag(CDecl->getLocation(), diag::err_continuation_class);
385     *isOverridingProperty = true;
386     return 0;
387   }
388 
389   // Find the property in continuation class's primary class only.
390   ObjCPropertyDecl *PIDecl =
391     CCPrimary->FindPropertyVisibleInPrimaryClass(PropertyId);
392 
393   if (!PIDecl) {
394     // No matching property found in the primary class. Just fall thru
395     // and add property to continuation class's primary class.
396     ObjCPropertyDecl *PrimaryPDecl =
397       CreatePropertyDecl(S, CCPrimary, AtLoc, LParenLoc,
398                          FD, GetterSel, SetterSel, isAssign, isReadWrite,
399                          Attributes,AttributesAsWritten, T, MethodImplKind, DC);
400 
401     // A case of continuation class adding a new property in the class. This
402     // is not what it was meant for. However, gcc supports it and so should we.
403     // Make sure setter/getters are declared here.
404     ProcessPropertyDecl(PrimaryPDecl, CCPrimary, /* redeclaredProperty = */ 0,
405                         /* lexicalDC = */ CDecl);
406     PDecl->setGetterMethodDecl(PrimaryPDecl->getGetterMethodDecl());
407     PDecl->setSetterMethodDecl(PrimaryPDecl->getSetterMethodDecl());
408     if (ASTMutationListener *L = Context.getASTMutationListener())
409       L->AddedObjCPropertyInClassExtension(PrimaryPDecl, /*OrigProp=*/0, CDecl);
410     return PrimaryPDecl;
411   }
412   if (!Context.hasSameType(PIDecl->getType(), PDecl->getType())) {
413     bool IncompatibleObjC = false;
414     QualType ConvertedType;
415     // Relax the strict type matching for property type in continuation class.
416     // Allow property object type of continuation class to be different as long
417     // as it narrows the object type in its primary class property. Note that
418     // this conversion is safe only because the wider type is for a 'readonly'
419     // property in primary class and 'narrowed' type for a 'readwrite' property
420     // in continuation class.
421     if (!isa<ObjCObjectPointerType>(PIDecl->getType()) ||
422         !isa<ObjCObjectPointerType>(PDecl->getType()) ||
423         (!isObjCPointerConversion(PDecl->getType(), PIDecl->getType(),
424                                   ConvertedType, IncompatibleObjC))
425         || IncompatibleObjC) {
426       Diag(AtLoc,
427           diag::err_type_mismatch_continuation_class) << PDecl->getType();
428       Diag(PIDecl->getLocation(), diag::note_property_declare);
429       return 0;
430     }
431   }
432 
433   // The property 'PIDecl's readonly attribute will be over-ridden
434   // with continuation class's readwrite property attribute!
435   unsigned PIkind = PIDecl->getPropertyAttributesAsWritten();
436   if (isReadWrite && (PIkind & ObjCPropertyDecl::OBJC_PR_readonly)) {
437     PIkind &= ~ObjCPropertyDecl::OBJC_PR_readonly;
438     PIkind |= ObjCPropertyDecl::OBJC_PR_readwrite;
439     PIkind |= deduceWeakPropertyFromType(*this, PIDecl->getType());
440     unsigned ClassExtensionMemoryModel = getOwnershipRule(Attributes);
441     unsigned PrimaryClassMemoryModel = getOwnershipRule(PIkind);
442     if (PrimaryClassMemoryModel && ClassExtensionMemoryModel &&
443         (PrimaryClassMemoryModel != ClassExtensionMemoryModel)) {
444       Diag(AtLoc, diag::warn_property_attr_mismatch);
445       Diag(PIDecl->getLocation(), diag::note_property_declare);
446     }
447     else if (getLangOpts().ObjCAutoRefCount) {
448       QualType PrimaryPropertyQT =
449         Context.getCanonicalType(PIDecl->getType()).getUnqualifiedType();
450       if (isa<ObjCObjectPointerType>(PrimaryPropertyQT)) {
451         bool PropertyIsWeak = ((PIkind & ObjCPropertyDecl::OBJC_PR_weak) != 0);
452         Qualifiers::ObjCLifetime PrimaryPropertyLifeTime =
453           PrimaryPropertyQT.getObjCLifetime();
454         if (PrimaryPropertyLifeTime == Qualifiers::OCL_None &&
455             (Attributes & ObjCDeclSpec::DQ_PR_weak) &&
456             !PropertyIsWeak) {
457               Diag(AtLoc, diag::warn_property_implicitly_mismatched);
458               Diag(PIDecl->getLocation(), diag::note_property_declare);
459             }
460         }
461     }
462 
463     DeclContext *DC = cast<DeclContext>(CCPrimary);
464     if (!ObjCPropertyDecl::findPropertyDecl(DC,
465                                  PIDecl->getDeclName().getAsIdentifierInfo())) {
466       // Protocol is not in the primary class. Must build one for it.
467       ObjCDeclSpec ProtocolPropertyODS;
468       // FIXME. Assuming that ObjCDeclSpec::ObjCPropertyAttributeKind
469       // and ObjCPropertyDecl::PropertyAttributeKind have identical
470       // values.  Should consolidate both into one enum type.
471       ProtocolPropertyODS.
472       setPropertyAttributes((ObjCDeclSpec::ObjCPropertyAttributeKind)
473                             PIkind);
474       // Must re-establish the context from class extension to primary
475       // class context.
476       ContextRAII SavedContext(*this, CCPrimary);
477 
478       Decl *ProtocolPtrTy =
479         ActOnProperty(S, AtLoc, LParenLoc, FD, ProtocolPropertyODS,
480                       PIDecl->getGetterName(),
481                       PIDecl->getSetterName(),
482                       isOverridingProperty,
483                       MethodImplKind,
484                       /* lexicalDC = */ CDecl);
485       PIDecl = cast<ObjCPropertyDecl>(ProtocolPtrTy);
486     }
487     PIDecl->makeitReadWriteAttribute();
488     if (Attributes & ObjCDeclSpec::DQ_PR_retain)
489       PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
490     if (Attributes & ObjCDeclSpec::DQ_PR_strong)
491       PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong);
492     if (Attributes & ObjCDeclSpec::DQ_PR_copy)
493       PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
494     PIDecl->setSetterName(SetterSel);
495   } else {
496     // Tailor the diagnostics for the common case where a readwrite
497     // property is declared both in the @interface and the continuation.
498     // This is a common error where the user often intended the original
499     // declaration to be readonly.
500     unsigned diag =
501       (Attributes & ObjCDeclSpec::DQ_PR_readwrite) &&
502       (PIkind & ObjCPropertyDecl::OBJC_PR_readwrite)
503       ? diag::err_use_continuation_class_redeclaration_readwrite
504       : diag::err_use_continuation_class;
505     Diag(AtLoc, diag)
506       << CCPrimary->getDeclName();
507     Diag(PIDecl->getLocation(), diag::note_property_declare);
508     return 0;
509   }
510   *isOverridingProperty = true;
511   // Make sure setter decl is synthesized, and added to primary class's list.
512   ProcessPropertyDecl(PIDecl, CCPrimary, PDecl, CDecl);
513   PDecl->setGetterMethodDecl(PIDecl->getGetterMethodDecl());
514   PDecl->setSetterMethodDecl(PIDecl->getSetterMethodDecl());
515   if (ASTMutationListener *L = Context.getASTMutationListener())
516     L->AddedObjCPropertyInClassExtension(PDecl, PIDecl, CDecl);
517   return PDecl;
518 }
519 
520 ObjCPropertyDecl *Sema::CreatePropertyDecl(Scope *S,
521                                            ObjCContainerDecl *CDecl,
522                                            SourceLocation AtLoc,
523                                            SourceLocation LParenLoc,
524                                            FieldDeclarator &FD,
525                                            Selector GetterSel,
526                                            Selector SetterSel,
527                                            const bool isAssign,
528                                            const bool isReadWrite,
529                                            const unsigned Attributes,
530                                            const unsigned AttributesAsWritten,
531                                            TypeSourceInfo *TInfo,
532                                            tok::ObjCKeywordKind MethodImplKind,
533                                            DeclContext *lexicalDC){
534   IdentifierInfo *PropertyId = FD.D.getIdentifier();
535   QualType T = TInfo->getType();
536 
537   // Issue a warning if property is 'assign' as default and its object, which is
538   // gc'able conforms to NSCopying protocol
539   if (getLangOpts().getGC() != LangOptions::NonGC &&
540       isAssign && !(Attributes & ObjCDeclSpec::DQ_PR_assign))
541     if (const ObjCObjectPointerType *ObjPtrTy =
542           T->getAs<ObjCObjectPointerType>()) {
543       ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
544       if (IDecl)
545         if (ObjCProtocolDecl* PNSCopying =
546             LookupProtocol(&Context.Idents.get("NSCopying"), AtLoc))
547           if (IDecl->ClassImplementsProtocol(PNSCopying, true))
548             Diag(AtLoc, diag::warn_implements_nscopying) << PropertyId;
549     }
550 
551   if (T->isObjCObjectType()) {
552     SourceLocation StarLoc = TInfo->getTypeLoc().getLocEnd();
553     StarLoc = PP.getLocForEndOfToken(StarLoc);
554     Diag(FD.D.getIdentifierLoc(), diag::err_statically_allocated_object)
555       << FixItHint::CreateInsertion(StarLoc, "*");
556     T = Context.getObjCObjectPointerType(T);
557     SourceLocation TLoc = TInfo->getTypeLoc().getLocStart();
558     TInfo = Context.getTrivialTypeSourceInfo(T, TLoc);
559   }
560 
561   DeclContext *DC = cast<DeclContext>(CDecl);
562   ObjCPropertyDecl *PDecl = ObjCPropertyDecl::Create(Context, DC,
563                                                      FD.D.getIdentifierLoc(),
564                                                      PropertyId, AtLoc, LParenLoc, TInfo);
565 
566   if (ObjCPropertyDecl *prevDecl =
567         ObjCPropertyDecl::findPropertyDecl(DC, PropertyId)) {
568     Diag(PDecl->getLocation(), diag::err_duplicate_property);
569     Diag(prevDecl->getLocation(), diag::note_property_declare);
570     PDecl->setInvalidDecl();
571   }
572   else {
573     DC->addDecl(PDecl);
574     if (lexicalDC)
575       PDecl->setLexicalDeclContext(lexicalDC);
576   }
577 
578   if (T->isArrayType() || T->isFunctionType()) {
579     Diag(AtLoc, diag::err_property_type) << T;
580     PDecl->setInvalidDecl();
581   }
582 
583   ProcessDeclAttributes(S, PDecl, FD.D);
584 
585   // Regardless of setter/getter attribute, we save the default getter/setter
586   // selector names in anticipation of declaration of setter/getter methods.
587   PDecl->setGetterName(GetterSel);
588   PDecl->setSetterName(SetterSel);
589   PDecl->setPropertyAttributesAsWritten(
590                           makePropertyAttributesAsWritten(AttributesAsWritten));
591 
592   if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
593     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly);
594 
595   if (Attributes & ObjCDeclSpec::DQ_PR_getter)
596     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_getter);
597 
598   if (Attributes & ObjCDeclSpec::DQ_PR_setter)
599     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_setter);
600 
601   if (isReadWrite)
602     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite);
603 
604   if (Attributes & ObjCDeclSpec::DQ_PR_retain)
605     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
606 
607   if (Attributes & ObjCDeclSpec::DQ_PR_strong)
608     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong);
609 
610   if (Attributes & ObjCDeclSpec::DQ_PR_weak)
611     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_weak);
612 
613   if (Attributes & ObjCDeclSpec::DQ_PR_copy)
614     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
615 
616   if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained)
617     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_unsafe_unretained);
618 
619   if (isAssign)
620     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign);
621 
622   // In the semantic attributes, one of nonatomic or atomic is always set.
623   if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)
624     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nonatomic);
625   else
626     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_atomic);
627 
628   // 'unsafe_unretained' is alias for 'assign'.
629   if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained)
630     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign);
631   if (isAssign)
632     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_unsafe_unretained);
633 
634   if (MethodImplKind == tok::objc_required)
635     PDecl->setPropertyImplementation(ObjCPropertyDecl::Required);
636   else if (MethodImplKind == tok::objc_optional)
637     PDecl->setPropertyImplementation(ObjCPropertyDecl::Optional);
638 
639   return PDecl;
640 }
641 
642 static void checkARCPropertyImpl(Sema &S, SourceLocation propertyImplLoc,
643                                  ObjCPropertyDecl *property,
644                                  ObjCIvarDecl *ivar) {
645   if (property->isInvalidDecl() || ivar->isInvalidDecl()) return;
646 
647   QualType ivarType = ivar->getType();
648   Qualifiers::ObjCLifetime ivarLifetime = ivarType.getObjCLifetime();
649 
650   // The lifetime implied by the property's attributes.
651   Qualifiers::ObjCLifetime propertyLifetime =
652     getImpliedARCOwnership(property->getPropertyAttributes(),
653                            property->getType());
654 
655   // We're fine if they match.
656   if (propertyLifetime == ivarLifetime) return;
657 
658   // These aren't valid lifetimes for object ivars;  don't diagnose twice.
659   if (ivarLifetime == Qualifiers::OCL_None ||
660       ivarLifetime == Qualifiers::OCL_Autoreleasing)
661     return;
662 
663   // If the ivar is private, and it's implicitly __unsafe_unretained
664   // becaues of its type, then pretend it was actually implicitly
665   // __strong.  This is only sound because we're processing the
666   // property implementation before parsing any method bodies.
667   if (ivarLifetime == Qualifiers::OCL_ExplicitNone &&
668       propertyLifetime == Qualifiers::OCL_Strong &&
669       ivar->getAccessControl() == ObjCIvarDecl::Private) {
670     SplitQualType split = ivarType.split();
671     if (split.Quals.hasObjCLifetime()) {
672       assert(ivarType->isObjCARCImplicitlyUnretainedType());
673       split.Quals.setObjCLifetime(Qualifiers::OCL_Strong);
674       ivarType = S.Context.getQualifiedType(split);
675       ivar->setType(ivarType);
676       return;
677     }
678   }
679 
680   switch (propertyLifetime) {
681   case Qualifiers::OCL_Strong:
682     S.Diag(ivar->getLocation(), diag::err_arc_strong_property_ownership)
683       << property->getDeclName()
684       << ivar->getDeclName()
685       << ivarLifetime;
686     break;
687 
688   case Qualifiers::OCL_Weak:
689     S.Diag(ivar->getLocation(), diag::error_weak_property)
690       << property->getDeclName()
691       << ivar->getDeclName();
692     break;
693 
694   case Qualifiers::OCL_ExplicitNone:
695     S.Diag(ivar->getLocation(), diag::err_arc_assign_property_ownership)
696       << property->getDeclName()
697       << ivar->getDeclName()
698       << ((property->getPropertyAttributesAsWritten()
699            & ObjCPropertyDecl::OBJC_PR_assign) != 0);
700     break;
701 
702   case Qualifiers::OCL_Autoreleasing:
703     llvm_unreachable("properties cannot be autoreleasing");
704 
705   case Qualifiers::OCL_None:
706     // Any other property should be ignored.
707     return;
708   }
709 
710   S.Diag(property->getLocation(), diag::note_property_declare);
711   if (propertyImplLoc.isValid())
712     S.Diag(propertyImplLoc, diag::note_property_synthesize);
713 }
714 
715 /// setImpliedPropertyAttributeForReadOnlyProperty -
716 /// This routine evaludates life-time attributes for a 'readonly'
717 /// property with no known lifetime of its own, using backing
718 /// 'ivar's attribute, if any. If no backing 'ivar', property's
719 /// life-time is assumed 'strong'.
720 static void setImpliedPropertyAttributeForReadOnlyProperty(
721               ObjCPropertyDecl *property, ObjCIvarDecl *ivar) {
722   Qualifiers::ObjCLifetime propertyLifetime =
723     getImpliedARCOwnership(property->getPropertyAttributes(),
724                            property->getType());
725   if (propertyLifetime != Qualifiers::OCL_None)
726     return;
727 
728   if (!ivar) {
729     // if no backing ivar, make property 'strong'.
730     property->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong);
731     return;
732   }
733   // property assumes owenership of backing ivar.
734   QualType ivarType = ivar->getType();
735   Qualifiers::ObjCLifetime ivarLifetime = ivarType.getObjCLifetime();
736   if (ivarLifetime == Qualifiers::OCL_Strong)
737     property->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong);
738   else if (ivarLifetime == Qualifiers::OCL_Weak)
739     property->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_weak);
740   return;
741 }
742 
743 /// DiagnosePropertyMismatchDeclInProtocols - diagnose properties declared
744 /// in inherited protocols with mismatched types. Since any of them can
745 /// be candidate for synthesis.
746 static void
747 DiagnosePropertyMismatchDeclInProtocols(Sema &S, SourceLocation AtLoc,
748                                         ObjCInterfaceDecl *ClassDecl,
749                                         ObjCPropertyDecl *Property) {
750   ObjCInterfaceDecl::ProtocolPropertyMap PropMap;
751   for (ObjCInterfaceDecl::all_protocol_iterator
752        PI = ClassDecl->all_referenced_protocol_begin(),
753        E = ClassDecl->all_referenced_protocol_end(); PI != E; ++PI) {
754     if (const ObjCProtocolDecl *PDecl = (*PI)->getDefinition())
755       PDecl->collectInheritedProtocolProperties(Property, PropMap);
756   }
757   if (ObjCInterfaceDecl *SDecl = ClassDecl->getSuperClass())
758     while (SDecl) {
759       for (ObjCInterfaceDecl::all_protocol_iterator
760            PI = SDecl->all_referenced_protocol_begin(),
761            E = SDecl->all_referenced_protocol_end(); PI != E; ++PI) {
762         if (const ObjCProtocolDecl *PDecl = (*PI)->getDefinition())
763           PDecl->collectInheritedProtocolProperties(Property, PropMap);
764       }
765       SDecl = SDecl->getSuperClass();
766     }
767 
768   if (PropMap.empty())
769     return;
770 
771   QualType RHSType = S.Context.getCanonicalType(Property->getType());
772   bool FirsTime = true;
773   for (ObjCInterfaceDecl::ProtocolPropertyMap::iterator
774        I = PropMap.begin(), E = PropMap.end(); I != E; I++) {
775     ObjCPropertyDecl *Prop = I->second;
776     QualType LHSType = S.Context.getCanonicalType(Prop->getType());
777     if (!S.Context.propertyTypesAreCompatible(LHSType, RHSType)) {
778       bool IncompatibleObjC = false;
779       QualType ConvertedType;
780       if (!S.isObjCPointerConversion(RHSType, LHSType, ConvertedType, IncompatibleObjC)
781           || IncompatibleObjC) {
782         if (FirsTime) {
783           S.Diag(Property->getLocation(), diag::warn_protocol_property_mismatch)
784             << Property->getType();
785           FirsTime = false;
786         }
787         S.Diag(Prop->getLocation(), diag::note_protocol_property_declare)
788           << Prop->getType();
789       }
790     }
791   }
792   if (!FirsTime && AtLoc.isValid())
793     S.Diag(AtLoc, diag::note_property_synthesize);
794 }
795 
796 /// ActOnPropertyImplDecl - This routine performs semantic checks and
797 /// builds the AST node for a property implementation declaration; declared
798 /// as \@synthesize or \@dynamic.
799 ///
800 Decl *Sema::ActOnPropertyImplDecl(Scope *S,
801                                   SourceLocation AtLoc,
802                                   SourceLocation PropertyLoc,
803                                   bool Synthesize,
804                                   IdentifierInfo *PropertyId,
805                                   IdentifierInfo *PropertyIvar,
806                                   SourceLocation PropertyIvarLoc) {
807   ObjCContainerDecl *ClassImpDecl =
808     dyn_cast<ObjCContainerDecl>(CurContext);
809   // Make sure we have a context for the property implementation declaration.
810   if (!ClassImpDecl) {
811     Diag(AtLoc, diag::error_missing_property_context);
812     return 0;
813   }
814   if (PropertyIvarLoc.isInvalid())
815     PropertyIvarLoc = PropertyLoc;
816   SourceLocation PropertyDiagLoc = PropertyLoc;
817   if (PropertyDiagLoc.isInvalid())
818     PropertyDiagLoc = ClassImpDecl->getLocStart();
819   ObjCPropertyDecl *property = 0;
820   ObjCInterfaceDecl* IDecl = 0;
821   // Find the class or category class where this property must have
822   // a declaration.
823   ObjCImplementationDecl *IC = 0;
824   ObjCCategoryImplDecl* CatImplClass = 0;
825   if ((IC = dyn_cast<ObjCImplementationDecl>(ClassImpDecl))) {
826     IDecl = IC->getClassInterface();
827     // We always synthesize an interface for an implementation
828     // without an interface decl. So, IDecl is always non-zero.
829     assert(IDecl &&
830            "ActOnPropertyImplDecl - @implementation without @interface");
831 
832     // Look for this property declaration in the @implementation's @interface
833     property = IDecl->FindPropertyDeclaration(PropertyId);
834     if (!property) {
835       Diag(PropertyLoc, diag::error_bad_property_decl) << IDecl->getDeclName();
836       return 0;
837     }
838     unsigned PIkind = property->getPropertyAttributesAsWritten();
839     if ((PIkind & (ObjCPropertyDecl::OBJC_PR_atomic |
840                    ObjCPropertyDecl::OBJC_PR_nonatomic) ) == 0) {
841       if (AtLoc.isValid())
842         Diag(AtLoc, diag::warn_implicit_atomic_property);
843       else
844         Diag(IC->getLocation(), diag::warn_auto_implicit_atomic_property);
845       Diag(property->getLocation(), diag::note_property_declare);
846     }
847 
848     if (const ObjCCategoryDecl *CD =
849         dyn_cast<ObjCCategoryDecl>(property->getDeclContext())) {
850       if (!CD->IsClassExtension()) {
851         Diag(PropertyLoc, diag::error_category_property) << CD->getDeclName();
852         Diag(property->getLocation(), diag::note_property_declare);
853         return 0;
854       }
855     }
856     if (Synthesize&&
857         (PIkind & ObjCPropertyDecl::OBJC_PR_readonly) &&
858         property->hasAttr<IBOutletAttr>() &&
859         !AtLoc.isValid()) {
860       bool ReadWriteProperty = false;
861       // Search into the class extensions and see if 'readonly property is
862       // redeclared 'readwrite', then no warning is to be issued.
863       for (ObjCInterfaceDecl::known_extensions_iterator
864             Ext = IDecl->known_extensions_begin(),
865             ExtEnd = IDecl->known_extensions_end(); Ext != ExtEnd; ++Ext) {
866         DeclContext::lookup_result R = Ext->lookup(property->getDeclName());
867         if (!R.empty())
868           if (ObjCPropertyDecl *ExtProp = dyn_cast<ObjCPropertyDecl>(R[0])) {
869             PIkind = ExtProp->getPropertyAttributesAsWritten();
870             if (PIkind & ObjCPropertyDecl::OBJC_PR_readwrite) {
871               ReadWriteProperty = true;
872               break;
873             }
874           }
875       }
876 
877       if (!ReadWriteProperty) {
878         Diag(property->getLocation(), diag::warn_auto_readonly_iboutlet_property)
879             << property;
880         SourceLocation readonlyLoc;
881         if (LocPropertyAttribute(Context, "readonly",
882                                  property->getLParenLoc(), readonlyLoc)) {
883           SourceLocation endLoc =
884             readonlyLoc.getLocWithOffset(strlen("readonly")-1);
885           SourceRange ReadonlySourceRange(readonlyLoc, endLoc);
886           Diag(property->getLocation(),
887                diag::note_auto_readonly_iboutlet_fixup_suggest) <<
888           FixItHint::CreateReplacement(ReadonlySourceRange, "readwrite");
889         }
890       }
891     }
892     if (Synthesize && isa<ObjCProtocolDecl>(property->getDeclContext()))
893       DiagnosePropertyMismatchDeclInProtocols(*this, AtLoc, IDecl, property);
894 
895   } else if ((CatImplClass = dyn_cast<ObjCCategoryImplDecl>(ClassImpDecl))) {
896     if (Synthesize) {
897       Diag(AtLoc, diag::error_synthesize_category_decl);
898       return 0;
899     }
900     IDecl = CatImplClass->getClassInterface();
901     if (!IDecl) {
902       Diag(AtLoc, diag::error_missing_property_interface);
903       return 0;
904     }
905     ObjCCategoryDecl *Category =
906     IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier());
907 
908     // If category for this implementation not found, it is an error which
909     // has already been reported eralier.
910     if (!Category)
911       return 0;
912     // Look for this property declaration in @implementation's category
913     property = Category->FindPropertyDeclaration(PropertyId);
914     if (!property) {
915       Diag(PropertyLoc, diag::error_bad_category_property_decl)
916       << Category->getDeclName();
917       return 0;
918     }
919   } else {
920     Diag(AtLoc, diag::error_bad_property_context);
921     return 0;
922   }
923   ObjCIvarDecl *Ivar = 0;
924   bool CompleteTypeErr = false;
925   bool compat = true;
926   // Check that we have a valid, previously declared ivar for @synthesize
927   if (Synthesize) {
928     // @synthesize
929     if (!PropertyIvar)
930       PropertyIvar = PropertyId;
931     // Check that this is a previously declared 'ivar' in 'IDecl' interface
932     ObjCInterfaceDecl *ClassDeclared;
933     Ivar = IDecl->lookupInstanceVariable(PropertyIvar, ClassDeclared);
934     QualType PropType = property->getType();
935     QualType PropertyIvarType = PropType.getNonReferenceType();
936 
937     if (RequireCompleteType(PropertyDiagLoc, PropertyIvarType,
938                             diag::err_incomplete_synthesized_property,
939                             property->getDeclName())) {
940       Diag(property->getLocation(), diag::note_property_declare);
941       CompleteTypeErr = true;
942     }
943 
944     if (getLangOpts().ObjCAutoRefCount &&
945         (property->getPropertyAttributesAsWritten() &
946          ObjCPropertyDecl::OBJC_PR_readonly) &&
947         PropertyIvarType->isObjCRetainableType()) {
948       setImpliedPropertyAttributeForReadOnlyProperty(property, Ivar);
949     }
950 
951     ObjCPropertyDecl::PropertyAttributeKind kind
952       = property->getPropertyAttributes();
953 
954     // Add GC __weak to the ivar type if the property is weak.
955     if ((kind & ObjCPropertyDecl::OBJC_PR_weak) &&
956         getLangOpts().getGC() != LangOptions::NonGC) {
957       assert(!getLangOpts().ObjCAutoRefCount);
958       if (PropertyIvarType.isObjCGCStrong()) {
959         Diag(PropertyDiagLoc, diag::err_gc_weak_property_strong_type);
960         Diag(property->getLocation(), diag::note_property_declare);
961       } else {
962         PropertyIvarType =
963           Context.getObjCGCQualType(PropertyIvarType, Qualifiers::Weak);
964       }
965     }
966     if (AtLoc.isInvalid()) {
967       // Check when default synthesizing a property that there is
968       // an ivar matching property name and issue warning; since this
969       // is the most common case of not using an ivar used for backing
970       // property in non-default synthesis case.
971       ObjCInterfaceDecl *ClassDeclared=0;
972       ObjCIvarDecl *originalIvar =
973       IDecl->lookupInstanceVariable(property->getIdentifier(),
974                                     ClassDeclared);
975       if (originalIvar) {
976         Diag(PropertyDiagLoc,
977              diag::warn_autosynthesis_property_ivar_match)
978         << PropertyId << (Ivar == 0) << PropertyIvar
979         << originalIvar->getIdentifier();
980         Diag(property->getLocation(), diag::note_property_declare);
981         Diag(originalIvar->getLocation(), diag::note_ivar_decl);
982       }
983     }
984 
985     if (!Ivar) {
986       // In ARC, give the ivar a lifetime qualifier based on the
987       // property attributes.
988       if (getLangOpts().ObjCAutoRefCount &&
989           !PropertyIvarType.getObjCLifetime() &&
990           PropertyIvarType->isObjCRetainableType()) {
991 
992         // It's an error if we have to do this and the user didn't
993         // explicitly write an ownership attribute on the property.
994         if (!property->hasWrittenStorageAttribute() &&
995             !(kind & ObjCPropertyDecl::OBJC_PR_strong)) {
996           Diag(PropertyDiagLoc,
997                diag::err_arc_objc_property_default_assign_on_object);
998           Diag(property->getLocation(), diag::note_property_declare);
999         } else {
1000           Qualifiers::ObjCLifetime lifetime =
1001             getImpliedARCOwnership(kind, PropertyIvarType);
1002           assert(lifetime && "no lifetime for property?");
1003           if (lifetime == Qualifiers::OCL_Weak) {
1004             bool err = false;
1005             if (const ObjCObjectPointerType *ObjT =
1006                 PropertyIvarType->getAs<ObjCObjectPointerType>()) {
1007               const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl();
1008               if (ObjI && ObjI->isArcWeakrefUnavailable()) {
1009                 Diag(property->getLocation(),
1010                      diag::err_arc_weak_unavailable_property) << PropertyIvarType;
1011                 Diag(ClassImpDecl->getLocation(), diag::note_implemented_by_class)
1012                   << ClassImpDecl->getName();
1013                 err = true;
1014               }
1015             }
1016             if (!err && !getLangOpts().ObjCARCWeak) {
1017               Diag(PropertyDiagLoc, diag::err_arc_weak_no_runtime);
1018               Diag(property->getLocation(), diag::note_property_declare);
1019             }
1020           }
1021 
1022           Qualifiers qs;
1023           qs.addObjCLifetime(lifetime);
1024           PropertyIvarType = Context.getQualifiedType(PropertyIvarType, qs);
1025         }
1026       }
1027 
1028       if (kind & ObjCPropertyDecl::OBJC_PR_weak &&
1029           !getLangOpts().ObjCAutoRefCount &&
1030           getLangOpts().getGC() == LangOptions::NonGC) {
1031         Diag(PropertyDiagLoc, diag::error_synthesize_weak_non_arc_or_gc);
1032         Diag(property->getLocation(), diag::note_property_declare);
1033       }
1034 
1035       Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
1036                                   PropertyIvarLoc,PropertyIvarLoc, PropertyIvar,
1037                                   PropertyIvarType, /*Dinfo=*/0,
1038                                   ObjCIvarDecl::Private,
1039                                   (Expr *)0, true);
1040       if (RequireNonAbstractType(PropertyIvarLoc,
1041                                  PropertyIvarType,
1042                                  diag::err_abstract_type_in_decl,
1043                                  AbstractSynthesizedIvarType)) {
1044         Diag(property->getLocation(), diag::note_property_declare);
1045         Ivar->setInvalidDecl();
1046       } else if (CompleteTypeErr)
1047           Ivar->setInvalidDecl();
1048       ClassImpDecl->addDecl(Ivar);
1049       IDecl->makeDeclVisibleInContext(Ivar);
1050 
1051       if (getLangOpts().ObjCRuntime.isFragile())
1052         Diag(PropertyDiagLoc, diag::error_missing_property_ivar_decl)
1053             << PropertyId;
1054       // Note! I deliberately want it to fall thru so, we have a
1055       // a property implementation and to avoid future warnings.
1056     } else if (getLangOpts().ObjCRuntime.isNonFragile() &&
1057                !declaresSameEntity(ClassDeclared, IDecl)) {
1058       Diag(PropertyDiagLoc, diag::error_ivar_in_superclass_use)
1059       << property->getDeclName() << Ivar->getDeclName()
1060       << ClassDeclared->getDeclName();
1061       Diag(Ivar->getLocation(), diag::note_previous_access_declaration)
1062       << Ivar << Ivar->getName();
1063       // Note! I deliberately want it to fall thru so more errors are caught.
1064     }
1065     property->setPropertyIvarDecl(Ivar);
1066 
1067     QualType IvarType = Context.getCanonicalType(Ivar->getType());
1068 
1069     // Check that type of property and its ivar are type compatible.
1070     if (!Context.hasSameType(PropertyIvarType, IvarType)) {
1071       if (isa<ObjCObjectPointerType>(PropertyIvarType)
1072           && isa<ObjCObjectPointerType>(IvarType))
1073         compat =
1074           Context.canAssignObjCInterfaces(
1075                                   PropertyIvarType->getAs<ObjCObjectPointerType>(),
1076                                   IvarType->getAs<ObjCObjectPointerType>());
1077       else {
1078         compat = (CheckAssignmentConstraints(PropertyIvarLoc, PropertyIvarType,
1079                                              IvarType)
1080                     == Compatible);
1081       }
1082       if (!compat) {
1083         Diag(PropertyDiagLoc, diag::error_property_ivar_type)
1084           << property->getDeclName() << PropType
1085           << Ivar->getDeclName() << IvarType;
1086         Diag(Ivar->getLocation(), diag::note_ivar_decl);
1087         // Note! I deliberately want it to fall thru so, we have a
1088         // a property implementation and to avoid future warnings.
1089       }
1090       else {
1091         // FIXME! Rules for properties are somewhat different that those
1092         // for assignments. Use a new routine to consolidate all cases;
1093         // specifically for property redeclarations as well as for ivars.
1094         QualType lhsType =Context.getCanonicalType(PropertyIvarType).getUnqualifiedType();
1095         QualType rhsType =Context.getCanonicalType(IvarType).getUnqualifiedType();
1096         if (lhsType != rhsType &&
1097             lhsType->isArithmeticType()) {
1098           Diag(PropertyDiagLoc, diag::error_property_ivar_type)
1099             << property->getDeclName() << PropType
1100             << Ivar->getDeclName() << IvarType;
1101           Diag(Ivar->getLocation(), diag::note_ivar_decl);
1102           // Fall thru - see previous comment
1103         }
1104       }
1105       // __weak is explicit. So it works on Canonical type.
1106       if ((PropType.isObjCGCWeak() && !IvarType.isObjCGCWeak() &&
1107            getLangOpts().getGC() != LangOptions::NonGC)) {
1108         Diag(PropertyDiagLoc, diag::error_weak_property)
1109         << property->getDeclName() << Ivar->getDeclName();
1110         Diag(Ivar->getLocation(), diag::note_ivar_decl);
1111         // Fall thru - see previous comment
1112       }
1113       // Fall thru - see previous comment
1114       if ((property->getType()->isObjCObjectPointerType() ||
1115            PropType.isObjCGCStrong()) && IvarType.isObjCGCWeak() &&
1116           getLangOpts().getGC() != LangOptions::NonGC) {
1117         Diag(PropertyDiagLoc, diag::error_strong_property)
1118         << property->getDeclName() << Ivar->getDeclName();
1119         // Fall thru - see previous comment
1120       }
1121     }
1122     if (getLangOpts().ObjCAutoRefCount)
1123       checkARCPropertyImpl(*this, PropertyLoc, property, Ivar);
1124   } else if (PropertyIvar)
1125     // @dynamic
1126     Diag(PropertyDiagLoc, diag::error_dynamic_property_ivar_decl);
1127 
1128   assert (property && "ActOnPropertyImplDecl - property declaration missing");
1129   ObjCPropertyImplDecl *PIDecl =
1130   ObjCPropertyImplDecl::Create(Context, CurContext, AtLoc, PropertyLoc,
1131                                property,
1132                                (Synthesize ?
1133                                 ObjCPropertyImplDecl::Synthesize
1134                                 : ObjCPropertyImplDecl::Dynamic),
1135                                Ivar, PropertyIvarLoc);
1136 
1137   if (CompleteTypeErr || !compat)
1138     PIDecl->setInvalidDecl();
1139 
1140   if (ObjCMethodDecl *getterMethod = property->getGetterMethodDecl()) {
1141     getterMethod->createImplicitParams(Context, IDecl);
1142     if (getLangOpts().CPlusPlus && Synthesize && !CompleteTypeErr &&
1143         Ivar->getType()->isRecordType()) {
1144       // For Objective-C++, need to synthesize the AST for the IVAR object to be
1145       // returned by the getter as it must conform to C++'s copy-return rules.
1146       // FIXME. Eventually we want to do this for Objective-C as well.
1147       SynthesizedFunctionScope Scope(*this, getterMethod);
1148       ImplicitParamDecl *SelfDecl = getterMethod->getSelfDecl();
1149       DeclRefExpr *SelfExpr =
1150         new (Context) DeclRefExpr(SelfDecl, false, SelfDecl->getType(),
1151                                   VK_LValue, PropertyDiagLoc);
1152       MarkDeclRefReferenced(SelfExpr);
1153       Expr *LoadSelfExpr =
1154         ImplicitCastExpr::Create(Context, SelfDecl->getType(),
1155                                  CK_LValueToRValue, SelfExpr, 0, VK_RValue);
1156       Expr *IvarRefExpr =
1157         new (Context) ObjCIvarRefExpr(Ivar, Ivar->getType(), PropertyDiagLoc,
1158                                       Ivar->getLocation(),
1159                                       LoadSelfExpr, true, true);
1160       ExprResult Res =
1161         PerformCopyInitialization(InitializedEntity::InitializeResult(
1162                                     PropertyDiagLoc,
1163                                     getterMethod->getResultType(),
1164                                     /*NRVO=*/false),
1165                                   PropertyDiagLoc,
1166                                   Owned(IvarRefExpr));
1167       if (!Res.isInvalid()) {
1168         Expr *ResExpr = Res.takeAs<Expr>();
1169         if (ResExpr)
1170           ResExpr = MaybeCreateExprWithCleanups(ResExpr);
1171         PIDecl->setGetterCXXConstructor(ResExpr);
1172       }
1173     }
1174     if (property->hasAttr<NSReturnsNotRetainedAttr>() &&
1175         !getterMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
1176       Diag(getterMethod->getLocation(),
1177            diag::warn_property_getter_owning_mismatch);
1178       Diag(property->getLocation(), diag::note_property_declare);
1179     }
1180     if (getLangOpts().ObjCAutoRefCount && Synthesize)
1181       switch (getterMethod->getMethodFamily()) {
1182         case OMF_retain:
1183         case OMF_retainCount:
1184         case OMF_release:
1185         case OMF_autorelease:
1186           Diag(getterMethod->getLocation(), diag::err_arc_illegal_method_def)
1187             << 1 << getterMethod->getSelector();
1188           break;
1189         default:
1190           break;
1191       }
1192   }
1193   if (ObjCMethodDecl *setterMethod = property->getSetterMethodDecl()) {
1194     setterMethod->createImplicitParams(Context, IDecl);
1195     if (getLangOpts().CPlusPlus && Synthesize && !CompleteTypeErr &&
1196         Ivar->getType()->isRecordType()) {
1197       // FIXME. Eventually we want to do this for Objective-C as well.
1198       SynthesizedFunctionScope Scope(*this, setterMethod);
1199       ImplicitParamDecl *SelfDecl = setterMethod->getSelfDecl();
1200       DeclRefExpr *SelfExpr =
1201         new (Context) DeclRefExpr(SelfDecl, false, SelfDecl->getType(),
1202                                   VK_LValue, PropertyDiagLoc);
1203       MarkDeclRefReferenced(SelfExpr);
1204       Expr *LoadSelfExpr =
1205         ImplicitCastExpr::Create(Context, SelfDecl->getType(),
1206                                  CK_LValueToRValue, SelfExpr, 0, VK_RValue);
1207       Expr *lhs =
1208         new (Context) ObjCIvarRefExpr(Ivar, Ivar->getType(), PropertyDiagLoc,
1209                                       Ivar->getLocation(),
1210                                       LoadSelfExpr, true, true);
1211       ObjCMethodDecl::param_iterator P = setterMethod->param_begin();
1212       ParmVarDecl *Param = (*P);
1213       QualType T = Param->getType().getNonReferenceType();
1214       DeclRefExpr *rhs = new (Context) DeclRefExpr(Param, false, T,
1215                                                    VK_LValue, PropertyDiagLoc);
1216       MarkDeclRefReferenced(rhs);
1217       ExprResult Res = BuildBinOp(S, PropertyDiagLoc,
1218                                   BO_Assign, lhs, rhs);
1219       if (property->getPropertyAttributes() &
1220           ObjCPropertyDecl::OBJC_PR_atomic) {
1221         Expr *callExpr = Res.takeAs<Expr>();
1222         if (const CXXOperatorCallExpr *CXXCE =
1223               dyn_cast_or_null<CXXOperatorCallExpr>(callExpr))
1224           if (const FunctionDecl *FuncDecl = CXXCE->getDirectCallee())
1225             if (!FuncDecl->isTrivial())
1226               if (property->getType()->isReferenceType()) {
1227                 Diag(PropertyDiagLoc,
1228                      diag::err_atomic_property_nontrivial_assign_op)
1229                     << property->getType();
1230                 Diag(FuncDecl->getLocStart(),
1231                      diag::note_callee_decl) << FuncDecl;
1232               }
1233       }
1234       PIDecl->setSetterCXXAssignment(Res.takeAs<Expr>());
1235     }
1236   }
1237 
1238   if (IC) {
1239     if (Synthesize)
1240       if (ObjCPropertyImplDecl *PPIDecl =
1241           IC->FindPropertyImplIvarDecl(PropertyIvar)) {
1242         Diag(PropertyLoc, diag::error_duplicate_ivar_use)
1243         << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
1244         << PropertyIvar;
1245         Diag(PPIDecl->getLocation(), diag::note_previous_use);
1246       }
1247 
1248     if (ObjCPropertyImplDecl *PPIDecl
1249         = IC->FindPropertyImplDecl(PropertyId)) {
1250       Diag(PropertyLoc, diag::error_property_implemented) << PropertyId;
1251       Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
1252       return 0;
1253     }
1254     IC->addPropertyImplementation(PIDecl);
1255     if (getLangOpts().ObjCDefaultSynthProperties &&
1256         getLangOpts().ObjCRuntime.isNonFragile() &&
1257         !IDecl->isObjCRequiresPropertyDefs()) {
1258       // Diagnose if an ivar was lazily synthesdized due to a previous
1259       // use and if 1) property is @dynamic or 2) property is synthesized
1260       // but it requires an ivar of different name.
1261       ObjCInterfaceDecl *ClassDeclared=0;
1262       ObjCIvarDecl *Ivar = 0;
1263       if (!Synthesize)
1264         Ivar = IDecl->lookupInstanceVariable(PropertyId, ClassDeclared);
1265       else {
1266         if (PropertyIvar && PropertyIvar != PropertyId)
1267           Ivar = IDecl->lookupInstanceVariable(PropertyId, ClassDeclared);
1268       }
1269       // Issue diagnostics only if Ivar belongs to current class.
1270       if (Ivar && Ivar->getSynthesize() &&
1271           declaresSameEntity(IC->getClassInterface(), ClassDeclared)) {
1272         Diag(Ivar->getLocation(), diag::err_undeclared_var_use)
1273         << PropertyId;
1274         Ivar->setInvalidDecl();
1275       }
1276     }
1277   } else {
1278     if (Synthesize)
1279       if (ObjCPropertyImplDecl *PPIDecl =
1280           CatImplClass->FindPropertyImplIvarDecl(PropertyIvar)) {
1281         Diag(PropertyDiagLoc, diag::error_duplicate_ivar_use)
1282         << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
1283         << PropertyIvar;
1284         Diag(PPIDecl->getLocation(), diag::note_previous_use);
1285       }
1286 
1287     if (ObjCPropertyImplDecl *PPIDecl =
1288         CatImplClass->FindPropertyImplDecl(PropertyId)) {
1289       Diag(PropertyDiagLoc, diag::error_property_implemented) << PropertyId;
1290       Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
1291       return 0;
1292     }
1293     CatImplClass->addPropertyImplementation(PIDecl);
1294   }
1295 
1296   return PIDecl;
1297 }
1298 
1299 //===----------------------------------------------------------------------===//
1300 // Helper methods.
1301 //===----------------------------------------------------------------------===//
1302 
1303 /// DiagnosePropertyMismatch - Compares two properties for their
1304 /// attributes and types and warns on a variety of inconsistencies.
1305 ///
1306 void
1307 Sema::DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
1308                                ObjCPropertyDecl *SuperProperty,
1309                                const IdentifierInfo *inheritedName,
1310                                bool OverridingProtocolProperty) {
1311   ObjCPropertyDecl::PropertyAttributeKind CAttr =
1312     Property->getPropertyAttributes();
1313   ObjCPropertyDecl::PropertyAttributeKind SAttr =
1314     SuperProperty->getPropertyAttributes();
1315 
1316   // We allow readonly properties without an explicit ownership
1317   // (assign/unsafe_unretained/weak/retain/strong/copy) in super class
1318   // to be overridden by a property with any explicit ownership in the subclass.
1319   if (!OverridingProtocolProperty &&
1320       !getOwnershipRule(SAttr) && getOwnershipRule(CAttr))
1321     ;
1322   else {
1323     if ((CAttr & ObjCPropertyDecl::OBJC_PR_readonly)
1324         && (SAttr & ObjCPropertyDecl::OBJC_PR_readwrite))
1325       Diag(Property->getLocation(), diag::warn_readonly_property)
1326         << Property->getDeclName() << inheritedName;
1327     if ((CAttr & ObjCPropertyDecl::OBJC_PR_copy)
1328         != (SAttr & ObjCPropertyDecl::OBJC_PR_copy))
1329       Diag(Property->getLocation(), diag::warn_property_attribute)
1330         << Property->getDeclName() << "copy" << inheritedName;
1331     else if (!(SAttr & ObjCPropertyDecl::OBJC_PR_readonly)){
1332       unsigned CAttrRetain =
1333         (CAttr &
1334          (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_strong));
1335       unsigned SAttrRetain =
1336         (SAttr &
1337          (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_strong));
1338       bool CStrong = (CAttrRetain != 0);
1339       bool SStrong = (SAttrRetain != 0);
1340       if (CStrong != SStrong)
1341         Diag(Property->getLocation(), diag::warn_property_attribute)
1342           << Property->getDeclName() << "retain (or strong)" << inheritedName;
1343     }
1344   }
1345 
1346   if ((CAttr & ObjCPropertyDecl::OBJC_PR_nonatomic)
1347       != (SAttr & ObjCPropertyDecl::OBJC_PR_nonatomic)) {
1348     Diag(Property->getLocation(), diag::warn_property_attribute)
1349       << Property->getDeclName() << "atomic" << inheritedName;
1350     Diag(SuperProperty->getLocation(), diag::note_property_declare);
1351   }
1352   if (Property->getSetterName() != SuperProperty->getSetterName()) {
1353     Diag(Property->getLocation(), diag::warn_property_attribute)
1354       << Property->getDeclName() << "setter" << inheritedName;
1355     Diag(SuperProperty->getLocation(), diag::note_property_declare);
1356   }
1357   if (Property->getGetterName() != SuperProperty->getGetterName()) {
1358     Diag(Property->getLocation(), diag::warn_property_attribute)
1359       << Property->getDeclName() << "getter" << inheritedName;
1360     Diag(SuperProperty->getLocation(), diag::note_property_declare);
1361   }
1362 
1363   QualType LHSType =
1364     Context.getCanonicalType(SuperProperty->getType());
1365   QualType RHSType =
1366     Context.getCanonicalType(Property->getType());
1367 
1368   if (!Context.propertyTypesAreCompatible(LHSType, RHSType)) {
1369     // Do cases not handled in above.
1370     // FIXME. For future support of covariant property types, revisit this.
1371     bool IncompatibleObjC = false;
1372     QualType ConvertedType;
1373     if (!isObjCPointerConversion(RHSType, LHSType,
1374                                  ConvertedType, IncompatibleObjC) ||
1375         IncompatibleObjC) {
1376         Diag(Property->getLocation(), diag::warn_property_types_are_incompatible)
1377         << Property->getType() << SuperProperty->getType() << inheritedName;
1378       Diag(SuperProperty->getLocation(), diag::note_property_declare);
1379     }
1380   }
1381 }
1382 
1383 bool Sema::DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *property,
1384                                             ObjCMethodDecl *GetterMethod,
1385                                             SourceLocation Loc) {
1386   if (!GetterMethod)
1387     return false;
1388   QualType GetterType = GetterMethod->getResultType().getNonReferenceType();
1389   QualType PropertyIvarType = property->getType().getNonReferenceType();
1390   bool compat = Context.hasSameType(PropertyIvarType, GetterType);
1391   if (!compat) {
1392     if (isa<ObjCObjectPointerType>(PropertyIvarType) &&
1393         isa<ObjCObjectPointerType>(GetterType))
1394       compat =
1395         Context.canAssignObjCInterfaces(
1396                                       GetterType->getAs<ObjCObjectPointerType>(),
1397                                       PropertyIvarType->getAs<ObjCObjectPointerType>());
1398     else if (CheckAssignmentConstraints(Loc, GetterType, PropertyIvarType)
1399               != Compatible) {
1400           Diag(Loc, diag::error_property_accessor_type)
1401             << property->getDeclName() << PropertyIvarType
1402             << GetterMethod->getSelector() << GetterType;
1403           Diag(GetterMethod->getLocation(), diag::note_declared_at);
1404           return true;
1405     } else {
1406       compat = true;
1407       QualType lhsType =Context.getCanonicalType(PropertyIvarType).getUnqualifiedType();
1408       QualType rhsType =Context.getCanonicalType(GetterType).getUnqualifiedType();
1409       if (lhsType != rhsType && lhsType->isArithmeticType())
1410         compat = false;
1411     }
1412   }
1413 
1414   if (!compat) {
1415     Diag(Loc, diag::warn_accessor_property_type_mismatch)
1416     << property->getDeclName()
1417     << GetterMethod->getSelector();
1418     Diag(GetterMethod->getLocation(), diag::note_declared_at);
1419     return true;
1420   }
1421 
1422   return false;
1423 }
1424 
1425 /// CollectImmediateProperties - This routine collects all properties in
1426 /// the class and its conforming protocols; but not those in its super class.
1427 void Sema::CollectImmediateProperties(ObjCContainerDecl *CDecl,
1428             ObjCContainerDecl::PropertyMap &PropMap,
1429             ObjCContainerDecl::PropertyMap &SuperPropMap) {
1430   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1431     for (ObjCContainerDecl::prop_iterator P = IDecl->prop_begin(),
1432          E = IDecl->prop_end(); P != E; ++P) {
1433       ObjCPropertyDecl *Prop = *P;
1434       PropMap[Prop->getIdentifier()] = Prop;
1435     }
1436     // scan through class's protocols.
1437     for (ObjCInterfaceDecl::all_protocol_iterator
1438          PI = IDecl->all_referenced_protocol_begin(),
1439          E = IDecl->all_referenced_protocol_end(); PI != E; ++PI)
1440         CollectImmediateProperties((*PI), PropMap, SuperPropMap);
1441   }
1442   if (ObjCCategoryDecl *CATDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1443     if (!CATDecl->IsClassExtension())
1444       for (ObjCContainerDecl::prop_iterator P = CATDecl->prop_begin(),
1445            E = CATDecl->prop_end(); P != E; ++P) {
1446         ObjCPropertyDecl *Prop = *P;
1447         PropMap[Prop->getIdentifier()] = Prop;
1448       }
1449     // scan through class's protocols.
1450     for (ObjCCategoryDecl::protocol_iterator PI = CATDecl->protocol_begin(),
1451          E = CATDecl->protocol_end(); PI != E; ++PI)
1452       CollectImmediateProperties((*PI), PropMap, SuperPropMap);
1453   }
1454   else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1455     for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
1456          E = PDecl->prop_end(); P != E; ++P) {
1457       ObjCPropertyDecl *Prop = *P;
1458       ObjCPropertyDecl *PropertyFromSuper = SuperPropMap[Prop->getIdentifier()];
1459       // Exclude property for protocols which conform to class's super-class,
1460       // as super-class has to implement the property.
1461       if (!PropertyFromSuper ||
1462           PropertyFromSuper->getIdentifier() != Prop->getIdentifier()) {
1463         ObjCPropertyDecl *&PropEntry = PropMap[Prop->getIdentifier()];
1464         if (!PropEntry)
1465           PropEntry = Prop;
1466       }
1467     }
1468     // scan through protocol's protocols.
1469     for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
1470          E = PDecl->protocol_end(); PI != E; ++PI)
1471       CollectImmediateProperties((*PI), PropMap, SuperPropMap);
1472   }
1473 }
1474 
1475 /// CollectSuperClassPropertyImplementations - This routine collects list of
1476 /// properties to be implemented in super class(s) and also coming from their
1477 /// conforming protocols.
1478 static void CollectSuperClassPropertyImplementations(ObjCInterfaceDecl *CDecl,
1479                                     ObjCInterfaceDecl::PropertyMap &PropMap) {
1480   if (ObjCInterfaceDecl *SDecl = CDecl->getSuperClass()) {
1481     ObjCInterfaceDecl::PropertyDeclOrder PO;
1482     while (SDecl) {
1483       SDecl->collectPropertiesToImplement(PropMap, PO);
1484       SDecl = SDecl->getSuperClass();
1485     }
1486   }
1487 }
1488 
1489 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
1490 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
1491 /// declared in class 'IFace'.
1492 bool
1493 Sema::IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
1494                                      ObjCMethodDecl *Method, ObjCIvarDecl *IV) {
1495   if (!IV->getSynthesize())
1496     return false;
1497   ObjCMethodDecl *IMD = IFace->lookupMethod(Method->getSelector(),
1498                                             Method->isInstanceMethod());
1499   if (!IMD || !IMD->isPropertyAccessor())
1500     return false;
1501 
1502   // look up a property declaration whose one of its accessors is implemented
1503   // by this method.
1504   for (ObjCContainerDecl::prop_iterator P = IFace->prop_begin(),
1505        E = IFace->prop_end(); P != E; ++P) {
1506     ObjCPropertyDecl *property = *P;
1507     if ((property->getGetterName() == IMD->getSelector() ||
1508          property->getSetterName() == IMD->getSelector()) &&
1509         (property->getPropertyIvarDecl() == IV))
1510       return true;
1511   }
1512   return false;
1513 }
1514 
1515 
1516 /// \brief Default synthesizes all properties which must be synthesized
1517 /// in class's \@implementation.
1518 void Sema::DefaultSynthesizeProperties(Scope *S, ObjCImplDecl* IMPDecl,
1519                                        ObjCInterfaceDecl *IDecl) {
1520 
1521   ObjCInterfaceDecl::PropertyMap PropMap;
1522   ObjCInterfaceDecl::PropertyDeclOrder PropertyOrder;
1523   IDecl->collectPropertiesToImplement(PropMap, PropertyOrder);
1524   if (PropMap.empty())
1525     return;
1526   ObjCInterfaceDecl::PropertyMap SuperPropMap;
1527   CollectSuperClassPropertyImplementations(IDecl, SuperPropMap);
1528 
1529   for (unsigned i = 0, e = PropertyOrder.size(); i != e; i++) {
1530     ObjCPropertyDecl *Prop = PropertyOrder[i];
1531     // Is there a matching property synthesize/dynamic?
1532     if (Prop->isInvalidDecl() ||
1533         Prop->getPropertyImplementation() == ObjCPropertyDecl::Optional)
1534       continue;
1535     // Property may have been synthesized by user.
1536     if (IMPDecl->FindPropertyImplDecl(Prop->getIdentifier()))
1537       continue;
1538     if (IMPDecl->getInstanceMethod(Prop->getGetterName())) {
1539       if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readonly)
1540         continue;
1541       if (IMPDecl->getInstanceMethod(Prop->getSetterName()))
1542         continue;
1543     }
1544     // If property to be implemented in the super class, ignore.
1545     if (SuperPropMap[Prop->getIdentifier()]) {
1546       ObjCPropertyDecl *PropInSuperClass = SuperPropMap[Prop->getIdentifier()];
1547       if ((Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readwrite) &&
1548           (PropInSuperClass->getPropertyAttributes() &
1549            ObjCPropertyDecl::OBJC_PR_readonly) &&
1550           !IMPDecl->getInstanceMethod(Prop->getSetterName()) &&
1551           !IDecl->HasUserDeclaredSetterMethod(Prop)) {
1552             Diag(Prop->getLocation(), diag::warn_no_autosynthesis_property)
1553               << Prop->getIdentifier();
1554             Diag(PropInSuperClass->getLocation(), diag::note_property_declare);
1555       }
1556       continue;
1557     }
1558     if (ObjCPropertyImplDecl *PID =
1559         IMPDecl->FindPropertyImplIvarDecl(Prop->getIdentifier())) {
1560       if (PID->getPropertyDecl() != Prop) {
1561         Diag(Prop->getLocation(), diag::warn_no_autosynthesis_shared_ivar_property)
1562           << Prop->getIdentifier();
1563         if (!PID->getLocation().isInvalid())
1564           Diag(PID->getLocation(), diag::note_property_synthesize);
1565       }
1566       continue;
1567     }
1568     if (ObjCProtocolDecl *Proto =
1569           dyn_cast<ObjCProtocolDecl>(Prop->getDeclContext())) {
1570       // We won't auto-synthesize properties declared in protocols.
1571       Diag(IMPDecl->getLocation(),
1572            diag::warn_auto_synthesizing_protocol_property)
1573         << Prop << Proto;
1574       Diag(Prop->getLocation(), diag::note_property_declare);
1575       continue;
1576     }
1577 
1578     // We use invalid SourceLocations for the synthesized ivars since they
1579     // aren't really synthesized at a particular location; they just exist.
1580     // Saying that they are located at the @implementation isn't really going
1581     // to help users.
1582     ObjCPropertyImplDecl *PIDecl = dyn_cast_or_null<ObjCPropertyImplDecl>(
1583       ActOnPropertyImplDecl(S, SourceLocation(), SourceLocation(),
1584                             true,
1585                             /* property = */ Prop->getIdentifier(),
1586                             /* ivar = */ Prop->getDefaultSynthIvarName(Context),
1587                             Prop->getLocation()));
1588     if (PIDecl) {
1589       Diag(Prop->getLocation(), diag::warn_missing_explicit_synthesis);
1590       Diag(IMPDecl->getLocation(), diag::note_while_in_implementation);
1591     }
1592   }
1593 }
1594 
1595 void Sema::DefaultSynthesizeProperties(Scope *S, Decl *D) {
1596   if (!LangOpts.ObjCDefaultSynthProperties || LangOpts.ObjCRuntime.isFragile())
1597     return;
1598   ObjCImplementationDecl *IC=dyn_cast_or_null<ObjCImplementationDecl>(D);
1599   if (!IC)
1600     return;
1601   if (ObjCInterfaceDecl* IDecl = IC->getClassInterface())
1602     if (!IDecl->isObjCRequiresPropertyDefs())
1603       DefaultSynthesizeProperties(S, IC, IDecl);
1604 }
1605 
1606 void Sema::DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
1607                                       ObjCContainerDecl *CDecl) {
1608   ObjCContainerDecl::PropertyMap NoNeedToImplPropMap;
1609   ObjCInterfaceDecl *IDecl;
1610   // Gather properties which need not be implemented in this class
1611   // or category.
1612   if (!(IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)))
1613     if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1614       // For categories, no need to implement properties declared in
1615       // its primary class (and its super classes) if property is
1616       // declared in one of those containers.
1617       if ((IDecl = C->getClassInterface())) {
1618         ObjCInterfaceDecl::PropertyDeclOrder PO;
1619         IDecl->collectPropertiesToImplement(NoNeedToImplPropMap, PO);
1620       }
1621     }
1622   if (IDecl)
1623     CollectSuperClassPropertyImplementations(IDecl, NoNeedToImplPropMap);
1624 
1625   ObjCContainerDecl::PropertyMap PropMap;
1626   CollectImmediateProperties(CDecl, PropMap, NoNeedToImplPropMap);
1627   if (PropMap.empty())
1628     return;
1629 
1630   llvm::DenseSet<ObjCPropertyDecl *> PropImplMap;
1631   for (ObjCImplDecl::propimpl_iterator
1632        I = IMPDecl->propimpl_begin(),
1633        EI = IMPDecl->propimpl_end(); I != EI; ++I)
1634     PropImplMap.insert(I->getPropertyDecl());
1635 
1636   SelectorSet InsMap;
1637   // Collect property accessors implemented in current implementation.
1638   for (ObjCImplementationDecl::instmeth_iterator
1639        I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I)
1640     InsMap.insert((*I)->getSelector());
1641 
1642   ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
1643   ObjCInterfaceDecl *PrimaryClass = 0;
1644   if (C && !C->IsClassExtension())
1645     if ((PrimaryClass = C->getClassInterface()))
1646       // Report unimplemented properties in the category as well.
1647       if (ObjCImplDecl *IMP = PrimaryClass->getImplementation()) {
1648         // When reporting on missing setter/getters, do not report when
1649         // setter/getter is implemented in category's primary class
1650         // implementation.
1651         for (ObjCImplementationDecl::instmeth_iterator
1652              I = IMP->instmeth_begin(), E = IMP->instmeth_end(); I!=E; ++I)
1653           InsMap.insert((*I)->getSelector());
1654       }
1655 
1656   for (ObjCContainerDecl::PropertyMap::iterator
1657        P = PropMap.begin(), E = PropMap.end(); P != E; ++P) {
1658     ObjCPropertyDecl *Prop = P->second;
1659     // Is there a matching propery synthesize/dynamic?
1660     if (Prop->isInvalidDecl() ||
1661         Prop->getPropertyImplementation() == ObjCPropertyDecl::Optional ||
1662         PropImplMap.count(Prop) ||
1663         Prop->getAvailability() == AR_Unavailable)
1664       continue;
1665     // When reporting on missing property getter implementation in
1666     // categories, do not report when they are declared in primary class,
1667     // class's protocol, or one of it super classes. This is because,
1668     // the class is going to implement them.
1669     if (!InsMap.count(Prop->getGetterName()) &&
1670         (PrimaryClass == 0 ||
1671          !PrimaryClass->lookupPropertyAccessor(Prop->getGetterName(), C))) {
1672       Diag(IMPDecl->getLocation(),
1673            isa<ObjCCategoryDecl>(CDecl) ?
1674             diag::warn_setter_getter_impl_required_in_category :
1675             diag::warn_setter_getter_impl_required)
1676       << Prop->getDeclName() << Prop->getGetterName();
1677       Diag(Prop->getLocation(),
1678            diag::note_property_declare);
1679       if (LangOpts.ObjCDefaultSynthProperties && LangOpts.ObjCRuntime.isNonFragile())
1680         if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CDecl))
1681           if (const ObjCInterfaceDecl *RID = ID->isObjCRequiresPropertyDefs())
1682             Diag(RID->getLocation(), diag::note_suppressed_class_declare);
1683 
1684     }
1685     // When reporting on missing property setter implementation in
1686     // categories, do not report when they are declared in primary class,
1687     // class's protocol, or one of it super classes. This is because,
1688     // the class is going to implement them.
1689     if (!Prop->isReadOnly() && !InsMap.count(Prop->getSetterName()) &&
1690         (PrimaryClass == 0 ||
1691          !PrimaryClass->lookupPropertyAccessor(Prop->getSetterName(), C))) {
1692       Diag(IMPDecl->getLocation(),
1693            isa<ObjCCategoryDecl>(CDecl) ?
1694            diag::warn_setter_getter_impl_required_in_category :
1695            diag::warn_setter_getter_impl_required)
1696       << Prop->getDeclName() << Prop->getSetterName();
1697       Diag(Prop->getLocation(),
1698            diag::note_property_declare);
1699       if (LangOpts.ObjCDefaultSynthProperties && LangOpts.ObjCRuntime.isNonFragile())
1700         if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CDecl))
1701           if (const ObjCInterfaceDecl *RID = ID->isObjCRequiresPropertyDefs())
1702             Diag(RID->getLocation(), diag::note_suppressed_class_declare);
1703     }
1704   }
1705 }
1706 
1707 void
1708 Sema::AtomicPropertySetterGetterRules (ObjCImplDecl* IMPDecl,
1709                                        ObjCContainerDecl* IDecl) {
1710   // Rules apply in non-GC mode only
1711   if (getLangOpts().getGC() != LangOptions::NonGC)
1712     return;
1713   for (ObjCContainerDecl::prop_iterator I = IDecl->prop_begin(),
1714        E = IDecl->prop_end();
1715        I != E; ++I) {
1716     ObjCPropertyDecl *Property = *I;
1717     ObjCMethodDecl *GetterMethod = 0;
1718     ObjCMethodDecl *SetterMethod = 0;
1719     bool LookedUpGetterSetter = false;
1720 
1721     unsigned Attributes = Property->getPropertyAttributes();
1722     unsigned AttributesAsWritten = Property->getPropertyAttributesAsWritten();
1723 
1724     if (!(AttributesAsWritten & ObjCPropertyDecl::OBJC_PR_atomic) &&
1725         !(AttributesAsWritten & ObjCPropertyDecl::OBJC_PR_nonatomic)) {
1726       GetterMethod = IMPDecl->getInstanceMethod(Property->getGetterName());
1727       SetterMethod = IMPDecl->getInstanceMethod(Property->getSetterName());
1728       LookedUpGetterSetter = true;
1729       if (GetterMethod) {
1730         Diag(GetterMethod->getLocation(),
1731              diag::warn_default_atomic_custom_getter_setter)
1732           << Property->getIdentifier() << 0;
1733         Diag(Property->getLocation(), diag::note_property_declare);
1734       }
1735       if (SetterMethod) {
1736         Diag(SetterMethod->getLocation(),
1737              diag::warn_default_atomic_custom_getter_setter)
1738           << Property->getIdentifier() << 1;
1739         Diag(Property->getLocation(), diag::note_property_declare);
1740       }
1741     }
1742 
1743     // We only care about readwrite atomic property.
1744     if ((Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) ||
1745         !(Attributes & ObjCPropertyDecl::OBJC_PR_readwrite))
1746       continue;
1747     if (const ObjCPropertyImplDecl *PIDecl
1748          = IMPDecl->FindPropertyImplDecl(Property->getIdentifier())) {
1749       if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
1750         continue;
1751       if (!LookedUpGetterSetter) {
1752         GetterMethod = IMPDecl->getInstanceMethod(Property->getGetterName());
1753         SetterMethod = IMPDecl->getInstanceMethod(Property->getSetterName());
1754         LookedUpGetterSetter = true;
1755       }
1756       if ((GetterMethod && !SetterMethod) || (!GetterMethod && SetterMethod)) {
1757         SourceLocation MethodLoc =
1758           (GetterMethod ? GetterMethod->getLocation()
1759                         : SetterMethod->getLocation());
1760         Diag(MethodLoc, diag::warn_atomic_property_rule)
1761           << Property->getIdentifier() << (GetterMethod != 0)
1762           << (SetterMethod != 0);
1763         // fixit stuff.
1764         if (!AttributesAsWritten) {
1765           if (Property->getLParenLoc().isValid()) {
1766             // @property () ... case.
1767             SourceRange PropSourceRange(Property->getAtLoc(),
1768                                         Property->getLParenLoc());
1769             Diag(Property->getLocation(), diag::note_atomic_property_fixup_suggest) <<
1770               FixItHint::CreateReplacement(PropSourceRange, "@property (nonatomic");
1771           }
1772           else {
1773             //@property id etc.
1774             SourceLocation endLoc =
1775               Property->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
1776             endLoc = endLoc.getLocWithOffset(-1);
1777             SourceRange PropSourceRange(Property->getAtLoc(), endLoc);
1778             Diag(Property->getLocation(), diag::note_atomic_property_fixup_suggest) <<
1779               FixItHint::CreateReplacement(PropSourceRange, "@property (nonatomic) ");
1780           }
1781         }
1782         else if (!(AttributesAsWritten & ObjCPropertyDecl::OBJC_PR_atomic)) {
1783           // @property () ... case.
1784           SourceLocation endLoc = Property->getLParenLoc();
1785           SourceRange PropSourceRange(Property->getAtLoc(), endLoc);
1786           Diag(Property->getLocation(), diag::note_atomic_property_fixup_suggest) <<
1787            FixItHint::CreateReplacement(PropSourceRange, "@property (nonatomic, ");
1788         }
1789         else
1790           Diag(MethodLoc, diag::note_atomic_property_fixup_suggest);
1791         Diag(Property->getLocation(), diag::note_property_declare);
1792       }
1793     }
1794   }
1795 }
1796 
1797 void Sema::DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D) {
1798   if (getLangOpts().getGC() == LangOptions::GCOnly)
1799     return;
1800 
1801   for (ObjCImplementationDecl::propimpl_iterator
1802          i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
1803     ObjCPropertyImplDecl *PID = *i;
1804     const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1805     if (PD && !PD->hasAttr<NSReturnsNotRetainedAttr>() &&
1806         !D->getInstanceMethod(PD->getGetterName())) {
1807       ObjCMethodDecl *method = PD->getGetterMethodDecl();
1808       if (!method)
1809         continue;
1810       ObjCMethodFamily family = method->getMethodFamily();
1811       if (family == OMF_alloc || family == OMF_copy ||
1812           family == OMF_mutableCopy || family == OMF_new) {
1813         if (getLangOpts().ObjCAutoRefCount)
1814           Diag(PD->getLocation(), diag::err_cocoa_naming_owned_rule);
1815         else
1816           Diag(PD->getLocation(), diag::warn_cocoa_naming_owned_rule);
1817       }
1818     }
1819   }
1820 }
1821 
1822 void Sema::DiagnoseMissingDesignatedInitOverrides(
1823                                             const ObjCImplementationDecl *ImplD,
1824                                             const ObjCInterfaceDecl *IFD) {
1825   assert(IFD->hasDesignatedInitializers());
1826   const ObjCInterfaceDecl *SuperD = IFD->getSuperClass();
1827   if (!SuperD)
1828     return;
1829 
1830   SelectorSet InitSelSet;
1831   for (ObjCImplementationDecl::instmeth_iterator
1832          I = ImplD->instmeth_begin(), E = ImplD->instmeth_end(); I!=E; ++I)
1833     if ((*I)->getMethodFamily() == OMF_init)
1834       InitSelSet.insert((*I)->getSelector());
1835 
1836   SmallVector<const ObjCMethodDecl *, 8> DesignatedInits;
1837   SuperD->getDesignatedInitializers(DesignatedInits);
1838   for (SmallVector<const ObjCMethodDecl *, 8>::iterator
1839          I = DesignatedInits.begin(), E = DesignatedInits.end(); I != E; ++I) {
1840     const ObjCMethodDecl *MD = *I;
1841     if (!InitSelSet.count(MD->getSelector())) {
1842       Diag(ImplD->getLocation(),
1843            diag::warn_objc_implementation_missing_designated_init_override)
1844         << MD->getSelector();
1845       Diag(MD->getLocation(), diag::note_objc_designated_init_marked_here);
1846     }
1847   }
1848 }
1849 
1850 /// AddPropertyAttrs - Propagates attributes from a property to the
1851 /// implicitly-declared getter or setter for that property.
1852 static void AddPropertyAttrs(Sema &S, ObjCMethodDecl *PropertyMethod,
1853                              ObjCPropertyDecl *Property) {
1854   // Should we just clone all attributes over?
1855   for (Decl::attr_iterator A = Property->attr_begin(),
1856                         AEnd = Property->attr_end();
1857        A != AEnd; ++A) {
1858     if (isa<DeprecatedAttr>(*A) ||
1859         isa<UnavailableAttr>(*A) ||
1860         isa<AvailabilityAttr>(*A))
1861       PropertyMethod->addAttr((*A)->clone(S.Context));
1862   }
1863 }
1864 
1865 /// ProcessPropertyDecl - Make sure that any user-defined setter/getter methods
1866 /// have the property type and issue diagnostics if they don't.
1867 /// Also synthesize a getter/setter method if none exist (and update the
1868 /// appropriate lookup tables. FIXME: Should reconsider if adding synthesized
1869 /// methods is the "right" thing to do.
1870 void Sema::ProcessPropertyDecl(ObjCPropertyDecl *property,
1871                                ObjCContainerDecl *CD,
1872                                ObjCPropertyDecl *redeclaredProperty,
1873                                ObjCContainerDecl *lexicalDC) {
1874 
1875   ObjCMethodDecl *GetterMethod, *SetterMethod;
1876 
1877   GetterMethod = CD->getInstanceMethod(property->getGetterName());
1878   SetterMethod = CD->getInstanceMethod(property->getSetterName());
1879   DiagnosePropertyAccessorMismatch(property, GetterMethod,
1880                                    property->getLocation());
1881 
1882   if (SetterMethod) {
1883     ObjCPropertyDecl::PropertyAttributeKind CAttr =
1884       property->getPropertyAttributes();
1885     if ((!(CAttr & ObjCPropertyDecl::OBJC_PR_readonly)) &&
1886         Context.getCanonicalType(SetterMethod->getResultType()) !=
1887           Context.VoidTy)
1888       Diag(SetterMethod->getLocation(), diag::err_setter_type_void);
1889     if (SetterMethod->param_size() != 1 ||
1890         !Context.hasSameUnqualifiedType(
1891           (*SetterMethod->param_begin())->getType().getNonReferenceType(),
1892           property->getType().getNonReferenceType())) {
1893       Diag(property->getLocation(),
1894            diag::warn_accessor_property_type_mismatch)
1895         << property->getDeclName()
1896         << SetterMethod->getSelector();
1897       Diag(SetterMethod->getLocation(), diag::note_declared_at);
1898     }
1899   }
1900 
1901   // Synthesize getter/setter methods if none exist.
1902   // Find the default getter and if one not found, add one.
1903   // FIXME: The synthesized property we set here is misleading. We almost always
1904   // synthesize these methods unless the user explicitly provided prototypes
1905   // (which is odd, but allowed). Sema should be typechecking that the
1906   // declarations jive in that situation (which it is not currently).
1907   if (!GetterMethod) {
1908     // No instance method of same name as property getter name was found.
1909     // Declare a getter method and add it to the list of methods
1910     // for this class.
1911     SourceLocation Loc = redeclaredProperty ?
1912       redeclaredProperty->getLocation() :
1913       property->getLocation();
1914 
1915     GetterMethod = ObjCMethodDecl::Create(Context, Loc, Loc,
1916                              property->getGetterName(),
1917                              property->getType(), 0, CD, /*isInstance=*/true,
1918                              /*isVariadic=*/false, /*isPropertyAccessor=*/true,
1919                              /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1920                              (property->getPropertyImplementation() ==
1921                               ObjCPropertyDecl::Optional) ?
1922                              ObjCMethodDecl::Optional :
1923                              ObjCMethodDecl::Required);
1924     CD->addDecl(GetterMethod);
1925 
1926     AddPropertyAttrs(*this, GetterMethod, property);
1927 
1928     // FIXME: Eventually this shouldn't be needed, as the lexical context
1929     // and the real context should be the same.
1930     if (lexicalDC)
1931       GetterMethod->setLexicalDeclContext(lexicalDC);
1932     if (property->hasAttr<NSReturnsNotRetainedAttr>())
1933       GetterMethod->addAttr(NSReturnsNotRetainedAttr::CreateImplicit(Context,
1934                                                                      Loc));
1935 
1936     if (property->hasAttr<ObjCReturnsInnerPointerAttr>())
1937       GetterMethod->addAttr(
1938         ObjCReturnsInnerPointerAttr::CreateImplicit(Context, Loc));
1939 
1940     if (const SectionAttr *SA = property->getAttr<SectionAttr>())
1941       GetterMethod->addAttr(SectionAttr::CreateImplicit(Context, SA->getName(),
1942                                                         Loc));
1943 
1944     if (getLangOpts().ObjCAutoRefCount)
1945       CheckARCMethodDecl(GetterMethod);
1946   } else
1947     // A user declared getter will be synthesize when @synthesize of
1948     // the property with the same name is seen in the @implementation
1949     GetterMethod->setPropertyAccessor(true);
1950   property->setGetterMethodDecl(GetterMethod);
1951 
1952   // Skip setter if property is read-only.
1953   if (!property->isReadOnly()) {
1954     // Find the default setter and if one not found, add one.
1955     if (!SetterMethod) {
1956       // No instance method of same name as property setter name was found.
1957       // Declare a setter method and add it to the list of methods
1958       // for this class.
1959       SourceLocation Loc = redeclaredProperty ?
1960         redeclaredProperty->getLocation() :
1961         property->getLocation();
1962 
1963       SetterMethod =
1964         ObjCMethodDecl::Create(Context, Loc, Loc,
1965                                property->getSetterName(), Context.VoidTy, 0,
1966                                CD, /*isInstance=*/true, /*isVariadic=*/false,
1967                                /*isPropertyAccessor=*/true,
1968                                /*isImplicitlyDeclared=*/true,
1969                                /*isDefined=*/false,
1970                                (property->getPropertyImplementation() ==
1971                                 ObjCPropertyDecl::Optional) ?
1972                                 ObjCMethodDecl::Optional :
1973                                 ObjCMethodDecl::Required);
1974 
1975       // Invent the arguments for the setter. We don't bother making a
1976       // nice name for the argument.
1977       ParmVarDecl *Argument = ParmVarDecl::Create(Context, SetterMethod,
1978                                                   Loc, Loc,
1979                                                   property->getIdentifier(),
1980                                     property->getType().getUnqualifiedType(),
1981                                                   /*TInfo=*/0,
1982                                                   SC_None,
1983                                                   0);
1984       SetterMethod->setMethodParams(Context, Argument, None);
1985 
1986       AddPropertyAttrs(*this, SetterMethod, property);
1987 
1988       CD->addDecl(SetterMethod);
1989       // FIXME: Eventually this shouldn't be needed, as the lexical context
1990       // and the real context should be the same.
1991       if (lexicalDC)
1992         SetterMethod->setLexicalDeclContext(lexicalDC);
1993       if (const SectionAttr *SA = property->getAttr<SectionAttr>())
1994         SetterMethod->addAttr(SectionAttr::CreateImplicit(Context,
1995                                                           SA->getName(), Loc));
1996       // It's possible for the user to have set a very odd custom
1997       // setter selector that causes it to have a method family.
1998       if (getLangOpts().ObjCAutoRefCount)
1999         CheckARCMethodDecl(SetterMethod);
2000     } else
2001       // A user declared setter will be synthesize when @synthesize of
2002       // the property with the same name is seen in the @implementation
2003       SetterMethod->setPropertyAccessor(true);
2004     property->setSetterMethodDecl(SetterMethod);
2005   }
2006   // Add any synthesized methods to the global pool. This allows us to
2007   // handle the following, which is supported by GCC (and part of the design).
2008   //
2009   // @interface Foo
2010   // @property double bar;
2011   // @end
2012   //
2013   // void thisIsUnfortunate() {
2014   //   id foo;
2015   //   double bar = [foo bar];
2016   // }
2017   //
2018   if (GetterMethod)
2019     AddInstanceMethodToGlobalPool(GetterMethod);
2020   if (SetterMethod)
2021     AddInstanceMethodToGlobalPool(SetterMethod);
2022 
2023   ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(CD);
2024   if (!CurrentClass) {
2025     if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(CD))
2026       CurrentClass = Cat->getClassInterface();
2027     else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(CD))
2028       CurrentClass = Impl->getClassInterface();
2029   }
2030   if (GetterMethod)
2031     CheckObjCMethodOverrides(GetterMethod, CurrentClass, Sema::RTC_Unknown);
2032   if (SetterMethod)
2033     CheckObjCMethodOverrides(SetterMethod, CurrentClass, Sema::RTC_Unknown);
2034 }
2035 
2036 void Sema::CheckObjCPropertyAttributes(Decl *PDecl,
2037                                        SourceLocation Loc,
2038                                        unsigned &Attributes,
2039                                        bool propertyInPrimaryClass) {
2040   // FIXME: Improve the reported location.
2041   if (!PDecl || PDecl->isInvalidDecl())
2042     return;
2043 
2044   if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
2045       (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
2046     Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2047     << "readonly" << "readwrite";
2048 
2049   ObjCPropertyDecl *PropertyDecl = cast<ObjCPropertyDecl>(PDecl);
2050   QualType PropertyTy = PropertyDecl->getType();
2051   unsigned PropertyOwnership = getOwnershipRule(Attributes);
2052 
2053   // 'readonly' property with no obvious lifetime.
2054   // its life time will be determined by its backing ivar.
2055   if (getLangOpts().ObjCAutoRefCount &&
2056       Attributes & ObjCDeclSpec::DQ_PR_readonly &&
2057       PropertyTy->isObjCRetainableType() &&
2058       !PropertyOwnership)
2059     return;
2060 
2061   // Check for copy or retain on non-object types.
2062   if ((Attributes & (ObjCDeclSpec::DQ_PR_weak | ObjCDeclSpec::DQ_PR_copy |
2063                     ObjCDeclSpec::DQ_PR_retain | ObjCDeclSpec::DQ_PR_strong)) &&
2064       !PropertyTy->isObjCRetainableType() &&
2065       !PropertyDecl->hasAttr<ObjCNSObjectAttr>()) {
2066     Diag(Loc, diag::err_objc_property_requires_object)
2067       << (Attributes & ObjCDeclSpec::DQ_PR_weak ? "weak" :
2068           Attributes & ObjCDeclSpec::DQ_PR_copy ? "copy" : "retain (or strong)");
2069     Attributes &= ~(ObjCDeclSpec::DQ_PR_weak   | ObjCDeclSpec::DQ_PR_copy |
2070                     ObjCDeclSpec::DQ_PR_retain | ObjCDeclSpec::DQ_PR_strong);
2071     PropertyDecl->setInvalidDecl();
2072   }
2073 
2074   // Check for more than one of { assign, copy, retain }.
2075   if (Attributes & ObjCDeclSpec::DQ_PR_assign) {
2076     if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
2077       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2078         << "assign" << "copy";
2079       Attributes &= ~ObjCDeclSpec::DQ_PR_copy;
2080     }
2081     if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
2082       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2083         << "assign" << "retain";
2084       Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
2085     }
2086     if (Attributes & ObjCDeclSpec::DQ_PR_strong) {
2087       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2088         << "assign" << "strong";
2089       Attributes &= ~ObjCDeclSpec::DQ_PR_strong;
2090     }
2091     if (getLangOpts().ObjCAutoRefCount  &&
2092         (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
2093       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2094         << "assign" << "weak";
2095       Attributes &= ~ObjCDeclSpec::DQ_PR_weak;
2096     }
2097     if (PropertyDecl->hasAttr<IBOutletCollectionAttr>())
2098       Diag(Loc, diag::warn_iboutletcollection_property_assign);
2099   } else if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) {
2100     if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
2101       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2102         << "unsafe_unretained" << "copy";
2103       Attributes &= ~ObjCDeclSpec::DQ_PR_copy;
2104     }
2105     if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
2106       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2107         << "unsafe_unretained" << "retain";
2108       Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
2109     }
2110     if (Attributes & ObjCDeclSpec::DQ_PR_strong) {
2111       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2112         << "unsafe_unretained" << "strong";
2113       Attributes &= ~ObjCDeclSpec::DQ_PR_strong;
2114     }
2115     if (getLangOpts().ObjCAutoRefCount  &&
2116         (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
2117       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2118         << "unsafe_unretained" << "weak";
2119       Attributes &= ~ObjCDeclSpec::DQ_PR_weak;
2120     }
2121   } else if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
2122     if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
2123       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2124         << "copy" << "retain";
2125       Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
2126     }
2127     if (Attributes & ObjCDeclSpec::DQ_PR_strong) {
2128       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2129         << "copy" << "strong";
2130       Attributes &= ~ObjCDeclSpec::DQ_PR_strong;
2131     }
2132     if (Attributes & ObjCDeclSpec::DQ_PR_weak) {
2133       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2134         << "copy" << "weak";
2135       Attributes &= ~ObjCDeclSpec::DQ_PR_weak;
2136     }
2137   }
2138   else if ((Attributes & ObjCDeclSpec::DQ_PR_retain) &&
2139            (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
2140       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2141         << "retain" << "weak";
2142       Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
2143   }
2144   else if ((Attributes & ObjCDeclSpec::DQ_PR_strong) &&
2145            (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
2146       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2147         << "strong" << "weak";
2148       Attributes &= ~ObjCDeclSpec::DQ_PR_weak;
2149   }
2150 
2151   if ((Attributes & ObjCDeclSpec::DQ_PR_atomic) &&
2152       (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)) {
2153       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2154         << "atomic" << "nonatomic";
2155       Attributes &= ~ObjCDeclSpec::DQ_PR_atomic;
2156   }
2157 
2158   // Warn if user supplied no assignment attribute, property is
2159   // readwrite, and this is an object type.
2160   if (!(Attributes & (ObjCDeclSpec::DQ_PR_assign | ObjCDeclSpec::DQ_PR_copy |
2161                       ObjCDeclSpec::DQ_PR_unsafe_unretained |
2162                       ObjCDeclSpec::DQ_PR_retain | ObjCDeclSpec::DQ_PR_strong |
2163                       ObjCDeclSpec::DQ_PR_weak)) &&
2164       PropertyTy->isObjCObjectPointerType()) {
2165       if (getLangOpts().ObjCAutoRefCount)
2166         // With arc,  @property definitions should default to (strong) when
2167         // not specified; including when property is 'readonly'.
2168         PropertyDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong);
2169       else if (!(Attributes & ObjCDeclSpec::DQ_PR_readonly)) {
2170         bool isAnyClassTy =
2171           (PropertyTy->isObjCClassType() ||
2172            PropertyTy->isObjCQualifiedClassType());
2173         // In non-gc, non-arc mode, 'Class' is treated as a 'void *' no need to
2174         // issue any warning.
2175         if (isAnyClassTy && getLangOpts().getGC() == LangOptions::NonGC)
2176           ;
2177         else if (propertyInPrimaryClass) {
2178           // Don't issue warning on property with no life time in class
2179           // extension as it is inherited from property in primary class.
2180           // Skip this warning in gc-only mode.
2181           if (getLangOpts().getGC() != LangOptions::GCOnly)
2182             Diag(Loc, diag::warn_objc_property_no_assignment_attribute);
2183 
2184           // If non-gc code warn that this is likely inappropriate.
2185           if (getLangOpts().getGC() == LangOptions::NonGC)
2186             Diag(Loc, diag::warn_objc_property_default_assign_on_object);
2187         }
2188       }
2189 
2190     // FIXME: Implement warning dependent on NSCopying being
2191     // implemented. See also:
2192     // <rdar://5168496&4855821&5607453&5096644&4947311&5698469&4947014&5168496>
2193     // (please trim this list while you are at it).
2194   }
2195 
2196   if (!(Attributes & ObjCDeclSpec::DQ_PR_copy)
2197       &&!(Attributes & ObjCDeclSpec::DQ_PR_readonly)
2198       && getLangOpts().getGC() == LangOptions::GCOnly
2199       && PropertyTy->isBlockPointerType())
2200     Diag(Loc, diag::warn_objc_property_copy_missing_on_block);
2201   else if ((Attributes & ObjCDeclSpec::DQ_PR_retain) &&
2202            !(Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
2203            !(Attributes & ObjCDeclSpec::DQ_PR_strong) &&
2204            PropertyTy->isBlockPointerType())
2205       Diag(Loc, diag::warn_objc_property_retain_of_block);
2206 
2207   if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
2208       (Attributes & ObjCDeclSpec::DQ_PR_setter))
2209     Diag(Loc, diag::warn_objc_readonly_property_has_setter);
2210 
2211 }
2212