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