clang API Documentation

SemaObjCProperty.cpp
Go to the documentation of this file.
00001 //===--- SemaObjCProperty.cpp - Semantic Analysis for ObjC @property ------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements semantic analysis for Objective C @property and
00011 //  @synthesize declarations.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "clang/Sema/SemaInternal.h"
00016 #include "clang/AST/ASTMutationListener.h"
00017 #include "clang/AST/DeclObjC.h"
00018 #include "clang/AST/ExprCXX.h"
00019 #include "clang/AST/ExprObjC.h"
00020 #include "clang/Basic/SourceManager.h"
00021 #include "clang/Lex/Lexer.h"
00022 #include "clang/Lex/Preprocessor.h"
00023 #include "clang/Sema/Initialization.h"
00024 #include "llvm/ADT/DenseSet.h"
00025 #include "llvm/ADT/SmallString.h"
00026 
00027 using namespace clang;
00028 
00029 //===----------------------------------------------------------------------===//
00030 // Grammar actions.
00031 //===----------------------------------------------------------------------===//
00032 
00033 /// getImpliedARCOwnership - Given a set of property attributes and a
00034 /// type, infer an expected lifetime.  The type's ownership qualification
00035 /// is not considered.
00036 ///
00037 /// Returns OCL_None if the attributes as stated do not imply an ownership.
00038 /// Never returns OCL_Autoreleasing.
00039 static Qualifiers::ObjCLifetime getImpliedARCOwnership(
00040                                ObjCPropertyDecl::PropertyAttributeKind attrs,
00041                                                 QualType type) {
00042   // retain, strong, copy, weak, and unsafe_unretained are only legal
00043   // on properties of retainable pointer type.
00044   if (attrs & (ObjCPropertyDecl::OBJC_PR_retain |
00045                ObjCPropertyDecl::OBJC_PR_strong |
00046                ObjCPropertyDecl::OBJC_PR_copy)) {
00047     return Qualifiers::OCL_Strong;
00048   } else if (attrs & ObjCPropertyDecl::OBJC_PR_weak) {
00049     return Qualifiers::OCL_Weak;
00050   } else if (attrs & ObjCPropertyDecl::OBJC_PR_unsafe_unretained) {
00051     return Qualifiers::OCL_ExplicitNone;
00052   }
00053 
00054   // assign can appear on other types, so we have to check the
00055   // property type.
00056   if (attrs & ObjCPropertyDecl::OBJC_PR_assign &&
00057       type->isObjCRetainableType()) {
00058     return Qualifiers::OCL_ExplicitNone;
00059   }
00060 
00061   return Qualifiers::OCL_None;
00062 }
00063 
00064 /// Check the internal consistency of a property declaration.
00065 static void checkARCPropertyDecl(Sema &S, ObjCPropertyDecl *property) {
00066   if (property->isInvalidDecl()) return;
00067 
00068   ObjCPropertyDecl::PropertyAttributeKind propertyKind
00069     = property->getPropertyAttributes();
00070   Qualifiers::ObjCLifetime propertyLifetime
00071     = property->getType().getObjCLifetime();
00072 
00073   // Nothing to do if we don't have a lifetime.
00074   if (propertyLifetime == Qualifiers::OCL_None) return;
00075 
00076   Qualifiers::ObjCLifetime expectedLifetime
00077     = getImpliedARCOwnership(propertyKind, property->getType());
00078   if (!expectedLifetime) {
00079     // We have a lifetime qualifier but no dominating property
00080     // attribute.  That's okay, but restore reasonable invariants by
00081     // setting the property attribute according to the lifetime
00082     // qualifier.
00083     ObjCPropertyDecl::PropertyAttributeKind attr;
00084     if (propertyLifetime == Qualifiers::OCL_Strong) {
00085       attr = ObjCPropertyDecl::OBJC_PR_strong;
00086     } else if (propertyLifetime == Qualifiers::OCL_Weak) {
00087       attr = ObjCPropertyDecl::OBJC_PR_weak;
00088     } else {
00089       assert(propertyLifetime == Qualifiers::OCL_ExplicitNone);
00090       attr = ObjCPropertyDecl::OBJC_PR_unsafe_unretained;
00091     }
00092     property->setPropertyAttributes(attr);
00093     return;
00094   }
00095 
00096   if (propertyLifetime == expectedLifetime) return;
00097 
00098   property->setInvalidDecl();
00099   S.Diag(property->getLocation(),
00100          diag::err_arc_inconsistent_property_ownership)
00101     << property->getDeclName()
00102     << expectedLifetime
00103     << propertyLifetime;
00104 }
00105 
00106 static unsigned deduceWeakPropertyFromType(Sema &S, QualType T) {
00107   if ((S.getLangOpts().getGC() != LangOptions::NonGC && 
00108        T.isObjCGCWeak()) ||
00109       (S.getLangOpts().ObjCAutoRefCount &&
00110        T.getObjCLifetime() == Qualifiers::OCL_Weak))
00111     return ObjCDeclSpec::DQ_PR_weak;
00112   return 0;
00113 }
00114 
00115 /// \brief Check this Objective-C property against a property declared in the
00116 /// given protocol.
00117 static void
00118 CheckPropertyAgainstProtocol(Sema &S, ObjCPropertyDecl *Prop,
00119                              ObjCProtocolDecl *Proto,
00120                              llvm::SmallPtrSet<ObjCProtocolDecl *, 16> &Known) {
00121   // Have we seen this protocol before?
00122   if (!Known.insert(Proto))
00123     return;
00124 
00125   // Look for a property with the same name.
00126   DeclContext::lookup_result R = Proto->lookup(Prop->getDeclName());
00127   for (unsigned I = 0, N = R.size(); I != N; ++I) {
00128     if (ObjCPropertyDecl *ProtoProp = dyn_cast<ObjCPropertyDecl>(R[I])) {
00129       S.DiagnosePropertyMismatch(Prop, ProtoProp, Proto->getIdentifier(), true);
00130       return;
00131     }
00132   }
00133 
00134   // Check this property against any protocols we inherit.
00135   for (auto *P : Proto->protocols())
00136     CheckPropertyAgainstProtocol(S, Prop, P, Known);
00137 }
00138 
00139 Decl *Sema::ActOnProperty(Scope *S, SourceLocation AtLoc,
00140                           SourceLocation LParenLoc,
00141                           FieldDeclarator &FD,
00142                           ObjCDeclSpec &ODS,
00143                           Selector GetterSel,
00144                           Selector SetterSel,
00145                           bool *isOverridingProperty,
00146                           tok::ObjCKeywordKind MethodImplKind,
00147                           DeclContext *lexicalDC) {
00148   unsigned Attributes = ODS.getPropertyAttributes();
00149   TypeSourceInfo *TSI = GetTypeForDeclarator(FD.D, S);
00150   QualType T = TSI->getType();
00151   Attributes |= deduceWeakPropertyFromType(*this, T);
00152   
00153   bool isReadWrite = ((Attributes & ObjCDeclSpec::DQ_PR_readwrite) ||
00154                       // default is readwrite!
00155                       !(Attributes & ObjCDeclSpec::DQ_PR_readonly));
00156   // property is defaulted to 'assign' if it is readwrite and is
00157   // not retain or copy
00158   bool isAssign = ((Attributes & ObjCDeclSpec::DQ_PR_assign) ||
00159                    (isReadWrite &&
00160                     !(Attributes & ObjCDeclSpec::DQ_PR_retain) &&
00161                     !(Attributes & ObjCDeclSpec::DQ_PR_strong) &&
00162                     !(Attributes & ObjCDeclSpec::DQ_PR_copy) &&
00163                     !(Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) &&
00164                     !(Attributes & ObjCDeclSpec::DQ_PR_weak)));
00165 
00166   // Proceed with constructing the ObjCPropertyDecls.
00167   ObjCContainerDecl *ClassDecl = cast<ObjCContainerDecl>(CurContext);
00168   ObjCPropertyDecl *Res = 0;
00169   if (ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
00170     if (CDecl->IsClassExtension()) {
00171       Res = HandlePropertyInClassExtension(S, AtLoc, LParenLoc,
00172                                            FD, GetterSel, SetterSel,
00173                                            isAssign, isReadWrite,
00174                                            Attributes,
00175                                            ODS.getPropertyAttributes(),
00176                                            isOverridingProperty, TSI,
00177                                            MethodImplKind);
00178       if (!Res)
00179         return 0;
00180     }
00181   }
00182 
00183   if (!Res) {
00184     Res = CreatePropertyDecl(S, ClassDecl, AtLoc, LParenLoc, FD,
00185                              GetterSel, SetterSel, isAssign, isReadWrite,
00186                              Attributes, ODS.getPropertyAttributes(),
00187                              TSI, MethodImplKind);
00188     if (lexicalDC)
00189       Res->setLexicalDeclContext(lexicalDC);
00190   }
00191 
00192   // Validate the attributes on the @property.
00193   CheckObjCPropertyAttributes(Res, AtLoc, Attributes, 
00194                               (isa<ObjCInterfaceDecl>(ClassDecl) ||
00195                                isa<ObjCProtocolDecl>(ClassDecl)));
00196 
00197   if (getLangOpts().ObjCAutoRefCount)
00198     checkARCPropertyDecl(*this, Res);
00199 
00200   llvm::SmallPtrSet<ObjCProtocolDecl *, 16> KnownProtos;
00201   if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
00202     // For a class, compare the property against a property in our superclass.
00203     bool FoundInSuper = false;
00204     ObjCInterfaceDecl *CurrentInterfaceDecl = IFace;
00205     while (ObjCInterfaceDecl *Super = CurrentInterfaceDecl->getSuperClass()) {
00206       DeclContext::lookup_result R = Super->lookup(Res->getDeclName());
00207       for (unsigned I = 0, N = R.size(); I != N; ++I) {
00208         if (ObjCPropertyDecl *SuperProp = dyn_cast<ObjCPropertyDecl>(R[I])) {
00209           DiagnosePropertyMismatch(Res, SuperProp, Super->getIdentifier(), false);
00210           FoundInSuper = true;
00211           break;
00212         }
00213       }
00214       if (FoundInSuper)
00215         break;
00216       else
00217         CurrentInterfaceDecl = Super;
00218     }
00219 
00220     if (FoundInSuper) {
00221       // Also compare the property against a property in our protocols.
00222       for (auto *P : CurrentInterfaceDecl->protocols()) {
00223         CheckPropertyAgainstProtocol(*this, Res, P, KnownProtos);
00224       }
00225     } else {
00226       // Slower path: look in all protocols we referenced.
00227       for (auto *P : IFace->all_referenced_protocols()) {
00228         CheckPropertyAgainstProtocol(*this, Res, P, KnownProtos);
00229       }
00230     }
00231   } else if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
00232     for (auto *P : Cat->protocols())
00233       CheckPropertyAgainstProtocol(*this, Res, P, KnownProtos);
00234   } else {
00235     ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(ClassDecl);
00236     for (auto *P : Proto->protocols())
00237       CheckPropertyAgainstProtocol(*this, Res, P, KnownProtos);
00238   }
00239 
00240   ActOnDocumentableDecl(Res);
00241   return Res;
00242 }
00243 
00244 static ObjCPropertyDecl::PropertyAttributeKind
00245 makePropertyAttributesAsWritten(unsigned Attributes) {
00246   unsigned attributesAsWritten = 0;
00247   if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
00248     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_readonly;
00249   if (Attributes & ObjCDeclSpec::DQ_PR_readwrite)
00250     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_readwrite;
00251   if (Attributes & ObjCDeclSpec::DQ_PR_getter)
00252     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_getter;
00253   if (Attributes & ObjCDeclSpec::DQ_PR_setter)
00254     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_setter;
00255   if (Attributes & ObjCDeclSpec::DQ_PR_assign)
00256     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_assign;
00257   if (Attributes & ObjCDeclSpec::DQ_PR_retain)
00258     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_retain;
00259   if (Attributes & ObjCDeclSpec::DQ_PR_strong)
00260     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_strong;
00261   if (Attributes & ObjCDeclSpec::DQ_PR_weak)
00262     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_weak;
00263   if (Attributes & ObjCDeclSpec::DQ_PR_copy)
00264     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_copy;
00265   if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained)
00266     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_unsafe_unretained;
00267   if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)
00268     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_nonatomic;
00269   if (Attributes & ObjCDeclSpec::DQ_PR_atomic)
00270     attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_atomic;
00271   
00272   return (ObjCPropertyDecl::PropertyAttributeKind)attributesAsWritten;
00273 }
00274 
00275 static bool LocPropertyAttribute( ASTContext &Context, const char *attrName, 
00276                                  SourceLocation LParenLoc, SourceLocation &Loc) {
00277   if (LParenLoc.isMacroID())
00278     return false;
00279   
00280   SourceManager &SM = Context.getSourceManager();
00281   std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(LParenLoc);
00282   // Try to load the file buffer.
00283   bool invalidTemp = false;
00284   StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
00285   if (invalidTemp)
00286     return false;
00287   const char *tokenBegin = file.data() + locInfo.second;
00288   
00289   // Lex from the start of the given location.
00290   Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
00291               Context.getLangOpts(),
00292               file.begin(), tokenBegin, file.end());
00293   Token Tok;
00294   do {
00295     lexer.LexFromRawLexer(Tok);
00296     if (Tok.is(tok::raw_identifier) &&
00297         StringRef(Tok.getRawIdentifierData(), Tok.getLength()) == attrName) {
00298       Loc = Tok.getLocation();
00299       return true;
00300     }
00301   } while (Tok.isNot(tok::r_paren));
00302   return false;
00303   
00304 }
00305 
00306 static unsigned getOwnershipRule(unsigned attr) {
00307   return attr & (ObjCPropertyDecl::OBJC_PR_assign |
00308                  ObjCPropertyDecl::OBJC_PR_retain |
00309                  ObjCPropertyDecl::OBJC_PR_copy   |
00310                  ObjCPropertyDecl::OBJC_PR_weak   |
00311                  ObjCPropertyDecl::OBJC_PR_strong |
00312                  ObjCPropertyDecl::OBJC_PR_unsafe_unretained);
00313 }
00314 
00315 ObjCPropertyDecl *
00316 Sema::HandlePropertyInClassExtension(Scope *S,
00317                                      SourceLocation AtLoc,
00318                                      SourceLocation LParenLoc,
00319                                      FieldDeclarator &FD,
00320                                      Selector GetterSel, Selector SetterSel,
00321                                      const bool isAssign,
00322                                      const bool isReadWrite,
00323                                      const unsigned Attributes,
00324                                      const unsigned AttributesAsWritten,
00325                                      bool *isOverridingProperty,
00326                                      TypeSourceInfo *T,
00327                                      tok::ObjCKeywordKind MethodImplKind) {
00328   ObjCCategoryDecl *CDecl = cast<ObjCCategoryDecl>(CurContext);
00329   // Diagnose if this property is already in continuation class.
00330   DeclContext *DC = CurContext;
00331   IdentifierInfo *PropertyId = FD.D.getIdentifier();
00332   ObjCInterfaceDecl *CCPrimary = CDecl->getClassInterface();
00333   
00334   if (CCPrimary) {
00335     // Check for duplicate declaration of this property in current and
00336     // other class extensions.
00337     for (const auto *Ext : CCPrimary->known_extensions()) {
00338       if (ObjCPropertyDecl *prevDecl
00339             = ObjCPropertyDecl::findPropertyDecl(Ext, PropertyId)) {
00340         Diag(AtLoc, diag::err_duplicate_property);
00341         Diag(prevDecl->getLocation(), diag::note_property_declare);
00342         return 0;
00343       }
00344     }
00345   }
00346 
00347   // Create a new ObjCPropertyDecl with the DeclContext being
00348   // the class extension.
00349   // FIXME. We should really be using CreatePropertyDecl for this.
00350   ObjCPropertyDecl *PDecl =
00351     ObjCPropertyDecl::Create(Context, DC, FD.D.getIdentifierLoc(),
00352                              PropertyId, AtLoc, LParenLoc, T);
00353   PDecl->setPropertyAttributesAsWritten(
00354                           makePropertyAttributesAsWritten(AttributesAsWritten));
00355   if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
00356     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly);
00357   if (Attributes & ObjCDeclSpec::DQ_PR_readwrite)
00358     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite);
00359   if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)
00360     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nonatomic);
00361   if (Attributes & ObjCDeclSpec::DQ_PR_atomic)
00362     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_atomic);
00363   // Set setter/getter selector name. Needed later.
00364   PDecl->setGetterName(GetterSel);
00365   PDecl->setSetterName(SetterSel);
00366   ProcessDeclAttributes(S, PDecl, FD.D);
00367   DC->addDecl(PDecl);
00368 
00369   // We need to look in the @interface to see if the @property was
00370   // already declared.
00371   if (!CCPrimary) {
00372     Diag(CDecl->getLocation(), diag::err_continuation_class);
00373     *isOverridingProperty = true;
00374     return 0;
00375   }
00376 
00377   // Find the property in continuation class's primary class only.
00378   ObjCPropertyDecl *PIDecl =
00379     CCPrimary->FindPropertyVisibleInPrimaryClass(PropertyId);
00380 
00381   if (!PIDecl) {
00382     // No matching property found in the primary class. Just fall thru
00383     // and add property to continuation class's primary class.
00384     ObjCPropertyDecl *PrimaryPDecl =
00385       CreatePropertyDecl(S, CCPrimary, AtLoc, LParenLoc,
00386                          FD, GetterSel, SetterSel, isAssign, isReadWrite,
00387                          Attributes,AttributesAsWritten, T, MethodImplKind, DC);
00388 
00389     // A case of continuation class adding a new property in the class. This
00390     // is not what it was meant for. However, gcc supports it and so should we.
00391     // Make sure setter/getters are declared here.
00392     ProcessPropertyDecl(PrimaryPDecl, CCPrimary, /* redeclaredProperty = */ 0,
00393                         /* lexicalDC = */ CDecl);
00394     PDecl->setGetterMethodDecl(PrimaryPDecl->getGetterMethodDecl());
00395     PDecl->setSetterMethodDecl(PrimaryPDecl->getSetterMethodDecl());
00396     if (ASTMutationListener *L = Context.getASTMutationListener())
00397       L->AddedObjCPropertyInClassExtension(PrimaryPDecl, /*OrigProp=*/0, CDecl);
00398     return PrimaryPDecl;
00399   }
00400   if (!Context.hasSameType(PIDecl->getType(), PDecl->getType())) {
00401     bool IncompatibleObjC = false;
00402     QualType ConvertedType;
00403     // Relax the strict type matching for property type in continuation class.
00404     // Allow property object type of continuation class to be different as long
00405     // as it narrows the object type in its primary class property. Note that
00406     // this conversion is safe only because the wider type is for a 'readonly'
00407     // property in primary class and 'narrowed' type for a 'readwrite' property
00408     // in continuation class.
00409     if (!isa<ObjCObjectPointerType>(PIDecl->getType()) ||
00410         !isa<ObjCObjectPointerType>(PDecl->getType()) ||
00411         (!isObjCPointerConversion(PDecl->getType(), PIDecl->getType(), 
00412                                   ConvertedType, IncompatibleObjC))
00413         || IncompatibleObjC) {
00414       Diag(AtLoc, 
00415           diag::err_type_mismatch_continuation_class) << PDecl->getType();
00416       Diag(PIDecl->getLocation(), diag::note_property_declare);
00417       return 0;
00418     }
00419   }
00420     
00421   // The property 'PIDecl's readonly attribute will be over-ridden
00422   // with continuation class's readwrite property attribute!
00423   unsigned PIkind = PIDecl->getPropertyAttributesAsWritten();
00424   if (isReadWrite && (PIkind & ObjCPropertyDecl::OBJC_PR_readonly)) {
00425     PIkind &= ~ObjCPropertyDecl::OBJC_PR_readonly;
00426     PIkind |= ObjCPropertyDecl::OBJC_PR_readwrite;
00427     PIkind |= deduceWeakPropertyFromType(*this, PIDecl->getType());
00428     unsigned ClassExtensionMemoryModel = getOwnershipRule(Attributes);
00429     unsigned PrimaryClassMemoryModel = getOwnershipRule(PIkind);
00430     if (PrimaryClassMemoryModel && ClassExtensionMemoryModel &&
00431         (PrimaryClassMemoryModel != ClassExtensionMemoryModel)) {
00432       Diag(AtLoc, diag::warn_property_attr_mismatch);
00433       Diag(PIDecl->getLocation(), diag::note_property_declare);
00434     }
00435     else if (getLangOpts().ObjCAutoRefCount) {
00436       QualType PrimaryPropertyQT =
00437         Context.getCanonicalType(PIDecl->getType()).getUnqualifiedType();
00438       if (isa<ObjCObjectPointerType>(PrimaryPropertyQT)) {
00439         bool PropertyIsWeak = ((PIkind & ObjCPropertyDecl::OBJC_PR_weak) != 0);
00440         Qualifiers::ObjCLifetime PrimaryPropertyLifeTime =
00441           PrimaryPropertyQT.getObjCLifetime();
00442         if (PrimaryPropertyLifeTime == Qualifiers::OCL_None &&
00443             (Attributes & ObjCDeclSpec::DQ_PR_weak) &&
00444             !PropertyIsWeak) {
00445               Diag(AtLoc, diag::warn_property_implicitly_mismatched);
00446               Diag(PIDecl->getLocation(), diag::note_property_declare);
00447             }
00448         }
00449     }
00450     
00451     DeclContext *DC = cast<DeclContext>(CCPrimary);
00452     if (!ObjCPropertyDecl::findPropertyDecl(DC,
00453                                  PIDecl->getDeclName().getAsIdentifierInfo())) {
00454       // In mrr mode, 'readwrite' property must have an explicit
00455       // memory attribute. If none specified, select the default (assign).
00456       if (!getLangOpts().ObjCAutoRefCount) {
00457         if (!(PIkind & (ObjCDeclSpec::DQ_PR_assign |
00458                         ObjCDeclSpec::DQ_PR_retain |
00459                         ObjCDeclSpec::DQ_PR_strong |
00460                         ObjCDeclSpec::DQ_PR_copy |
00461                         ObjCDeclSpec::DQ_PR_unsafe_unretained |
00462                         ObjCDeclSpec::DQ_PR_weak)))
00463           PIkind |= ObjCPropertyDecl::OBJC_PR_assign;
00464       }
00465       
00466       // Protocol is not in the primary class. Must build one for it.
00467       ObjCDeclSpec ProtocolPropertyODS;
00468       // FIXME. Assuming that ObjCDeclSpec::ObjCPropertyAttributeKind
00469       // and ObjCPropertyDecl::PropertyAttributeKind have identical
00470       // values.  Should consolidate both into one enum type.
00471       ProtocolPropertyODS.
00472       setPropertyAttributes((ObjCDeclSpec::ObjCPropertyAttributeKind)
00473                             PIkind);
00474       // Must re-establish the context from class extension to primary
00475       // class context.
00476       ContextRAII SavedContext(*this, CCPrimary);
00477       
00478       Decl *ProtocolPtrTy =
00479         ActOnProperty(S, AtLoc, LParenLoc, FD, ProtocolPropertyODS,
00480                       PIDecl->getGetterName(),
00481                       PIDecl->getSetterName(),
00482                       isOverridingProperty,
00483                       MethodImplKind,
00484                       /* lexicalDC = */ CDecl);
00485       PIDecl = cast<ObjCPropertyDecl>(ProtocolPtrTy);
00486     }
00487     PIDecl->makeitReadWriteAttribute();
00488     if (Attributes & ObjCDeclSpec::DQ_PR_retain)
00489       PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
00490     if (Attributes & ObjCDeclSpec::DQ_PR_strong)
00491       PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong);
00492     if (Attributes & ObjCDeclSpec::DQ_PR_copy)
00493       PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
00494     PIDecl->setSetterName(SetterSel);
00495   } else {
00496     // Tailor the diagnostics for the common case where a readwrite
00497     // property is declared both in the @interface and the continuation.
00498     // This is a common error where the user often intended the original
00499     // declaration to be readonly.
00500     unsigned diag =
00501       (Attributes & ObjCDeclSpec::DQ_PR_readwrite) &&
00502       (PIkind & ObjCPropertyDecl::OBJC_PR_readwrite)
00503       ? diag::err_use_continuation_class_redeclaration_readwrite
00504       : diag::err_use_continuation_class;
00505     Diag(AtLoc, diag)
00506       << CCPrimary->getDeclName();
00507     Diag(PIDecl->getLocation(), diag::note_property_declare);
00508     return 0;
00509   }
00510   *isOverridingProperty = true;
00511   // Make sure setter decl is synthesized, and added to primary class's list.
00512   ProcessPropertyDecl(PIDecl, CCPrimary, PDecl, CDecl);
00513   PDecl->setGetterMethodDecl(PIDecl->getGetterMethodDecl());
00514   PDecl->setSetterMethodDecl(PIDecl->getSetterMethodDecl());
00515   if (ASTMutationListener *L = Context.getASTMutationListener())
00516     L->AddedObjCPropertyInClassExtension(PDecl, PIDecl, CDecl);
00517   return PDecl;
00518 }
00519 
00520 ObjCPropertyDecl *Sema::CreatePropertyDecl(Scope *S,
00521                                            ObjCContainerDecl *CDecl,
00522                                            SourceLocation AtLoc,
00523                                            SourceLocation LParenLoc,
00524                                            FieldDeclarator &FD,
00525                                            Selector GetterSel,
00526                                            Selector SetterSel,
00527                                            const bool isAssign,
00528                                            const bool isReadWrite,
00529                                            const unsigned Attributes,
00530                                            const unsigned AttributesAsWritten,
00531                                            TypeSourceInfo *TInfo,
00532                                            tok::ObjCKeywordKind MethodImplKind,
00533                                            DeclContext *lexicalDC){
00534   IdentifierInfo *PropertyId = FD.D.getIdentifier();
00535   QualType T = TInfo->getType();
00536 
00537   // Issue a warning if property is 'assign' as default and its object, which is
00538   // gc'able conforms to NSCopying protocol
00539   if (getLangOpts().getGC() != LangOptions::NonGC &&
00540       isAssign && !(Attributes & ObjCDeclSpec::DQ_PR_assign))
00541     if (const ObjCObjectPointerType *ObjPtrTy =
00542           T->getAs<ObjCObjectPointerType>()) {
00543       ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
00544       if (IDecl)
00545         if (ObjCProtocolDecl* PNSCopying =
00546             LookupProtocol(&Context.Idents.get("NSCopying"), AtLoc))
00547           if (IDecl->ClassImplementsProtocol(PNSCopying, true))
00548             Diag(AtLoc, diag::warn_implements_nscopying) << PropertyId;
00549     }
00550 
00551   if (T->isObjCObjectType()) {
00552     SourceLocation StarLoc = TInfo->getTypeLoc().getLocEnd();
00553     StarLoc = PP.getLocForEndOfToken(StarLoc);
00554     Diag(FD.D.getIdentifierLoc(), diag::err_statically_allocated_object)
00555       << FixItHint::CreateInsertion(StarLoc, "*");
00556     T = Context.getObjCObjectPointerType(T);
00557     SourceLocation TLoc = TInfo->getTypeLoc().getLocStart();
00558     TInfo = Context.getTrivialTypeSourceInfo(T, TLoc);
00559   }
00560 
00561   DeclContext *DC = cast<DeclContext>(CDecl);
00562   ObjCPropertyDecl *PDecl = ObjCPropertyDecl::Create(Context, DC,
00563                                                      FD.D.getIdentifierLoc(),
00564                                                      PropertyId, AtLoc, LParenLoc, TInfo);
00565 
00566   if (ObjCPropertyDecl *prevDecl =
00567         ObjCPropertyDecl::findPropertyDecl(DC, PropertyId)) {
00568     Diag(PDecl->getLocation(), diag::err_duplicate_property);
00569     Diag(prevDecl->getLocation(), diag::note_property_declare);
00570     PDecl->setInvalidDecl();
00571   }
00572   else {
00573     DC->addDecl(PDecl);
00574     if (lexicalDC)
00575       PDecl->setLexicalDeclContext(lexicalDC);
00576   }
00577 
00578   if (T->isArrayType() || T->isFunctionType()) {
00579     Diag(AtLoc, diag::err_property_type) << T;
00580     PDecl->setInvalidDecl();
00581   }
00582 
00583   ProcessDeclAttributes(S, PDecl, FD.D);
00584 
00585   // Regardless of setter/getter attribute, we save the default getter/setter
00586   // selector names in anticipation of declaration of setter/getter methods.
00587   PDecl->setGetterName(GetterSel);
00588   PDecl->setSetterName(SetterSel);
00589   PDecl->setPropertyAttributesAsWritten(
00590                           makePropertyAttributesAsWritten(AttributesAsWritten));
00591 
00592   if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
00593     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly);
00594 
00595   if (Attributes & ObjCDeclSpec::DQ_PR_getter)
00596     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_getter);
00597 
00598   if (Attributes & ObjCDeclSpec::DQ_PR_setter)
00599     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_setter);
00600 
00601   if (isReadWrite)
00602     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite);
00603 
00604   if (Attributes & ObjCDeclSpec::DQ_PR_retain)
00605     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
00606 
00607   if (Attributes & ObjCDeclSpec::DQ_PR_strong)
00608     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong);
00609 
00610   if (Attributes & ObjCDeclSpec::DQ_PR_weak)
00611     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_weak);
00612 
00613   if (Attributes & ObjCDeclSpec::DQ_PR_copy)
00614     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
00615 
00616   if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained)
00617     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_unsafe_unretained);
00618 
00619   if (isAssign)
00620     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign);
00621 
00622   // In the semantic attributes, one of nonatomic or atomic is always set.
00623   if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)
00624     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nonatomic);
00625   else
00626     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_atomic);
00627 
00628   // 'unsafe_unretained' is alias for 'assign'.
00629   if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained)
00630     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign);
00631   if (isAssign)
00632     PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_unsafe_unretained);
00633 
00634   if (MethodImplKind == tok::objc_required)
00635     PDecl->setPropertyImplementation(ObjCPropertyDecl::Required);
00636   else if (MethodImplKind == tok::objc_optional)
00637     PDecl->setPropertyImplementation(ObjCPropertyDecl::Optional);
00638 
00639   return PDecl;
00640 }
00641 
00642 static void checkARCPropertyImpl(Sema &S, SourceLocation propertyImplLoc,
00643                                  ObjCPropertyDecl *property,
00644                                  ObjCIvarDecl *ivar) {
00645   if (property->isInvalidDecl() || ivar->isInvalidDecl()) return;
00646 
00647   QualType ivarType = ivar->getType();
00648   Qualifiers::ObjCLifetime ivarLifetime = ivarType.getObjCLifetime();
00649 
00650   // The lifetime implied by the property's attributes.
00651   Qualifiers::ObjCLifetime propertyLifetime =
00652     getImpliedARCOwnership(property->getPropertyAttributes(),
00653                            property->getType());
00654 
00655   // We're fine if they match.
00656   if (propertyLifetime == ivarLifetime) return;
00657 
00658   // These aren't valid lifetimes for object ivars;  don't diagnose twice.
00659   if (ivarLifetime == Qualifiers::OCL_None ||
00660       ivarLifetime == Qualifiers::OCL_Autoreleasing)
00661     return;
00662 
00663   // If the ivar is private, and it's implicitly __unsafe_unretained
00664   // becaues of its type, then pretend it was actually implicitly
00665   // __strong.  This is only sound because we're processing the
00666   // property implementation before parsing any method bodies.
00667   if (ivarLifetime == Qualifiers::OCL_ExplicitNone &&
00668       propertyLifetime == Qualifiers::OCL_Strong &&
00669       ivar->getAccessControl() == ObjCIvarDecl::Private) {
00670     SplitQualType split = ivarType.split();
00671     if (split.Quals.hasObjCLifetime()) {
00672       assert(ivarType->isObjCARCImplicitlyUnretainedType());
00673       split.Quals.setObjCLifetime(Qualifiers::OCL_Strong);
00674       ivarType = S.Context.getQualifiedType(split);
00675       ivar->setType(ivarType);
00676       return;
00677     }
00678   }
00679 
00680   switch (propertyLifetime) {
00681   case Qualifiers::OCL_Strong:
00682     S.Diag(ivar->getLocation(), diag::err_arc_strong_property_ownership)
00683       << property->getDeclName()
00684       << ivar->getDeclName()
00685       << ivarLifetime;
00686     break;
00687 
00688   case Qualifiers::OCL_Weak:
00689     S.Diag(ivar->getLocation(), diag::error_weak_property)
00690       << property->getDeclName()
00691       << ivar->getDeclName();
00692     break;
00693 
00694   case Qualifiers::OCL_ExplicitNone:
00695     S.Diag(ivar->getLocation(), diag::err_arc_assign_property_ownership)
00696       << property->getDeclName()
00697       << ivar->getDeclName()
00698       << ((property->getPropertyAttributesAsWritten() 
00699            & ObjCPropertyDecl::OBJC_PR_assign) != 0);
00700     break;
00701 
00702   case Qualifiers::OCL_Autoreleasing:
00703     llvm_unreachable("properties cannot be autoreleasing");
00704 
00705   case Qualifiers::OCL_None:
00706     // Any other property should be ignored.
00707     return;
00708   }
00709 
00710   S.Diag(property->getLocation(), diag::note_property_declare);
00711   if (propertyImplLoc.isValid())
00712     S.Diag(propertyImplLoc, diag::note_property_synthesize);
00713 }
00714 
00715 /// setImpliedPropertyAttributeForReadOnlyProperty -
00716 /// This routine evaludates life-time attributes for a 'readonly'
00717 /// property with no known lifetime of its own, using backing
00718 /// 'ivar's attribute, if any. If no backing 'ivar', property's
00719 /// life-time is assumed 'strong'.
00720 static void setImpliedPropertyAttributeForReadOnlyProperty(
00721               ObjCPropertyDecl *property, ObjCIvarDecl *ivar) {
00722   Qualifiers::ObjCLifetime propertyLifetime = 
00723     getImpliedARCOwnership(property->getPropertyAttributes(),
00724                            property->getType());
00725   if (propertyLifetime != Qualifiers::OCL_None)
00726     return;
00727   
00728   if (!ivar) {
00729     // if no backing ivar, make property 'strong'.
00730     property->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong);
00731     return;
00732   }
00733   // property assumes owenership of backing ivar.
00734   QualType ivarType = ivar->getType();
00735   Qualifiers::ObjCLifetime ivarLifetime = ivarType.getObjCLifetime();
00736   if (ivarLifetime == Qualifiers::OCL_Strong)
00737     property->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong);
00738   else if (ivarLifetime == Qualifiers::OCL_Weak)
00739     property->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_weak);
00740   return;
00741 }
00742 
00743 /// DiagnosePropertyMismatchDeclInProtocols - diagnose properties declared
00744 /// in inherited protocols with mismatched types. Since any of them can
00745 /// be candidate for synthesis.
00746 static void
00747 DiagnosePropertyMismatchDeclInProtocols(Sema &S, SourceLocation AtLoc,
00748                                         ObjCInterfaceDecl *ClassDecl,
00749                                         ObjCPropertyDecl *Property) {
00750   ObjCInterfaceDecl::ProtocolPropertyMap PropMap;
00751   for (const auto *PI : ClassDecl->all_referenced_protocols()) {
00752     if (const ObjCProtocolDecl *PDecl = PI->getDefinition())
00753       PDecl->collectInheritedProtocolProperties(Property, PropMap);
00754   }
00755   if (ObjCInterfaceDecl *SDecl = ClassDecl->getSuperClass())
00756     while (SDecl) {
00757       for (const auto *PI : SDecl->all_referenced_protocols()) {
00758         if (const ObjCProtocolDecl *PDecl = PI->getDefinition())
00759           PDecl->collectInheritedProtocolProperties(Property, PropMap);
00760       }
00761       SDecl = SDecl->getSuperClass();
00762     }
00763   
00764   if (PropMap.empty())
00765     return;
00766   
00767   QualType RHSType = S.Context.getCanonicalType(Property->getType());
00768   bool FirsTime = true;
00769   for (ObjCInterfaceDecl::ProtocolPropertyMap::iterator
00770        I = PropMap.begin(), E = PropMap.end(); I != E; I++) {
00771     ObjCPropertyDecl *Prop = I->second;
00772     QualType LHSType = S.Context.getCanonicalType(Prop->getType());
00773     if (!S.Context.propertyTypesAreCompatible(LHSType, RHSType)) {
00774       bool IncompatibleObjC = false;
00775       QualType ConvertedType;
00776       if (!S.isObjCPointerConversion(RHSType, LHSType, ConvertedType, IncompatibleObjC)
00777           || IncompatibleObjC) {
00778         if (FirsTime) {
00779           S.Diag(Property->getLocation(), diag::warn_protocol_property_mismatch)
00780             << Property->getType();
00781           FirsTime = false;
00782         }
00783         S.Diag(Prop->getLocation(), diag::note_protocol_property_declare)
00784           << Prop->getType();
00785       }
00786     }
00787   }
00788   if (!FirsTime && AtLoc.isValid())
00789     S.Diag(AtLoc, diag::note_property_synthesize);
00790 }
00791 
00792 /// ActOnPropertyImplDecl - This routine performs semantic checks and
00793 /// builds the AST node for a property implementation declaration; declared
00794 /// as \@synthesize or \@dynamic.
00795 ///
00796 Decl *Sema::ActOnPropertyImplDecl(Scope *S,
00797                                   SourceLocation AtLoc,
00798                                   SourceLocation PropertyLoc,
00799                                   bool Synthesize,
00800                                   IdentifierInfo *PropertyId,
00801                                   IdentifierInfo *PropertyIvar,
00802                                   SourceLocation PropertyIvarLoc) {
00803   ObjCContainerDecl *ClassImpDecl =
00804     dyn_cast<ObjCContainerDecl>(CurContext);
00805   // Make sure we have a context for the property implementation declaration.
00806   if (!ClassImpDecl) {
00807     Diag(AtLoc, diag::error_missing_property_context);
00808     return 0;
00809   }
00810   if (PropertyIvarLoc.isInvalid())
00811     PropertyIvarLoc = PropertyLoc;
00812   SourceLocation PropertyDiagLoc = PropertyLoc;
00813   if (PropertyDiagLoc.isInvalid())
00814     PropertyDiagLoc = ClassImpDecl->getLocStart();
00815   ObjCPropertyDecl *property = 0;
00816   ObjCInterfaceDecl* IDecl = 0;
00817   // Find the class or category class where this property must have
00818   // a declaration.
00819   ObjCImplementationDecl *IC = 0;
00820   ObjCCategoryImplDecl* CatImplClass = 0;
00821   if ((IC = dyn_cast<ObjCImplementationDecl>(ClassImpDecl))) {
00822     IDecl = IC->getClassInterface();
00823     // We always synthesize an interface for an implementation
00824     // without an interface decl. So, IDecl is always non-zero.
00825     assert(IDecl &&
00826            "ActOnPropertyImplDecl - @implementation without @interface");
00827 
00828     // Look for this property declaration in the @implementation's @interface
00829     property = IDecl->FindPropertyDeclaration(PropertyId);
00830     if (!property) {
00831       Diag(PropertyLoc, diag::error_bad_property_decl) << IDecl->getDeclName();
00832       return 0;
00833     }
00834     unsigned PIkind = property->getPropertyAttributesAsWritten();
00835     if ((PIkind & (ObjCPropertyDecl::OBJC_PR_atomic |
00836                    ObjCPropertyDecl::OBJC_PR_nonatomic) ) == 0) {
00837       if (AtLoc.isValid())
00838         Diag(AtLoc, diag::warn_implicit_atomic_property);
00839       else
00840         Diag(IC->getLocation(), diag::warn_auto_implicit_atomic_property);
00841       Diag(property->getLocation(), diag::note_property_declare);
00842     }
00843     
00844     if (const ObjCCategoryDecl *CD =
00845         dyn_cast<ObjCCategoryDecl>(property->getDeclContext())) {
00846       if (!CD->IsClassExtension()) {
00847         Diag(PropertyLoc, diag::error_category_property) << CD->getDeclName();
00848         Diag(property->getLocation(), diag::note_property_declare);
00849         return 0;
00850       }
00851     }
00852     if (Synthesize&&
00853         (PIkind & ObjCPropertyDecl::OBJC_PR_readonly) &&
00854         property->hasAttr<IBOutletAttr>() &&
00855         !AtLoc.isValid()) {
00856       bool ReadWriteProperty = false;
00857       // Search into the class extensions and see if 'readonly property is
00858       // redeclared 'readwrite', then no warning is to be issued.
00859       for (auto *Ext : IDecl->known_extensions()) {
00860         DeclContext::lookup_result R = Ext->lookup(property->getDeclName());
00861         if (!R.empty())
00862           if (ObjCPropertyDecl *ExtProp = dyn_cast<ObjCPropertyDecl>(R[0])) {
00863             PIkind = ExtProp->getPropertyAttributesAsWritten();
00864             if (PIkind & ObjCPropertyDecl::OBJC_PR_readwrite) {
00865               ReadWriteProperty = true;
00866               break;
00867             }
00868           }
00869       }
00870       
00871       if (!ReadWriteProperty) {
00872         Diag(property->getLocation(), diag::warn_auto_readonly_iboutlet_property)
00873             << property;
00874         SourceLocation readonlyLoc;
00875         if (LocPropertyAttribute(Context, "readonly", 
00876                                  property->getLParenLoc(), readonlyLoc)) {
00877           SourceLocation endLoc = 
00878             readonlyLoc.getLocWithOffset(strlen("readonly")-1);
00879           SourceRange ReadonlySourceRange(readonlyLoc, endLoc);
00880           Diag(property->getLocation(), 
00881                diag::note_auto_readonly_iboutlet_fixup_suggest) <<
00882           FixItHint::CreateReplacement(ReadonlySourceRange, "readwrite");
00883         }
00884       }
00885     }
00886     if (Synthesize && isa<ObjCProtocolDecl>(property->getDeclContext()))
00887       DiagnosePropertyMismatchDeclInProtocols(*this, AtLoc, IDecl, property);
00888         
00889   } else if ((CatImplClass = dyn_cast<ObjCCategoryImplDecl>(ClassImpDecl))) {
00890     if (Synthesize) {
00891       Diag(AtLoc, diag::error_synthesize_category_decl);
00892       return 0;
00893     }
00894     IDecl = CatImplClass->getClassInterface();
00895     if (!IDecl) {
00896       Diag(AtLoc, diag::error_missing_property_interface);
00897       return 0;
00898     }
00899     ObjCCategoryDecl *Category =
00900     IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier());
00901 
00902     // If category for this implementation not found, it is an error which
00903     // has already been reported eralier.
00904     if (!Category)
00905       return 0;
00906     // Look for this property declaration in @implementation's category
00907     property = Category->FindPropertyDeclaration(PropertyId);
00908     if (!property) {
00909       Diag(PropertyLoc, diag::error_bad_category_property_decl)
00910       << Category->getDeclName();
00911       return 0;
00912     }
00913   } else {
00914     Diag(AtLoc, diag::error_bad_property_context);
00915     return 0;
00916   }
00917   ObjCIvarDecl *Ivar = 0;
00918   bool CompleteTypeErr = false;
00919   bool compat = true;
00920   // Check that we have a valid, previously declared ivar for @synthesize
00921   if (Synthesize) {
00922     // @synthesize
00923     if (!PropertyIvar)
00924       PropertyIvar = PropertyId;
00925     // Check that this is a previously declared 'ivar' in 'IDecl' interface
00926     ObjCInterfaceDecl *ClassDeclared;
00927     Ivar = IDecl->lookupInstanceVariable(PropertyIvar, ClassDeclared);
00928     QualType PropType = property->getType();
00929     QualType PropertyIvarType = PropType.getNonReferenceType();
00930 
00931     if (RequireCompleteType(PropertyDiagLoc, PropertyIvarType,
00932                             diag::err_incomplete_synthesized_property,
00933                             property->getDeclName())) {
00934       Diag(property->getLocation(), diag::note_property_declare);
00935       CompleteTypeErr = true;
00936     }
00937 
00938     if (getLangOpts().ObjCAutoRefCount &&
00939         (property->getPropertyAttributesAsWritten() &
00940          ObjCPropertyDecl::OBJC_PR_readonly) &&
00941         PropertyIvarType->isObjCRetainableType()) {
00942       setImpliedPropertyAttributeForReadOnlyProperty(property, Ivar);    
00943     }
00944     
00945     ObjCPropertyDecl::PropertyAttributeKind kind 
00946       = property->getPropertyAttributes();
00947 
00948     // Add GC __weak to the ivar type if the property is weak.
00949     if ((kind & ObjCPropertyDecl::OBJC_PR_weak) && 
00950         getLangOpts().getGC() != LangOptions::NonGC) {
00951       assert(!getLangOpts().ObjCAutoRefCount);
00952       if (PropertyIvarType.isObjCGCStrong()) {
00953         Diag(PropertyDiagLoc, diag::err_gc_weak_property_strong_type);
00954         Diag(property->getLocation(), diag::note_property_declare);
00955       } else {
00956         PropertyIvarType =
00957           Context.getObjCGCQualType(PropertyIvarType, Qualifiers::Weak);
00958       }
00959     }
00960     if (AtLoc.isInvalid()) {
00961       // Check when default synthesizing a property that there is 
00962       // an ivar matching property name and issue warning; since this
00963       // is the most common case of not using an ivar used for backing
00964       // property in non-default synthesis case.
00965       ObjCInterfaceDecl *ClassDeclared=0;
00966       ObjCIvarDecl *originalIvar = 
00967       IDecl->lookupInstanceVariable(property->getIdentifier(), 
00968                                     ClassDeclared);
00969       if (originalIvar) {
00970         Diag(PropertyDiagLoc, 
00971              diag::warn_autosynthesis_property_ivar_match)
00972         << PropertyId << (Ivar == 0) << PropertyIvar 
00973         << originalIvar->getIdentifier();
00974         Diag(property->getLocation(), diag::note_property_declare);
00975         Diag(originalIvar->getLocation(), diag::note_ivar_decl);
00976       }
00977     }
00978     
00979     if (!Ivar) {
00980       // In ARC, give the ivar a lifetime qualifier based on the
00981       // property attributes.
00982       if (getLangOpts().ObjCAutoRefCount &&
00983           !PropertyIvarType.getObjCLifetime() &&
00984           PropertyIvarType->isObjCRetainableType()) {
00985 
00986         // It's an error if we have to do this and the user didn't
00987         // explicitly write an ownership attribute on the property.
00988         if (!property->hasWrittenStorageAttribute() &&
00989             !(kind & ObjCPropertyDecl::OBJC_PR_strong)) {
00990           Diag(PropertyDiagLoc,
00991                diag::err_arc_objc_property_default_assign_on_object);
00992           Diag(property->getLocation(), diag::note_property_declare);
00993         } else {
00994           Qualifiers::ObjCLifetime lifetime =
00995             getImpliedARCOwnership(kind, PropertyIvarType);
00996           assert(lifetime && "no lifetime for property?");
00997           if (lifetime == Qualifiers::OCL_Weak) {
00998             bool err = false;
00999             if (const ObjCObjectPointerType *ObjT =
01000                 PropertyIvarType->getAs<ObjCObjectPointerType>()) {
01001               const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl();
01002               if (ObjI && ObjI->isArcWeakrefUnavailable()) {
01003                 Diag(property->getLocation(),
01004                      diag::err_arc_weak_unavailable_property) << PropertyIvarType;
01005                 Diag(ClassImpDecl->getLocation(), diag::note_implemented_by_class)
01006                   << ClassImpDecl->getName();
01007                 err = true;
01008               }
01009             }
01010             if (!err && !getLangOpts().ObjCARCWeak) {
01011               Diag(PropertyDiagLoc, diag::err_arc_weak_no_runtime);
01012               Diag(property->getLocation(), diag::note_property_declare);
01013             }
01014           }
01015           
01016           Qualifiers qs;
01017           qs.addObjCLifetime(lifetime);
01018           PropertyIvarType = Context.getQualifiedType(PropertyIvarType, qs);   
01019         }
01020       }
01021 
01022       if (kind & ObjCPropertyDecl::OBJC_PR_weak &&
01023           !getLangOpts().ObjCAutoRefCount &&
01024           getLangOpts().getGC() == LangOptions::NonGC) {
01025         Diag(PropertyDiagLoc, diag::error_synthesize_weak_non_arc_or_gc);
01026         Diag(property->getLocation(), diag::note_property_declare);
01027       }
01028 
01029       Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
01030                                   PropertyIvarLoc,PropertyIvarLoc, PropertyIvar,
01031                                   PropertyIvarType, /*Dinfo=*/0,
01032                                   ObjCIvarDecl::Private,
01033                                   (Expr *)0, true);
01034       if (RequireNonAbstractType(PropertyIvarLoc,
01035                                  PropertyIvarType,
01036                                  diag::err_abstract_type_in_decl,
01037                                  AbstractSynthesizedIvarType)) {
01038         Diag(property->getLocation(), diag::note_property_declare);
01039         Ivar->setInvalidDecl();
01040       } else if (CompleteTypeErr)
01041           Ivar->setInvalidDecl();
01042       ClassImpDecl->addDecl(Ivar);
01043       IDecl->makeDeclVisibleInContext(Ivar);
01044 
01045       if (getLangOpts().ObjCRuntime.isFragile())
01046         Diag(PropertyDiagLoc, diag::error_missing_property_ivar_decl)
01047             << PropertyId;
01048       // Note! I deliberately want it to fall thru so, we have a
01049       // a property implementation and to avoid future warnings.
01050     } else if (getLangOpts().ObjCRuntime.isNonFragile() &&
01051                !declaresSameEntity(ClassDeclared, IDecl)) {
01052       Diag(PropertyDiagLoc, diag::error_ivar_in_superclass_use)
01053       << property->getDeclName() << Ivar->getDeclName()
01054       << ClassDeclared->getDeclName();
01055       Diag(Ivar->getLocation(), diag::note_previous_access_declaration)
01056       << Ivar << Ivar->getName();
01057       // Note! I deliberately want it to fall thru so more errors are caught.
01058     }
01059     property->setPropertyIvarDecl(Ivar);
01060 
01061     QualType IvarType = Context.getCanonicalType(Ivar->getType());
01062 
01063     // Check that type of property and its ivar are type compatible.
01064     if (!Context.hasSameType(PropertyIvarType, IvarType)) {
01065       if (isa<ObjCObjectPointerType>(PropertyIvarType) 
01066           && isa<ObjCObjectPointerType>(IvarType))
01067         compat =
01068           Context.canAssignObjCInterfaces(
01069                                   PropertyIvarType->getAs<ObjCObjectPointerType>(),
01070                                   IvarType->getAs<ObjCObjectPointerType>());
01071       else {
01072         compat = (CheckAssignmentConstraints(PropertyIvarLoc, PropertyIvarType,
01073                                              IvarType)
01074                     == Compatible);
01075       }
01076       if (!compat) {
01077         Diag(PropertyDiagLoc, diag::error_property_ivar_type)
01078           << property->getDeclName() << PropType
01079           << Ivar->getDeclName() << IvarType;
01080         Diag(Ivar->getLocation(), diag::note_ivar_decl);
01081         // Note! I deliberately want it to fall thru so, we have a
01082         // a property implementation and to avoid future warnings.
01083       }
01084       else {
01085         // FIXME! Rules for properties are somewhat different that those
01086         // for assignments. Use a new routine to consolidate all cases;
01087         // specifically for property redeclarations as well as for ivars.
01088         QualType lhsType =Context.getCanonicalType(PropertyIvarType).getUnqualifiedType();
01089         QualType rhsType =Context.getCanonicalType(IvarType).getUnqualifiedType();
01090         if (lhsType != rhsType &&
01091             lhsType->isArithmeticType()) {
01092           Diag(PropertyDiagLoc, diag::error_property_ivar_type)
01093             << property->getDeclName() << PropType
01094             << Ivar->getDeclName() << IvarType;
01095           Diag(Ivar->getLocation(), diag::note_ivar_decl);
01096           // Fall thru - see previous comment
01097         }
01098       }
01099       // __weak is explicit. So it works on Canonical type.
01100       if ((PropType.isObjCGCWeak() && !IvarType.isObjCGCWeak() &&
01101            getLangOpts().getGC() != LangOptions::NonGC)) {
01102         Diag(PropertyDiagLoc, diag::error_weak_property)
01103         << property->getDeclName() << Ivar->getDeclName();
01104         Diag(Ivar->getLocation(), diag::note_ivar_decl);
01105         // Fall thru - see previous comment
01106       }
01107       // Fall thru - see previous comment
01108       if ((property->getType()->isObjCObjectPointerType() ||
01109            PropType.isObjCGCStrong()) && IvarType.isObjCGCWeak() &&
01110           getLangOpts().getGC() != LangOptions::NonGC) {
01111         Diag(PropertyDiagLoc, diag::error_strong_property)
01112         << property->getDeclName() << Ivar->getDeclName();
01113         // Fall thru - see previous comment
01114       }
01115     }
01116     if (getLangOpts().ObjCAutoRefCount)
01117       checkARCPropertyImpl(*this, PropertyLoc, property, Ivar);
01118   } else if (PropertyIvar)
01119     // @dynamic
01120     Diag(PropertyDiagLoc, diag::error_dynamic_property_ivar_decl);
01121     
01122   assert (property && "ActOnPropertyImplDecl - property declaration missing");
01123   ObjCPropertyImplDecl *PIDecl =
01124   ObjCPropertyImplDecl::Create(Context, CurContext, AtLoc, PropertyLoc,
01125                                property,
01126                                (Synthesize ?
01127                                 ObjCPropertyImplDecl::Synthesize
01128                                 : ObjCPropertyImplDecl::Dynamic),
01129                                Ivar, PropertyIvarLoc);
01130 
01131   if (CompleteTypeErr || !compat)
01132     PIDecl->setInvalidDecl();
01133 
01134   if (ObjCMethodDecl *getterMethod = property->getGetterMethodDecl()) {
01135     getterMethod->createImplicitParams(Context, IDecl);
01136     if (getLangOpts().CPlusPlus && Synthesize && !CompleteTypeErr &&
01137         Ivar->getType()->isRecordType()) {
01138       // For Objective-C++, need to synthesize the AST for the IVAR object to be
01139       // returned by the getter as it must conform to C++'s copy-return rules.
01140       // FIXME. Eventually we want to do this for Objective-C as well.
01141       SynthesizedFunctionScope Scope(*this, getterMethod);
01142       ImplicitParamDecl *SelfDecl = getterMethod->getSelfDecl();
01143       DeclRefExpr *SelfExpr = 
01144         new (Context) DeclRefExpr(SelfDecl, false, SelfDecl->getType(),
01145                                   VK_LValue, PropertyDiagLoc);
01146       MarkDeclRefReferenced(SelfExpr);
01147       Expr *LoadSelfExpr =
01148         ImplicitCastExpr::Create(Context, SelfDecl->getType(),
01149                                  CK_LValueToRValue, SelfExpr, 0, VK_RValue);
01150       Expr *IvarRefExpr =
01151         new (Context) ObjCIvarRefExpr(Ivar, Ivar->getType(), PropertyDiagLoc,
01152                                       Ivar->getLocation(),
01153                                       LoadSelfExpr, true, true);
01154       ExprResult Res = PerformCopyInitialization(
01155           InitializedEntity::InitializeResult(PropertyDiagLoc,
01156                                               getterMethod->getReturnType(),
01157                                               /*NRVO=*/false),
01158           PropertyDiagLoc, Owned(IvarRefExpr));
01159       if (!Res.isInvalid()) {
01160         Expr *ResExpr = Res.takeAs<Expr>();
01161         if (ResExpr)
01162           ResExpr = MaybeCreateExprWithCleanups(ResExpr);
01163         PIDecl->setGetterCXXConstructor(ResExpr);
01164       }
01165     }
01166     if (property->hasAttr<NSReturnsNotRetainedAttr>() &&
01167         !getterMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
01168       Diag(getterMethod->getLocation(), 
01169            diag::warn_property_getter_owning_mismatch);
01170       Diag(property->getLocation(), diag::note_property_declare);
01171     }
01172     if (getLangOpts().ObjCAutoRefCount && Synthesize)
01173       switch (getterMethod->getMethodFamily()) {
01174         case OMF_retain:
01175         case OMF_retainCount:
01176         case OMF_release:
01177         case OMF_autorelease:
01178           Diag(getterMethod->getLocation(), diag::err_arc_illegal_method_def)
01179             << 1 << getterMethod->getSelector();
01180           break;
01181         default:
01182           break;
01183       }
01184   }
01185   if (ObjCMethodDecl *setterMethod = property->getSetterMethodDecl()) {
01186     setterMethod->createImplicitParams(Context, IDecl);
01187     if (getLangOpts().CPlusPlus && Synthesize && !CompleteTypeErr &&
01188         Ivar->getType()->isRecordType()) {
01189       // FIXME. Eventually we want to do this for Objective-C as well.
01190       SynthesizedFunctionScope Scope(*this, setterMethod);
01191       ImplicitParamDecl *SelfDecl = setterMethod->getSelfDecl();
01192       DeclRefExpr *SelfExpr = 
01193         new (Context) DeclRefExpr(SelfDecl, false, SelfDecl->getType(),
01194                                   VK_LValue, PropertyDiagLoc);
01195       MarkDeclRefReferenced(SelfExpr);
01196       Expr *LoadSelfExpr =
01197         ImplicitCastExpr::Create(Context, SelfDecl->getType(),
01198                                  CK_LValueToRValue, SelfExpr, 0, VK_RValue);
01199       Expr *lhs =
01200         new (Context) ObjCIvarRefExpr(Ivar, Ivar->getType(), PropertyDiagLoc,
01201                                       Ivar->getLocation(),
01202                                       LoadSelfExpr, true, true);
01203       ObjCMethodDecl::param_iterator P = setterMethod->param_begin();
01204       ParmVarDecl *Param = (*P);
01205       QualType T = Param->getType().getNonReferenceType();
01206       DeclRefExpr *rhs = new (Context) DeclRefExpr(Param, false, T,
01207                                                    VK_LValue, PropertyDiagLoc);
01208       MarkDeclRefReferenced(rhs);
01209       ExprResult Res = BuildBinOp(S, PropertyDiagLoc, 
01210                                   BO_Assign, lhs, rhs);
01211       if (property->getPropertyAttributes() & 
01212           ObjCPropertyDecl::OBJC_PR_atomic) {
01213         Expr *callExpr = Res.takeAs<Expr>();
01214         if (const CXXOperatorCallExpr *CXXCE = 
01215               dyn_cast_or_null<CXXOperatorCallExpr>(callExpr))
01216           if (const FunctionDecl *FuncDecl = CXXCE->getDirectCallee())
01217             if (!FuncDecl->isTrivial())
01218               if (property->getType()->isReferenceType()) {
01219                 Diag(PropertyDiagLoc, 
01220                      diag::err_atomic_property_nontrivial_assign_op)
01221                     << property->getType();
01222                 Diag(FuncDecl->getLocStart(), 
01223                      diag::note_callee_decl) << FuncDecl;
01224               }
01225       }
01226       PIDecl->setSetterCXXAssignment(Res.takeAs<Expr>());
01227     }
01228   }
01229   
01230   if (IC) {
01231     if (Synthesize)
01232       if (ObjCPropertyImplDecl *PPIDecl =
01233           IC->FindPropertyImplIvarDecl(PropertyIvar)) {
01234         Diag(PropertyLoc, diag::error_duplicate_ivar_use)
01235         << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
01236         << PropertyIvar;
01237         Diag(PPIDecl->getLocation(), diag::note_previous_use);
01238       }
01239 
01240     if (ObjCPropertyImplDecl *PPIDecl
01241         = IC->FindPropertyImplDecl(PropertyId)) {
01242       Diag(PropertyLoc, diag::error_property_implemented) << PropertyId;
01243       Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
01244       return 0;
01245     }
01246     IC->addPropertyImplementation(PIDecl);
01247     if (getLangOpts().ObjCDefaultSynthProperties &&
01248         getLangOpts().ObjCRuntime.isNonFragile() &&
01249         !IDecl->isObjCRequiresPropertyDefs()) {
01250       // Diagnose if an ivar was lazily synthesdized due to a previous
01251       // use and if 1) property is @dynamic or 2) property is synthesized
01252       // but it requires an ivar of different name.
01253       ObjCInterfaceDecl *ClassDeclared=0;
01254       ObjCIvarDecl *Ivar = 0;
01255       if (!Synthesize)
01256         Ivar = IDecl->lookupInstanceVariable(PropertyId, ClassDeclared);
01257       else {
01258         if (PropertyIvar && PropertyIvar != PropertyId)
01259           Ivar = IDecl->lookupInstanceVariable(PropertyId, ClassDeclared);
01260       }
01261       // Issue diagnostics only if Ivar belongs to current class.
01262       if (Ivar && Ivar->getSynthesize() && 
01263           declaresSameEntity(IC->getClassInterface(), ClassDeclared)) {
01264         Diag(Ivar->getLocation(), diag::err_undeclared_var_use) 
01265         << PropertyId;
01266         Ivar->setInvalidDecl();
01267       }
01268     }
01269   } else {
01270     if (Synthesize)
01271       if (ObjCPropertyImplDecl *PPIDecl =
01272           CatImplClass->FindPropertyImplIvarDecl(PropertyIvar)) {
01273         Diag(PropertyDiagLoc, diag::error_duplicate_ivar_use)
01274         << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
01275         << PropertyIvar;
01276         Diag(PPIDecl->getLocation(), diag::note_previous_use);
01277       }
01278 
01279     if (ObjCPropertyImplDecl *PPIDecl =
01280         CatImplClass->FindPropertyImplDecl(PropertyId)) {
01281       Diag(PropertyDiagLoc, diag::error_property_implemented) << PropertyId;
01282       Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
01283       return 0;
01284     }
01285     CatImplClass->addPropertyImplementation(PIDecl);
01286   }
01287 
01288   return PIDecl;
01289 }
01290 
01291 //===----------------------------------------------------------------------===//
01292 // Helper methods.
01293 //===----------------------------------------------------------------------===//
01294 
01295 /// DiagnosePropertyMismatch - Compares two properties for their
01296 /// attributes and types and warns on a variety of inconsistencies.
01297 ///
01298 void
01299 Sema::DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
01300                                ObjCPropertyDecl *SuperProperty,
01301                                const IdentifierInfo *inheritedName,
01302                                bool OverridingProtocolProperty) {
01303   ObjCPropertyDecl::PropertyAttributeKind CAttr =
01304     Property->getPropertyAttributes();
01305   ObjCPropertyDecl::PropertyAttributeKind SAttr =
01306     SuperProperty->getPropertyAttributes();
01307   
01308   // We allow readonly properties without an explicit ownership
01309   // (assign/unsafe_unretained/weak/retain/strong/copy) in super class
01310   // to be overridden by a property with any explicit ownership in the subclass.
01311   if (!OverridingProtocolProperty &&
01312       !getOwnershipRule(SAttr) && getOwnershipRule(CAttr))
01313     ;
01314   else {
01315     if ((CAttr & ObjCPropertyDecl::OBJC_PR_readonly)
01316         && (SAttr & ObjCPropertyDecl::OBJC_PR_readwrite))
01317       Diag(Property->getLocation(), diag::warn_readonly_property)
01318         << Property->getDeclName() << inheritedName;
01319     if ((CAttr & ObjCPropertyDecl::OBJC_PR_copy)
01320         != (SAttr & ObjCPropertyDecl::OBJC_PR_copy))
01321       Diag(Property->getLocation(), diag::warn_property_attribute)
01322         << Property->getDeclName() << "copy" << inheritedName;
01323     else if (!(SAttr & ObjCPropertyDecl::OBJC_PR_readonly)){
01324       unsigned CAttrRetain =
01325         (CAttr &
01326          (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_strong));
01327       unsigned SAttrRetain =
01328         (SAttr &
01329          (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_strong));
01330       bool CStrong = (CAttrRetain != 0);
01331       bool SStrong = (SAttrRetain != 0);
01332       if (CStrong != SStrong)
01333         Diag(Property->getLocation(), diag::warn_property_attribute)
01334           << Property->getDeclName() << "retain (or strong)" << inheritedName;
01335     }
01336   }
01337 
01338   if ((CAttr & ObjCPropertyDecl::OBJC_PR_nonatomic)
01339       != (SAttr & ObjCPropertyDecl::OBJC_PR_nonatomic)) {
01340     Diag(Property->getLocation(), diag::warn_property_attribute)
01341       << Property->getDeclName() << "atomic" << inheritedName;
01342     Diag(SuperProperty->getLocation(), diag::note_property_declare);
01343   }
01344   if (Property->getSetterName() != SuperProperty->getSetterName()) {
01345     Diag(Property->getLocation(), diag::warn_property_attribute)
01346       << Property->getDeclName() << "setter" << inheritedName;
01347     Diag(SuperProperty->getLocation(), diag::note_property_declare);
01348   }
01349   if (Property->getGetterName() != SuperProperty->getGetterName()) {
01350     Diag(Property->getLocation(), diag::warn_property_attribute)
01351       << Property->getDeclName() << "getter" << inheritedName;
01352     Diag(SuperProperty->getLocation(), diag::note_property_declare);
01353   }
01354 
01355   QualType LHSType =
01356     Context.getCanonicalType(SuperProperty->getType());
01357   QualType RHSType =
01358     Context.getCanonicalType(Property->getType());
01359 
01360   if (!Context.propertyTypesAreCompatible(LHSType, RHSType)) {
01361     // Do cases not handled in above.
01362     // FIXME. For future support of covariant property types, revisit this.
01363     bool IncompatibleObjC = false;
01364     QualType ConvertedType;
01365     if (!isObjCPointerConversion(RHSType, LHSType, 
01366                                  ConvertedType, IncompatibleObjC) ||
01367         IncompatibleObjC) {
01368         Diag(Property->getLocation(), diag::warn_property_types_are_incompatible)
01369         << Property->getType() << SuperProperty->getType() << inheritedName;
01370       Diag(SuperProperty->getLocation(), diag::note_property_declare);
01371     }
01372   }
01373 }
01374 
01375 bool Sema::DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *property,
01376                                             ObjCMethodDecl *GetterMethod,
01377                                             SourceLocation Loc) {
01378   if (!GetterMethod)
01379     return false;
01380   QualType GetterType = GetterMethod->getReturnType().getNonReferenceType();
01381   QualType PropertyIvarType = property->getType().getNonReferenceType();
01382   bool compat = Context.hasSameType(PropertyIvarType, GetterType);
01383   if (!compat) {
01384     if (isa<ObjCObjectPointerType>(PropertyIvarType) && 
01385         isa<ObjCObjectPointerType>(GetterType))
01386       compat =
01387         Context.canAssignObjCInterfaces(
01388                                       GetterType->getAs<ObjCObjectPointerType>(),
01389                                       PropertyIvarType->getAs<ObjCObjectPointerType>());
01390     else if (CheckAssignmentConstraints(Loc, GetterType, PropertyIvarType) 
01391               != Compatible) {
01392           Diag(Loc, diag::error_property_accessor_type)
01393             << property->getDeclName() << PropertyIvarType
01394             << GetterMethod->getSelector() << GetterType;
01395           Diag(GetterMethod->getLocation(), diag::note_declared_at);
01396           return true;
01397     } else {
01398       compat = true;
01399       QualType lhsType =Context.getCanonicalType(PropertyIvarType).getUnqualifiedType();
01400       QualType rhsType =Context.getCanonicalType(GetterType).getUnqualifiedType();
01401       if (lhsType != rhsType && lhsType->isArithmeticType())
01402         compat = false;
01403     }
01404   }
01405   
01406   if (!compat) {
01407     Diag(Loc, diag::warn_accessor_property_type_mismatch)
01408     << property->getDeclName()
01409     << GetterMethod->getSelector();
01410     Diag(GetterMethod->getLocation(), diag::note_declared_at);
01411     return true;
01412   }
01413 
01414   return false;
01415 }
01416 
01417 /// CollectImmediateProperties - This routine collects all properties in
01418 /// the class and its conforming protocols; but not those in its super class.
01419 static void CollectImmediateProperties(ObjCContainerDecl *CDecl,
01420                                        ObjCContainerDecl::PropertyMap &PropMap,
01421                                        ObjCContainerDecl::PropertyMap &SuperPropMap,
01422                                        bool IncludeProtocols = true) {
01423 
01424   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
01425     for (auto *Prop : IDecl->properties())
01426       PropMap[Prop->getIdentifier()] = Prop;
01427     if (IncludeProtocols) {
01428       // Scan through class's protocols.
01429       for (auto *PI : IDecl->all_referenced_protocols())
01430         CollectImmediateProperties(PI, PropMap, SuperPropMap);
01431     }
01432   }
01433   if (ObjCCategoryDecl *CATDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) {
01434     if (!CATDecl->IsClassExtension())
01435       for (auto *Prop : CATDecl->properties())
01436         PropMap[Prop->getIdentifier()] = Prop;
01437     if (IncludeProtocols) {
01438       // Scan through class's protocols.
01439       for (auto *PI : CATDecl->protocols())
01440         CollectImmediateProperties(PI, PropMap, SuperPropMap);
01441     }
01442   }
01443   else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(CDecl)) {
01444     for (auto *Prop : PDecl->properties()) {
01445       ObjCPropertyDecl *PropertyFromSuper = SuperPropMap[Prop->getIdentifier()];
01446       // Exclude property for protocols which conform to class's super-class, 
01447       // as super-class has to implement the property.
01448       if (!PropertyFromSuper || 
01449           PropertyFromSuper->getIdentifier() != Prop->getIdentifier()) {
01450         ObjCPropertyDecl *&PropEntry = PropMap[Prop->getIdentifier()];
01451         if (!PropEntry)
01452           PropEntry = Prop;
01453       }
01454     }
01455     // scan through protocol's protocols.
01456     for (auto *PI : PDecl->protocols())
01457       CollectImmediateProperties(PI, PropMap, SuperPropMap);
01458   }
01459 }
01460 
01461 /// CollectSuperClassPropertyImplementations - This routine collects list of
01462 /// properties to be implemented in super class(s) and also coming from their
01463 /// conforming protocols.
01464 static void CollectSuperClassPropertyImplementations(ObjCInterfaceDecl *CDecl,
01465                                     ObjCInterfaceDecl::PropertyMap &PropMap) {
01466   if (ObjCInterfaceDecl *SDecl = CDecl->getSuperClass()) {
01467     ObjCInterfaceDecl::PropertyDeclOrder PO;
01468     while (SDecl) {
01469       SDecl->collectPropertiesToImplement(PropMap, PO);
01470       SDecl = SDecl->getSuperClass();
01471     }
01472   }
01473 }
01474 
01475 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
01476 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
01477 /// declared in class 'IFace'.
01478 bool
01479 Sema::IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
01480                                      ObjCMethodDecl *Method, ObjCIvarDecl *IV) {
01481   if (!IV->getSynthesize())
01482     return false;
01483   ObjCMethodDecl *IMD = IFace->lookupMethod(Method->getSelector(),
01484                                             Method->isInstanceMethod());
01485   if (!IMD || !IMD->isPropertyAccessor())
01486     return false;
01487   
01488   // look up a property declaration whose one of its accessors is implemented
01489   // by this method.
01490   for (const auto *Property : IFace->properties()) {
01491     if ((Property->getGetterName() == IMD->getSelector() ||
01492          Property->getSetterName() == IMD->getSelector()) &&
01493         (Property->getPropertyIvarDecl() == IV))
01494       return true;
01495   }
01496   return false;
01497 }
01498 
01499 static bool SuperClassImplementsProperty(ObjCInterfaceDecl *IDecl,
01500                                          ObjCPropertyDecl *Prop) {
01501   bool SuperClassImplementsGetter = false;
01502   bool SuperClassImplementsSetter = false;
01503   if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readonly)
01504     SuperClassImplementsSetter = true;
01505 
01506   while (IDecl->getSuperClass()) {
01507     ObjCInterfaceDecl *SDecl = IDecl->getSuperClass();
01508     if (!SuperClassImplementsGetter && SDecl->getInstanceMethod(Prop->getGetterName()))
01509       SuperClassImplementsGetter = true;
01510 
01511     if (!SuperClassImplementsSetter && SDecl->getInstanceMethod(Prop->getSetterName()))
01512       SuperClassImplementsSetter = true;
01513     if (SuperClassImplementsGetter && SuperClassImplementsSetter)
01514       return true;
01515     IDecl = IDecl->getSuperClass();
01516   }
01517   return false;
01518 }
01519 
01520 /// \brief Default synthesizes all properties which must be synthesized
01521 /// in class's \@implementation.
01522 void Sema::DefaultSynthesizeProperties(Scope *S, ObjCImplDecl* IMPDecl,
01523                                        ObjCInterfaceDecl *IDecl) {
01524   
01525   ObjCInterfaceDecl::PropertyMap PropMap;
01526   ObjCInterfaceDecl::PropertyDeclOrder PropertyOrder;
01527   IDecl->collectPropertiesToImplement(PropMap, PropertyOrder);
01528   if (PropMap.empty())
01529     return;
01530   ObjCInterfaceDecl::PropertyMap SuperPropMap;
01531   CollectSuperClassPropertyImplementations(IDecl, SuperPropMap);
01532   
01533   for (unsigned i = 0, e = PropertyOrder.size(); i != e; i++) {
01534     ObjCPropertyDecl *Prop = PropertyOrder[i];
01535     // Is there a matching property synthesize/dynamic?
01536     if (Prop->isInvalidDecl() ||
01537         Prop->getPropertyImplementation() == ObjCPropertyDecl::Optional)
01538       continue;
01539     // Property may have been synthesized by user.
01540     if (IMPDecl->FindPropertyImplDecl(Prop->getIdentifier()))
01541       continue;
01542     if (IMPDecl->getInstanceMethod(Prop->getGetterName())) {
01543       if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readonly)
01544         continue;
01545       if (IMPDecl->getInstanceMethod(Prop->getSetterName()))
01546         continue;
01547     }
01548     // If property to be implemented in the super class, ignore.
01549     if (SuperPropMap[Prop->getIdentifier()]) {
01550       ObjCPropertyDecl *PropInSuperClass = SuperPropMap[Prop->getIdentifier()];
01551       if ((Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readwrite) &&
01552           (PropInSuperClass->getPropertyAttributes() &
01553            ObjCPropertyDecl::OBJC_PR_readonly) &&
01554           !IMPDecl->getInstanceMethod(Prop->getSetterName()) &&
01555           !IDecl->HasUserDeclaredSetterMethod(Prop)) {
01556             Diag(Prop->getLocation(), diag::warn_no_autosynthesis_property)
01557               << Prop->getIdentifier();
01558             Diag(PropInSuperClass->getLocation(), diag::note_property_declare);
01559       }
01560       continue;
01561     }
01562     if (ObjCPropertyImplDecl *PID =
01563         IMPDecl->FindPropertyImplIvarDecl(Prop->getIdentifier())) {
01564       if (PID->getPropertyDecl() != Prop) {
01565         Diag(Prop->getLocation(), diag::warn_no_autosynthesis_shared_ivar_property)
01566           << Prop->getIdentifier();
01567         if (!PID->getLocation().isInvalid())
01568           Diag(PID->getLocation(), diag::note_property_synthesize);
01569       }
01570       continue;
01571     }
01572     if (ObjCProtocolDecl *Proto =
01573           dyn_cast<ObjCProtocolDecl>(Prop->getDeclContext())) {
01574       // We won't auto-synthesize properties declared in protocols.
01575       // Suppress the warning if class's superclass implements property's
01576       // getter and implements property's setter (if readwrite property).
01577       if (!SuperClassImplementsProperty(IDecl, Prop)) {
01578         Diag(IMPDecl->getLocation(),
01579              diag::warn_auto_synthesizing_protocol_property)
01580           << Prop << Proto;
01581         Diag(Prop->getLocation(), diag::note_property_declare);
01582       }
01583       continue;
01584     }
01585 
01586     // We use invalid SourceLocations for the synthesized ivars since they
01587     // aren't really synthesized at a particular location; they just exist.
01588     // Saying that they are located at the @implementation isn't really going
01589     // to help users.
01590     ObjCPropertyImplDecl *PIDecl = dyn_cast_or_null<ObjCPropertyImplDecl>(
01591       ActOnPropertyImplDecl(S, SourceLocation(), SourceLocation(),
01592                             true,
01593                             /* property = */ Prop->getIdentifier(),
01594                             /* ivar = */ Prop->getDefaultSynthIvarName(Context),
01595                             Prop->getLocation()));
01596     if (PIDecl) {
01597       Diag(Prop->getLocation(), diag::warn_missing_explicit_synthesis);
01598       Diag(IMPDecl->getLocation(), diag::note_while_in_implementation);
01599     }
01600   }
01601 }
01602 
01603 void Sema::DefaultSynthesizeProperties(Scope *S, Decl *D) {
01604   if (!LangOpts.ObjCDefaultSynthProperties || LangOpts.ObjCRuntime.isFragile())
01605     return;
01606   ObjCImplementationDecl *IC=dyn_cast_or_null<ObjCImplementationDecl>(D);
01607   if (!IC)
01608     return;
01609   if (ObjCInterfaceDecl* IDecl = IC->getClassInterface())
01610     if (!IDecl->isObjCRequiresPropertyDefs())
01611       DefaultSynthesizeProperties(S, IC, IDecl);
01612 }
01613 
01614 static void DiagnoseUnimplementedAccessor(Sema &S,
01615                                           ObjCInterfaceDecl *PrimaryClass,
01616                                           Selector Method,
01617                                           ObjCImplDecl* IMPDecl,
01618                                           ObjCContainerDecl *CDecl,
01619                                           ObjCCategoryDecl *C,
01620                                           ObjCPropertyDecl *Prop,
01621                                           Sema::SelectorSet &SMap) {
01622   // When reporting on missing property setter/getter implementation in
01623   // categories, do not report when they are declared in primary class,
01624   // class's protocol, or one of it super classes. This is because,
01625   // the class is going to implement them.
01626   if (!SMap.count(Method) &&
01627       (PrimaryClass == 0 ||
01628        !PrimaryClass->lookupPropertyAccessor(Method, C))) {
01629         S.Diag(IMPDecl->getLocation(),
01630                isa<ObjCCategoryDecl>(CDecl) ?
01631                diag::warn_setter_getter_impl_required_in_category :
01632                diag::warn_setter_getter_impl_required)
01633             << Prop->getDeclName() << Method;
01634         S.Diag(Prop->getLocation(),
01635              diag::note_property_declare);
01636         if (S.LangOpts.ObjCDefaultSynthProperties &&
01637             S.LangOpts.ObjCRuntime.isNonFragile())
01638           if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CDecl))
01639             if (const ObjCInterfaceDecl *RID = ID->isObjCRequiresPropertyDefs())
01640             S.Diag(RID->getLocation(), diag::note_suppressed_class_declare);
01641       }
01642 }
01643 
01644 void Sema::DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
01645                                            ObjCContainerDecl *CDecl,
01646                                            bool SynthesizeProperties) {
01647   ObjCContainerDecl::PropertyMap PropMap;
01648   ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
01649 
01650   if (!SynthesizeProperties) {
01651     ObjCContainerDecl::PropertyMap NoNeedToImplPropMap;
01652     // Gather properties which need not be implemented in this class
01653     // or category.
01654     if (!IDecl)
01655       if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
01656         // For categories, no need to implement properties declared in
01657         // its primary class (and its super classes) if property is
01658         // declared in one of those containers.
01659         if ((IDecl = C->getClassInterface())) {
01660           ObjCInterfaceDecl::PropertyDeclOrder PO;
01661           IDecl->collectPropertiesToImplement(NoNeedToImplPropMap, PO);
01662         }
01663       }
01664     if (IDecl)
01665       CollectSuperClassPropertyImplementations(IDecl, NoNeedToImplPropMap);
01666     
01667     CollectImmediateProperties(CDecl, PropMap, NoNeedToImplPropMap);
01668   }
01669 
01670   // Scan the @interface to see if any of the protocols it adopts
01671   // require an explicit implementation, via attribute
01672   // 'objc_protocol_requires_explicit_implementation'.
01673   if (IDecl) {
01674     std::unique_ptr<ObjCContainerDecl::PropertyMap> LazyMap;
01675 
01676     for (auto *PDecl : IDecl->all_referenced_protocols()) {
01677       if (!PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
01678         continue;
01679       // Lazily construct a set of all the properties in the @interface
01680       // of the class, without looking at the superclass.  We cannot
01681       // use the call to CollectImmediateProperties() above as that
01682       // utilizes information fromt he super class's properties as well
01683       // as scans the adopted protocols.  This work only triggers for protocols
01684       // with the attribute, which is very rare, and only occurs when
01685       // analyzing the @implementation.
01686       if (!LazyMap) {
01687         ObjCContainerDecl::PropertyMap NoNeedToImplPropMap;
01688         LazyMap.reset(new ObjCContainerDecl::PropertyMap());
01689         CollectImmediateProperties(CDecl, *LazyMap, NoNeedToImplPropMap,
01690                                    /* IncludeProtocols */ false);
01691       }
01692       // Add the properties of 'PDecl' to the list of properties that
01693       // need to be implemented.
01694       for (auto *PropDecl : PDecl->properties()) {
01695         if ((*LazyMap)[PropDecl->getIdentifier()])
01696           continue;
01697         PropMap[PropDecl->getIdentifier()] = PropDecl;
01698       }
01699     }
01700   }
01701 
01702   if (PropMap.empty())
01703     return;
01704 
01705   llvm::DenseSet<ObjCPropertyDecl *> PropImplMap;
01706   for (const auto *I : IMPDecl->property_impls())
01707     PropImplMap.insert(I->getPropertyDecl());
01708 
01709   SelectorSet InsMap;
01710   // Collect property accessors implemented in current implementation.
01711   for (const auto *I : IMPDecl->instance_methods())
01712     InsMap.insert(I->getSelector());
01713   
01714   ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
01715   ObjCInterfaceDecl *PrimaryClass = 0;
01716   if (C && !C->IsClassExtension())
01717     if ((PrimaryClass = C->getClassInterface()))
01718       // Report unimplemented properties in the category as well.
01719       if (ObjCImplDecl *IMP = PrimaryClass->getImplementation()) {
01720         // When reporting on missing setter/getters, do not report when
01721         // setter/getter is implemented in category's primary class
01722         // implementation.
01723         for (const auto *I : IMP->instance_methods())
01724           InsMap.insert(I->getSelector());
01725       }
01726 
01727   for (ObjCContainerDecl::PropertyMap::iterator
01728        P = PropMap.begin(), E = PropMap.end(); P != E; ++P) {
01729     ObjCPropertyDecl *Prop = P->second;
01730     // Is there a matching propery synthesize/dynamic?
01731     if (Prop->isInvalidDecl() ||
01732         Prop->getPropertyImplementation() == ObjCPropertyDecl::Optional ||
01733         PropImplMap.count(Prop) ||
01734         Prop->getAvailability() == AR_Unavailable)
01735       continue;
01736 
01737     // Diagnose unimplemented getters and setters.
01738     DiagnoseUnimplementedAccessor(*this,
01739           PrimaryClass, Prop->getGetterName(), IMPDecl, CDecl, C, Prop, InsMap);
01740     if (!Prop->isReadOnly())
01741       DiagnoseUnimplementedAccessor(*this,
01742                                     PrimaryClass, Prop->getSetterName(),
01743                                     IMPDecl, CDecl, C, Prop, InsMap);
01744   }
01745 }
01746 
01747 void
01748 Sema::AtomicPropertySetterGetterRules (ObjCImplDecl* IMPDecl,
01749                                        ObjCContainerDecl* IDecl) {
01750   // Rules apply in non-GC mode only
01751   if (getLangOpts().getGC() != LangOptions::NonGC)
01752     return;
01753   for (const auto *Property : IDecl->properties()) {
01754     ObjCMethodDecl *GetterMethod = 0;
01755     ObjCMethodDecl *SetterMethod = 0;
01756     bool LookedUpGetterSetter = false;
01757 
01758     unsigned Attributes = Property->getPropertyAttributes();
01759     unsigned AttributesAsWritten = Property->getPropertyAttributesAsWritten();
01760 
01761     if (!(AttributesAsWritten & ObjCPropertyDecl::OBJC_PR_atomic) &&
01762         !(AttributesAsWritten & ObjCPropertyDecl::OBJC_PR_nonatomic)) {
01763       GetterMethod = IMPDecl->getInstanceMethod(Property->getGetterName());
01764       SetterMethod = IMPDecl->getInstanceMethod(Property->getSetterName());
01765       LookedUpGetterSetter = true;
01766       if (GetterMethod) {
01767         Diag(GetterMethod->getLocation(),
01768              diag::warn_default_atomic_custom_getter_setter)
01769           << Property->getIdentifier() << 0;
01770         Diag(Property->getLocation(), diag::note_property_declare);
01771       }
01772       if (SetterMethod) {
01773         Diag(SetterMethod->getLocation(),
01774              diag::warn_default_atomic_custom_getter_setter)
01775           << Property->getIdentifier() << 1;
01776         Diag(Property->getLocation(), diag::note_property_declare);
01777       }
01778     }
01779 
01780     // We only care about readwrite atomic property.
01781     if ((Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) ||
01782         !(Attributes & ObjCPropertyDecl::OBJC_PR_readwrite))
01783       continue;
01784     if (const ObjCPropertyImplDecl *PIDecl
01785          = IMPDecl->FindPropertyImplDecl(Property->getIdentifier())) {
01786       if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
01787         continue;
01788       if (!LookedUpGetterSetter) {
01789         GetterMethod = IMPDecl->getInstanceMethod(Property->getGetterName());
01790         SetterMethod = IMPDecl->getInstanceMethod(Property->getSetterName());
01791       }
01792       if ((GetterMethod && !SetterMethod) || (!GetterMethod && SetterMethod)) {
01793         SourceLocation MethodLoc =
01794           (GetterMethod ? GetterMethod->getLocation()
01795                         : SetterMethod->getLocation());
01796         Diag(MethodLoc, diag::warn_atomic_property_rule)
01797           << Property->getIdentifier() << (GetterMethod != 0)
01798           << (SetterMethod != 0);
01799         // fixit stuff.
01800         if (!AttributesAsWritten) {
01801           if (Property->getLParenLoc().isValid()) {
01802             // @property () ... case.
01803             SourceRange PropSourceRange(Property->getAtLoc(), 
01804                                         Property->getLParenLoc());
01805             Diag(Property->getLocation(), diag::note_atomic_property_fixup_suggest) <<
01806               FixItHint::CreateReplacement(PropSourceRange, "@property (nonatomic");
01807           }
01808           else {
01809             //@property id etc.
01810             SourceLocation endLoc = 
01811               Property->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
01812             endLoc = endLoc.getLocWithOffset(-1);
01813             SourceRange PropSourceRange(Property->getAtLoc(), endLoc);
01814             Diag(Property->getLocation(), diag::note_atomic_property_fixup_suggest) <<
01815               FixItHint::CreateReplacement(PropSourceRange, "@property (nonatomic) ");
01816           }
01817         }
01818         else if (!(AttributesAsWritten & ObjCPropertyDecl::OBJC_PR_atomic)) {
01819           // @property () ... case.
01820           SourceLocation endLoc = Property->getLParenLoc();
01821           SourceRange PropSourceRange(Property->getAtLoc(), endLoc);
01822           Diag(Property->getLocation(), diag::note_atomic_property_fixup_suggest) <<
01823            FixItHint::CreateReplacement(PropSourceRange, "@property (nonatomic, ");
01824         }
01825         else
01826           Diag(MethodLoc, diag::note_atomic_property_fixup_suggest);
01827         Diag(Property->getLocation(), diag::note_property_declare);
01828       }
01829     }
01830   }
01831 }
01832 
01833 void Sema::DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D) {
01834   if (getLangOpts().getGC() == LangOptions::GCOnly)
01835     return;
01836 
01837   for (const auto *PID : D->property_impls()) {
01838     const ObjCPropertyDecl *PD = PID->getPropertyDecl();
01839     if (PD && !PD->hasAttr<NSReturnsNotRetainedAttr>() &&
01840         !D->getInstanceMethod(PD->getGetterName())) {
01841       ObjCMethodDecl *method = PD->getGetterMethodDecl();
01842       if (!method)
01843         continue;
01844       ObjCMethodFamily family = method->getMethodFamily();
01845       if (family == OMF_alloc || family == OMF_copy ||
01846           family == OMF_mutableCopy || family == OMF_new) {
01847         if (getLangOpts().ObjCAutoRefCount)
01848           Diag(PD->getLocation(), diag::err_cocoa_naming_owned_rule);
01849         else
01850           Diag(PD->getLocation(), diag::warn_cocoa_naming_owned_rule);
01851       }
01852     }
01853   }
01854 }
01855 
01856 void Sema::DiagnoseMissingDesignatedInitOverrides(
01857                                             const ObjCImplementationDecl *ImplD,
01858                                             const ObjCInterfaceDecl *IFD) {
01859   assert(IFD->hasDesignatedInitializers());
01860   const ObjCInterfaceDecl *SuperD = IFD->getSuperClass();
01861   if (!SuperD)
01862     return;
01863 
01864   SelectorSet InitSelSet;
01865   for (const auto *I : ImplD->instance_methods())
01866     if (I->getMethodFamily() == OMF_init)
01867       InitSelSet.insert(I->getSelector());
01868 
01869   SmallVector<const ObjCMethodDecl *, 8> DesignatedInits;
01870   SuperD->getDesignatedInitializers(DesignatedInits);
01871   for (SmallVector<const ObjCMethodDecl *, 8>::iterator
01872          I = DesignatedInits.begin(), E = DesignatedInits.end(); I != E; ++I) {
01873     const ObjCMethodDecl *MD = *I;
01874     if (!InitSelSet.count(MD->getSelector())) {
01875       Diag(ImplD->getLocation(),
01876            diag::warn_objc_implementation_missing_designated_init_override)
01877         << MD->getSelector();
01878       Diag(MD->getLocation(), diag::note_objc_designated_init_marked_here);
01879     }
01880   }
01881 }
01882 
01883 /// AddPropertyAttrs - Propagates attributes from a property to the
01884 /// implicitly-declared getter or setter for that property.
01885 static void AddPropertyAttrs(Sema &S, ObjCMethodDecl *PropertyMethod,
01886                              ObjCPropertyDecl *Property) {
01887   // Should we just clone all attributes over?
01888   for (const auto *A : Property->attrs()) {
01889     if (isa<DeprecatedAttr>(A) || 
01890         isa<UnavailableAttr>(A) || 
01891         isa<AvailabilityAttr>(A))
01892       PropertyMethod->addAttr(A->clone(S.Context));
01893   }
01894 }
01895 
01896 /// ProcessPropertyDecl - Make sure that any user-defined setter/getter methods
01897 /// have the property type and issue diagnostics if they don't.
01898 /// Also synthesize a getter/setter method if none exist (and update the
01899 /// appropriate lookup tables. FIXME: Should reconsider if adding synthesized
01900 /// methods is the "right" thing to do.
01901 void Sema::ProcessPropertyDecl(ObjCPropertyDecl *property,
01902                                ObjCContainerDecl *CD,
01903                                ObjCPropertyDecl *redeclaredProperty,
01904                                ObjCContainerDecl *lexicalDC) {
01905 
01906   ObjCMethodDecl *GetterMethod, *SetterMethod;
01907 
01908   GetterMethod = CD->getInstanceMethod(property->getGetterName());
01909   SetterMethod = CD->getInstanceMethod(property->getSetterName());
01910   DiagnosePropertyAccessorMismatch(property, GetterMethod,
01911                                    property->getLocation());
01912 
01913   if (SetterMethod) {
01914     ObjCPropertyDecl::PropertyAttributeKind CAttr =
01915       property->getPropertyAttributes();
01916     if ((!(CAttr & ObjCPropertyDecl::OBJC_PR_readonly)) &&
01917         Context.getCanonicalType(SetterMethod->getReturnType()) !=
01918             Context.VoidTy)
01919       Diag(SetterMethod->getLocation(), diag::err_setter_type_void);
01920     if (SetterMethod->param_size() != 1 ||
01921         !Context.hasSameUnqualifiedType(
01922           (*SetterMethod->param_begin())->getType().getNonReferenceType(), 
01923           property->getType().getNonReferenceType())) {
01924       Diag(property->getLocation(),
01925            diag::warn_accessor_property_type_mismatch)
01926         << property->getDeclName()
01927         << SetterMethod->getSelector();
01928       Diag(SetterMethod->getLocation(), diag::note_declared_at);
01929     }
01930   }
01931 
01932   // Synthesize getter/setter methods if none exist.
01933   // Find the default getter and if one not found, add one.
01934   // FIXME: The synthesized property we set here is misleading. We almost always
01935   // synthesize these methods unless the user explicitly provided prototypes
01936   // (which is odd, but allowed). Sema should be typechecking that the
01937   // declarations jive in that situation (which it is not currently).
01938   if (!GetterMethod) {
01939     // No instance method of same name as property getter name was found.
01940     // Declare a getter method and add it to the list of methods
01941     // for this class.
01942     SourceLocation Loc = redeclaredProperty ? 
01943       redeclaredProperty->getLocation() :
01944       property->getLocation();
01945 
01946     GetterMethod = ObjCMethodDecl::Create(Context, Loc, Loc,
01947                              property->getGetterName(),
01948                              property->getType(), 0, CD, /*isInstance=*/true,
01949                              /*isVariadic=*/false, /*isPropertyAccessor=*/true,
01950                              /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
01951                              (property->getPropertyImplementation() ==
01952                               ObjCPropertyDecl::Optional) ?
01953                              ObjCMethodDecl::Optional :
01954                              ObjCMethodDecl::Required);
01955     CD->addDecl(GetterMethod);
01956 
01957     AddPropertyAttrs(*this, GetterMethod, property);
01958 
01959     // FIXME: Eventually this shouldn't be needed, as the lexical context
01960     // and the real context should be the same.
01961     if (lexicalDC)
01962       GetterMethod->setLexicalDeclContext(lexicalDC);
01963     if (property->hasAttr<NSReturnsNotRetainedAttr>())
01964       GetterMethod->addAttr(NSReturnsNotRetainedAttr::CreateImplicit(Context,
01965                                                                      Loc));
01966     
01967     if (property->hasAttr<ObjCReturnsInnerPointerAttr>())
01968       GetterMethod->addAttr(
01969         ObjCReturnsInnerPointerAttr::CreateImplicit(Context, Loc));
01970     
01971     if (const SectionAttr *SA = property->getAttr<SectionAttr>())
01972       GetterMethod->addAttr(
01973           SectionAttr::CreateImplicit(Context, SectionAttr::GNU_section,
01974                                       SA->getName(), Loc));
01975 
01976     if (getLangOpts().ObjCAutoRefCount)
01977       CheckARCMethodDecl(GetterMethod);
01978   } else
01979     // A user declared getter will be synthesize when @synthesize of
01980     // the property with the same name is seen in the @implementation
01981     GetterMethod->setPropertyAccessor(true);
01982   property->setGetterMethodDecl(GetterMethod);
01983 
01984   // Skip setter if property is read-only.
01985   if (!property->isReadOnly()) {
01986     // Find the default setter and if one not found, add one.
01987     if (!SetterMethod) {
01988       // No instance method of same name as property setter name was found.
01989       // Declare a setter method and add it to the list of methods
01990       // for this class.
01991       SourceLocation Loc = redeclaredProperty ? 
01992         redeclaredProperty->getLocation() :
01993         property->getLocation();
01994 
01995       SetterMethod =
01996         ObjCMethodDecl::Create(Context, Loc, Loc,
01997                                property->getSetterName(), Context.VoidTy, 0,
01998                                CD, /*isInstance=*/true, /*isVariadic=*/false,
01999                                /*isPropertyAccessor=*/true,
02000                                /*isImplicitlyDeclared=*/true,
02001                                /*isDefined=*/false,
02002                                (property->getPropertyImplementation() ==
02003                                 ObjCPropertyDecl::Optional) ?
02004                                 ObjCMethodDecl::Optional :
02005                                 ObjCMethodDecl::Required);
02006 
02007       // Invent the arguments for the setter. We don't bother making a
02008       // nice name for the argument.
02009       ParmVarDecl *Argument = ParmVarDecl::Create(Context, SetterMethod,
02010                                                   Loc, Loc,
02011                                                   property->getIdentifier(),
02012                                     property->getType().getUnqualifiedType(),
02013                                                   /*TInfo=*/0,
02014                                                   SC_None,
02015                                                   0);
02016       SetterMethod->setMethodParams(Context, Argument, None);
02017 
02018       AddPropertyAttrs(*this, SetterMethod, property);
02019 
02020       CD->addDecl(SetterMethod);
02021       // FIXME: Eventually this shouldn't be needed, as the lexical context
02022       // and the real context should be the same.
02023       if (lexicalDC)
02024         SetterMethod->setLexicalDeclContext(lexicalDC);
02025       if (const SectionAttr *SA = property->getAttr<SectionAttr>())
02026         SetterMethod->addAttr(
02027             SectionAttr::CreateImplicit(Context, SectionAttr::GNU_section,
02028                                         SA->getName(), Loc));
02029       // It's possible for the user to have set a very odd custom
02030       // setter selector that causes it to have a method family.
02031       if (getLangOpts().ObjCAutoRefCount)
02032         CheckARCMethodDecl(SetterMethod);
02033     } else
02034       // A user declared setter will be synthesize when @synthesize of
02035       // the property with the same name is seen in the @implementation
02036       SetterMethod->setPropertyAccessor(true);
02037     property->setSetterMethodDecl(SetterMethod);
02038   }
02039   // Add any synthesized methods to the global pool. This allows us to
02040   // handle the following, which is supported by GCC (and part of the design).
02041   //
02042   // @interface Foo
02043   // @property double bar;
02044   // @end
02045   //
02046   // void thisIsUnfortunate() {
02047   //   id foo;
02048   //   double bar = [foo bar];
02049   // }
02050   //
02051   if (GetterMethod)
02052     AddInstanceMethodToGlobalPool(GetterMethod);
02053   if (SetterMethod)
02054     AddInstanceMethodToGlobalPool(SetterMethod);
02055 
02056   ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(CD);
02057   if (!CurrentClass) {
02058     if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(CD))
02059       CurrentClass = Cat->getClassInterface();
02060     else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(CD))
02061       CurrentClass = Impl->getClassInterface();
02062   }
02063   if (GetterMethod)
02064     CheckObjCMethodOverrides(GetterMethod, CurrentClass, Sema::RTC_Unknown);
02065   if (SetterMethod)
02066     CheckObjCMethodOverrides(SetterMethod, CurrentClass, Sema::RTC_Unknown);
02067 }
02068 
02069 void Sema::CheckObjCPropertyAttributes(Decl *PDecl,
02070                                        SourceLocation Loc,
02071                                        unsigned &Attributes,
02072                                        bool propertyInPrimaryClass) {
02073   // FIXME: Improve the reported location.
02074   if (!PDecl || PDecl->isInvalidDecl())
02075     return;
02076   
02077   if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
02078       (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
02079     Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02080     << "readonly" << "readwrite";
02081   
02082   ObjCPropertyDecl *PropertyDecl = cast<ObjCPropertyDecl>(PDecl);
02083   QualType PropertyTy = PropertyDecl->getType();
02084   unsigned PropertyOwnership = getOwnershipRule(Attributes);
02085 
02086   // 'readonly' property with no obvious lifetime.
02087   // its life time will be determined by its backing ivar.
02088   if (getLangOpts().ObjCAutoRefCount &&
02089       Attributes & ObjCDeclSpec::DQ_PR_readonly &&
02090       PropertyTy->isObjCRetainableType() &&
02091       !PropertyOwnership)
02092     return;
02093 
02094   // Check for copy or retain on non-object types.
02095   if ((Attributes & (ObjCDeclSpec::DQ_PR_weak | ObjCDeclSpec::DQ_PR_copy |
02096                     ObjCDeclSpec::DQ_PR_retain | ObjCDeclSpec::DQ_PR_strong)) &&
02097       !PropertyTy->isObjCRetainableType() &&
02098       !PropertyDecl->hasAttr<ObjCNSObjectAttr>()) {
02099     Diag(Loc, diag::err_objc_property_requires_object)
02100       << (Attributes & ObjCDeclSpec::DQ_PR_weak ? "weak" :
02101           Attributes & ObjCDeclSpec::DQ_PR_copy ? "copy" : "retain (or strong)");
02102     Attributes &= ~(ObjCDeclSpec::DQ_PR_weak   | ObjCDeclSpec::DQ_PR_copy |
02103                     ObjCDeclSpec::DQ_PR_retain | ObjCDeclSpec::DQ_PR_strong);
02104     PropertyDecl->setInvalidDecl();
02105   }
02106 
02107   // Check for more than one of { assign, copy, retain }.
02108   if (Attributes & ObjCDeclSpec::DQ_PR_assign) {
02109     if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
02110       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02111         << "assign" << "copy";
02112       Attributes &= ~ObjCDeclSpec::DQ_PR_copy;
02113     }
02114     if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
02115       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02116         << "assign" << "retain";
02117       Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
02118     }
02119     if (Attributes & ObjCDeclSpec::DQ_PR_strong) {
02120       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02121         << "assign" << "strong";
02122       Attributes &= ~ObjCDeclSpec::DQ_PR_strong;
02123     }
02124     if (getLangOpts().ObjCAutoRefCount  &&
02125         (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
02126       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02127         << "assign" << "weak";
02128       Attributes &= ~ObjCDeclSpec::DQ_PR_weak;
02129     }
02130     if (PropertyDecl->hasAttr<IBOutletCollectionAttr>())
02131       Diag(Loc, diag::warn_iboutletcollection_property_assign);
02132   } else if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) {
02133     if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
02134       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02135         << "unsafe_unretained" << "copy";
02136       Attributes &= ~ObjCDeclSpec::DQ_PR_copy;
02137     }
02138     if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
02139       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02140         << "unsafe_unretained" << "retain";
02141       Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
02142     }
02143     if (Attributes & ObjCDeclSpec::DQ_PR_strong) {
02144       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02145         << "unsafe_unretained" << "strong";
02146       Attributes &= ~ObjCDeclSpec::DQ_PR_strong;
02147     }
02148     if (getLangOpts().ObjCAutoRefCount  &&
02149         (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
02150       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02151         << "unsafe_unretained" << "weak";
02152       Attributes &= ~ObjCDeclSpec::DQ_PR_weak;
02153     }
02154   } else if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
02155     if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
02156       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02157         << "copy" << "retain";
02158       Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
02159     }
02160     if (Attributes & ObjCDeclSpec::DQ_PR_strong) {
02161       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02162         << "copy" << "strong";
02163       Attributes &= ~ObjCDeclSpec::DQ_PR_strong;
02164     }
02165     if (Attributes & ObjCDeclSpec::DQ_PR_weak) {
02166       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02167         << "copy" << "weak";
02168       Attributes &= ~ObjCDeclSpec::DQ_PR_weak;
02169     }
02170   }
02171   else if ((Attributes & ObjCDeclSpec::DQ_PR_retain) &&
02172            (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
02173       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02174         << "retain" << "weak";
02175       Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
02176   }
02177   else if ((Attributes & ObjCDeclSpec::DQ_PR_strong) &&
02178            (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
02179       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02180         << "strong" << "weak";
02181       Attributes &= ~ObjCDeclSpec::DQ_PR_weak;
02182   }
02183 
02184   if ((Attributes & ObjCDeclSpec::DQ_PR_atomic) &&
02185       (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)) {
02186       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02187         << "atomic" << "nonatomic";
02188       Attributes &= ~ObjCDeclSpec::DQ_PR_atomic;
02189   }
02190 
02191   // Warn if user supplied no assignment attribute, property is
02192   // readwrite, and this is an object type.
02193   if (!(Attributes & (ObjCDeclSpec::DQ_PR_assign | ObjCDeclSpec::DQ_PR_copy |
02194                       ObjCDeclSpec::DQ_PR_unsafe_unretained |
02195                       ObjCDeclSpec::DQ_PR_retain | ObjCDeclSpec::DQ_PR_strong |
02196                       ObjCDeclSpec::DQ_PR_weak)) &&
02197       PropertyTy->isObjCObjectPointerType()) {
02198       if (getLangOpts().ObjCAutoRefCount)
02199         // With arc,  @property definitions should default to (strong) when 
02200         // not specified; including when property is 'readonly'.
02201         PropertyDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong);
02202       else if (!(Attributes & ObjCDeclSpec::DQ_PR_readonly)) {
02203         bool isAnyClassTy = 
02204           (PropertyTy->isObjCClassType() || 
02205            PropertyTy->isObjCQualifiedClassType());
02206         // In non-gc, non-arc mode, 'Class' is treated as a 'void *' no need to
02207         // issue any warning.
02208         if (isAnyClassTy && getLangOpts().getGC() == LangOptions::NonGC)
02209           ;
02210         else if (propertyInPrimaryClass) {
02211           // Don't issue warning on property with no life time in class 
02212           // extension as it is inherited from property in primary class.
02213           // Skip this warning in gc-only mode.
02214           if (getLangOpts().getGC() != LangOptions::GCOnly)
02215             Diag(Loc, diag::warn_objc_property_no_assignment_attribute);
02216 
02217           // If non-gc code warn that this is likely inappropriate.
02218           if (getLangOpts().getGC() == LangOptions::NonGC)
02219             Diag(Loc, diag::warn_objc_property_default_assign_on_object);
02220         }
02221       }
02222 
02223     // FIXME: Implement warning dependent on NSCopying being
02224     // implemented. See also:
02225     // <rdar://5168496&4855821&5607453&5096644&4947311&5698469&4947014&5168496>
02226     // (please trim this list while you are at it).
02227   }
02228 
02229   if (!(Attributes & ObjCDeclSpec::DQ_PR_copy)
02230       &&!(Attributes & ObjCDeclSpec::DQ_PR_readonly)
02231       && getLangOpts().getGC() == LangOptions::GCOnly
02232       && PropertyTy->isBlockPointerType())
02233     Diag(Loc, diag::warn_objc_property_copy_missing_on_block);
02234   else if ((Attributes & ObjCDeclSpec::DQ_PR_retain) &&
02235            !(Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
02236            !(Attributes & ObjCDeclSpec::DQ_PR_strong) &&
02237            PropertyTy->isBlockPointerType())
02238       Diag(Loc, diag::warn_objc_property_retain_of_block);
02239   
02240   if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
02241       (Attributes & ObjCDeclSpec::DQ_PR_setter))
02242     Diag(Loc, diag::warn_objc_readonly_property_has_setter);
02243       
02244 }