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,
01161                                       Ivar->getUsageType(SelfDecl->getType()),
01162                                       PropertyDiagLoc,
01163                                       Ivar->getLocation(),
01164                                       LoadSelfExpr, true, true);
01165       ExprResult Res = PerformCopyInitialization(
01166           InitializedEntity::InitializeResult(PropertyDiagLoc,
01167                                               getterMethod->getReturnType(),
01168                                               /*NRVO=*/false),
01169           PropertyDiagLoc, IvarRefExpr);
01170       if (!Res.isInvalid()) {
01171         Expr *ResExpr = Res.getAs<Expr>();
01172         if (ResExpr)
01173           ResExpr = MaybeCreateExprWithCleanups(ResExpr);
01174         PIDecl->setGetterCXXConstructor(ResExpr);
01175       }
01176     }
01177     if (property->hasAttr<NSReturnsNotRetainedAttr>() &&
01178         !getterMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
01179       Diag(getterMethod->getLocation(), 
01180            diag::warn_property_getter_owning_mismatch);
01181       Diag(property->getLocation(), diag::note_property_declare);
01182     }
01183     if (getLangOpts().ObjCAutoRefCount && Synthesize)
01184       switch (getterMethod->getMethodFamily()) {
01185         case OMF_retain:
01186         case OMF_retainCount:
01187         case OMF_release:
01188         case OMF_autorelease:
01189           Diag(getterMethod->getLocation(), diag::err_arc_illegal_method_def)
01190             << 1 << getterMethod->getSelector();
01191           break;
01192         default:
01193           break;
01194       }
01195   }
01196   if (ObjCMethodDecl *setterMethod = property->getSetterMethodDecl()) {
01197     setterMethod->createImplicitParams(Context, IDecl);
01198     if (getLangOpts().CPlusPlus && Synthesize && !CompleteTypeErr &&
01199         Ivar->getType()->isRecordType()) {
01200       // FIXME. Eventually we want to do this for Objective-C as well.
01201       SynthesizedFunctionScope Scope(*this, setterMethod);
01202       ImplicitParamDecl *SelfDecl = setterMethod->getSelfDecl();
01203       DeclRefExpr *SelfExpr = 
01204         new (Context) DeclRefExpr(SelfDecl, false, SelfDecl->getType(),
01205                                   VK_LValue, PropertyDiagLoc);
01206       MarkDeclRefReferenced(SelfExpr);
01207       Expr *LoadSelfExpr =
01208         ImplicitCastExpr::Create(Context, SelfDecl->getType(),
01209                                  CK_LValueToRValue, SelfExpr, nullptr,
01210                                  VK_RValue);
01211       Expr *lhs =
01212         new (Context) ObjCIvarRefExpr(Ivar,
01213                                       Ivar->getUsageType(SelfDecl->getType()),
01214                                       PropertyDiagLoc,
01215                                       Ivar->getLocation(),
01216                                       LoadSelfExpr, true, true);
01217       ObjCMethodDecl::param_iterator P = setterMethod->param_begin();
01218       ParmVarDecl *Param = (*P);
01219       QualType T = Param->getType().getNonReferenceType();
01220       DeclRefExpr *rhs = new (Context) DeclRefExpr(Param, false, T,
01221                                                    VK_LValue, PropertyDiagLoc);
01222       MarkDeclRefReferenced(rhs);
01223       ExprResult Res = BuildBinOp(S, PropertyDiagLoc, 
01224                                   BO_Assign, lhs, rhs);
01225       if (property->getPropertyAttributes() & 
01226           ObjCPropertyDecl::OBJC_PR_atomic) {
01227         Expr *callExpr = Res.getAs<Expr>();
01228         if (const CXXOperatorCallExpr *CXXCE = 
01229               dyn_cast_or_null<CXXOperatorCallExpr>(callExpr))
01230           if (const FunctionDecl *FuncDecl = CXXCE->getDirectCallee())
01231             if (!FuncDecl->isTrivial())
01232               if (property->getType()->isReferenceType()) {
01233                 Diag(PropertyDiagLoc, 
01234                      diag::err_atomic_property_nontrivial_assign_op)
01235                     << property->getType();
01236                 Diag(FuncDecl->getLocStart(), 
01237                      diag::note_callee_decl) << FuncDecl;
01238               }
01239       }
01240       PIDecl->setSetterCXXAssignment(Res.getAs<Expr>());
01241     }
01242   }
01243   
01244   if (IC) {
01245     if (Synthesize)
01246       if (ObjCPropertyImplDecl *PPIDecl =
01247           IC->FindPropertyImplIvarDecl(PropertyIvar)) {
01248         Diag(PropertyLoc, diag::error_duplicate_ivar_use)
01249         << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
01250         << PropertyIvar;
01251         Diag(PPIDecl->getLocation(), diag::note_previous_use);
01252       }
01253 
01254     if (ObjCPropertyImplDecl *PPIDecl
01255         = IC->FindPropertyImplDecl(PropertyId)) {
01256       Diag(PropertyLoc, diag::error_property_implemented) << PropertyId;
01257       Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
01258       return nullptr;
01259     }
01260     IC->addPropertyImplementation(PIDecl);
01261     if (getLangOpts().ObjCDefaultSynthProperties &&
01262         getLangOpts().ObjCRuntime.isNonFragile() &&
01263         !IDecl->isObjCRequiresPropertyDefs()) {
01264       // Diagnose if an ivar was lazily synthesdized due to a previous
01265       // use and if 1) property is @dynamic or 2) property is synthesized
01266       // but it requires an ivar of different name.
01267       ObjCInterfaceDecl *ClassDeclared=nullptr;
01268       ObjCIvarDecl *Ivar = nullptr;
01269       if (!Synthesize)
01270         Ivar = IDecl->lookupInstanceVariable(PropertyId, ClassDeclared);
01271       else {
01272         if (PropertyIvar && PropertyIvar != PropertyId)
01273           Ivar = IDecl->lookupInstanceVariable(PropertyId, ClassDeclared);
01274       }
01275       // Issue diagnostics only if Ivar belongs to current class.
01276       if (Ivar && Ivar->getSynthesize() && 
01277           declaresSameEntity(IC->getClassInterface(), ClassDeclared)) {
01278         Diag(Ivar->getLocation(), diag::err_undeclared_var_use) 
01279         << PropertyId;
01280         Ivar->setInvalidDecl();
01281       }
01282     }
01283   } else {
01284     if (Synthesize)
01285       if (ObjCPropertyImplDecl *PPIDecl =
01286           CatImplClass->FindPropertyImplIvarDecl(PropertyIvar)) {
01287         Diag(PropertyDiagLoc, diag::error_duplicate_ivar_use)
01288         << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
01289         << PropertyIvar;
01290         Diag(PPIDecl->getLocation(), diag::note_previous_use);
01291       }
01292 
01293     if (ObjCPropertyImplDecl *PPIDecl =
01294         CatImplClass->FindPropertyImplDecl(PropertyId)) {
01295       Diag(PropertyDiagLoc, diag::error_property_implemented) << PropertyId;
01296       Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
01297       return nullptr;
01298     }
01299     CatImplClass->addPropertyImplementation(PIDecl);
01300   }
01301 
01302   return PIDecl;
01303 }
01304 
01305 //===----------------------------------------------------------------------===//
01306 // Helper methods.
01307 //===----------------------------------------------------------------------===//
01308 
01309 /// DiagnosePropertyMismatch - Compares two properties for their
01310 /// attributes and types and warns on a variety of inconsistencies.
01311 ///
01312 void
01313 Sema::DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
01314                                ObjCPropertyDecl *SuperProperty,
01315                                const IdentifierInfo *inheritedName,
01316                                bool OverridingProtocolProperty) {
01317   ObjCPropertyDecl::PropertyAttributeKind CAttr =
01318     Property->getPropertyAttributes();
01319   ObjCPropertyDecl::PropertyAttributeKind SAttr =
01320     SuperProperty->getPropertyAttributes();
01321   
01322   // We allow readonly properties without an explicit ownership
01323   // (assign/unsafe_unretained/weak/retain/strong/copy) in super class
01324   // to be overridden by a property with any explicit ownership in the subclass.
01325   if (!OverridingProtocolProperty &&
01326       !getOwnershipRule(SAttr) && getOwnershipRule(CAttr))
01327     ;
01328   else {
01329     if ((CAttr & ObjCPropertyDecl::OBJC_PR_readonly)
01330         && (SAttr & ObjCPropertyDecl::OBJC_PR_readwrite))
01331       Diag(Property->getLocation(), diag::warn_readonly_property)
01332         << Property->getDeclName() << inheritedName;
01333     if ((CAttr & ObjCPropertyDecl::OBJC_PR_copy)
01334         != (SAttr & ObjCPropertyDecl::OBJC_PR_copy))
01335       Diag(Property->getLocation(), diag::warn_property_attribute)
01336         << Property->getDeclName() << "copy" << inheritedName;
01337     else if (!(SAttr & ObjCPropertyDecl::OBJC_PR_readonly)){
01338       unsigned CAttrRetain =
01339         (CAttr &
01340          (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_strong));
01341       unsigned SAttrRetain =
01342         (SAttr &
01343          (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_strong));
01344       bool CStrong = (CAttrRetain != 0);
01345       bool SStrong = (SAttrRetain != 0);
01346       if (CStrong != SStrong)
01347         Diag(Property->getLocation(), diag::warn_property_attribute)
01348           << Property->getDeclName() << "retain (or strong)" << inheritedName;
01349     }
01350   }
01351 
01352   if ((CAttr & ObjCPropertyDecl::OBJC_PR_nonatomic)
01353       != (SAttr & ObjCPropertyDecl::OBJC_PR_nonatomic)) {
01354     Diag(Property->getLocation(), diag::warn_property_attribute)
01355       << Property->getDeclName() << "atomic" << inheritedName;
01356     Diag(SuperProperty->getLocation(), diag::note_property_declare);
01357   }
01358   if (Property->getSetterName() != SuperProperty->getSetterName()) {
01359     Diag(Property->getLocation(), diag::warn_property_attribute)
01360       << Property->getDeclName() << "setter" << inheritedName;
01361     Diag(SuperProperty->getLocation(), diag::note_property_declare);
01362   }
01363   if (Property->getGetterName() != SuperProperty->getGetterName()) {
01364     Diag(Property->getLocation(), diag::warn_property_attribute)
01365       << Property->getDeclName() << "getter" << inheritedName;
01366     Diag(SuperProperty->getLocation(), diag::note_property_declare);
01367   }
01368 
01369   QualType LHSType =
01370     Context.getCanonicalType(SuperProperty->getType());
01371   QualType RHSType =
01372     Context.getCanonicalType(Property->getType());
01373 
01374   if (!Context.propertyTypesAreCompatible(LHSType, RHSType)) {
01375     // Do cases not handled in above.
01376     // FIXME. For future support of covariant property types, revisit this.
01377     bool IncompatibleObjC = false;
01378     QualType ConvertedType;
01379     if (!isObjCPointerConversion(RHSType, LHSType, 
01380                                  ConvertedType, IncompatibleObjC) ||
01381         IncompatibleObjC) {
01382         Diag(Property->getLocation(), diag::warn_property_types_are_incompatible)
01383         << Property->getType() << SuperProperty->getType() << inheritedName;
01384       Diag(SuperProperty->getLocation(), diag::note_property_declare);
01385     }
01386   }
01387 }
01388 
01389 bool Sema::DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *property,
01390                                             ObjCMethodDecl *GetterMethod,
01391                                             SourceLocation Loc) {
01392   if (!GetterMethod)
01393     return false;
01394   QualType GetterType = GetterMethod->getReturnType().getNonReferenceType();
01395   QualType PropertyIvarType = property->getType().getNonReferenceType();
01396   bool compat = Context.hasSameType(PropertyIvarType, GetterType);
01397   if (!compat) {
01398     if (isa<ObjCObjectPointerType>(PropertyIvarType) && 
01399         isa<ObjCObjectPointerType>(GetterType))
01400       compat =
01401         Context.canAssignObjCInterfaces(
01402                                       GetterType->getAs<ObjCObjectPointerType>(),
01403                                       PropertyIvarType->getAs<ObjCObjectPointerType>());
01404     else if (CheckAssignmentConstraints(Loc, GetterType, PropertyIvarType) 
01405               != Compatible) {
01406           Diag(Loc, diag::error_property_accessor_type)
01407             << property->getDeclName() << PropertyIvarType
01408             << GetterMethod->getSelector() << GetterType;
01409           Diag(GetterMethod->getLocation(), diag::note_declared_at);
01410           return true;
01411     } else {
01412       compat = true;
01413       QualType lhsType =Context.getCanonicalType(PropertyIvarType).getUnqualifiedType();
01414       QualType rhsType =Context.getCanonicalType(GetterType).getUnqualifiedType();
01415       if (lhsType != rhsType && lhsType->isArithmeticType())
01416         compat = false;
01417     }
01418   }
01419   
01420   if (!compat) {
01421     Diag(Loc, diag::warn_accessor_property_type_mismatch)
01422     << property->getDeclName()
01423     << GetterMethod->getSelector();
01424     Diag(GetterMethod->getLocation(), diag::note_declared_at);
01425     return true;
01426   }
01427 
01428   return false;
01429 }
01430 
01431 /// CollectImmediateProperties - This routine collects all properties in
01432 /// the class and its conforming protocols; but not those in its super class.
01433 static void CollectImmediateProperties(ObjCContainerDecl *CDecl,
01434                                        ObjCContainerDecl::PropertyMap &PropMap,
01435                                        ObjCContainerDecl::PropertyMap &SuperPropMap,
01436                                        bool IncludeProtocols = true) {
01437 
01438   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
01439     for (auto *Prop : IDecl->properties())
01440       PropMap[Prop->getIdentifier()] = Prop;
01441     if (IncludeProtocols) {
01442       // Scan through class's protocols.
01443       for (auto *PI : IDecl->all_referenced_protocols())
01444         CollectImmediateProperties(PI, PropMap, SuperPropMap);
01445     }
01446   }
01447   if (ObjCCategoryDecl *CATDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) {
01448     if (!CATDecl->IsClassExtension())
01449       for (auto *Prop : CATDecl->properties())
01450         PropMap[Prop->getIdentifier()] = Prop;
01451     if (IncludeProtocols) {
01452       // Scan through class's protocols.
01453       for (auto *PI : CATDecl->protocols())
01454         CollectImmediateProperties(PI, PropMap, SuperPropMap);
01455     }
01456   }
01457   else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(CDecl)) {
01458     for (auto *Prop : PDecl->properties()) {
01459       ObjCPropertyDecl *PropertyFromSuper = SuperPropMap[Prop->getIdentifier()];
01460       // Exclude property for protocols which conform to class's super-class, 
01461       // as super-class has to implement the property.
01462       if (!PropertyFromSuper || 
01463           PropertyFromSuper->getIdentifier() != Prop->getIdentifier()) {
01464         ObjCPropertyDecl *&PropEntry = PropMap[Prop->getIdentifier()];
01465         if (!PropEntry)
01466           PropEntry = Prop;
01467       }
01468     }
01469     // scan through protocol's protocols.
01470     for (auto *PI : PDecl->protocols())
01471       CollectImmediateProperties(PI, PropMap, SuperPropMap);
01472   }
01473 }
01474 
01475 /// CollectSuperClassPropertyImplementations - This routine collects list of
01476 /// properties to be implemented in super class(s) and also coming from their
01477 /// conforming protocols.
01478 static void CollectSuperClassPropertyImplementations(ObjCInterfaceDecl *CDecl,
01479                                     ObjCInterfaceDecl::PropertyMap &PropMap) {
01480   if (ObjCInterfaceDecl *SDecl = CDecl->getSuperClass()) {
01481     ObjCInterfaceDecl::PropertyDeclOrder PO;
01482     while (SDecl) {
01483       SDecl->collectPropertiesToImplement(PropMap, PO);
01484       SDecl = SDecl->getSuperClass();
01485     }
01486   }
01487 }
01488 
01489 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
01490 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
01491 /// declared in class 'IFace'.
01492 bool
01493 Sema::IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
01494                                      ObjCMethodDecl *Method, ObjCIvarDecl *IV) {
01495   if (!IV->getSynthesize())
01496     return false;
01497   ObjCMethodDecl *IMD = IFace->lookupMethod(Method->getSelector(),
01498                                             Method->isInstanceMethod());
01499   if (!IMD || !IMD->isPropertyAccessor())
01500     return false;
01501   
01502   // look up a property declaration whose one of its accessors is implemented
01503   // by this method.
01504   for (const auto *Property : IFace->properties()) {
01505     if ((Property->getGetterName() == IMD->getSelector() ||
01506          Property->getSetterName() == IMD->getSelector()) &&
01507         (Property->getPropertyIvarDecl() == IV))
01508       return true;
01509   }
01510   return false;
01511 }
01512 
01513 static bool SuperClassImplementsProperty(ObjCInterfaceDecl *IDecl,
01514                                          ObjCPropertyDecl *Prop) {
01515   bool SuperClassImplementsGetter = false;
01516   bool SuperClassImplementsSetter = false;
01517   if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readonly)
01518     SuperClassImplementsSetter = true;
01519 
01520   while (IDecl->getSuperClass()) {
01521     ObjCInterfaceDecl *SDecl = IDecl->getSuperClass();
01522     if (!SuperClassImplementsGetter && SDecl->getInstanceMethod(Prop->getGetterName()))
01523       SuperClassImplementsGetter = true;
01524 
01525     if (!SuperClassImplementsSetter && SDecl->getInstanceMethod(Prop->getSetterName()))
01526       SuperClassImplementsSetter = true;
01527     if (SuperClassImplementsGetter && SuperClassImplementsSetter)
01528       return true;
01529     IDecl = IDecl->getSuperClass();
01530   }
01531   return false;
01532 }
01533 
01534 /// \brief Default synthesizes all properties which must be synthesized
01535 /// in class's \@implementation.
01536 void Sema::DefaultSynthesizeProperties(Scope *S, ObjCImplDecl* IMPDecl,
01537                                        ObjCInterfaceDecl *IDecl) {
01538   
01539   ObjCInterfaceDecl::PropertyMap PropMap;
01540   ObjCInterfaceDecl::PropertyDeclOrder PropertyOrder;
01541   IDecl->collectPropertiesToImplement(PropMap, PropertyOrder);
01542   if (PropMap.empty())
01543     return;
01544   ObjCInterfaceDecl::PropertyMap SuperPropMap;
01545   CollectSuperClassPropertyImplementations(IDecl, SuperPropMap);
01546   
01547   for (unsigned i = 0, e = PropertyOrder.size(); i != e; i++) {
01548     ObjCPropertyDecl *Prop = PropertyOrder[i];
01549     // Is there a matching property synthesize/dynamic?
01550     if (Prop->isInvalidDecl() ||
01551         Prop->getPropertyImplementation() == ObjCPropertyDecl::Optional)
01552       continue;
01553     // Property may have been synthesized by user.
01554     if (IMPDecl->FindPropertyImplDecl(Prop->getIdentifier()))
01555       continue;
01556     if (IMPDecl->getInstanceMethod(Prop->getGetterName())) {
01557       if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readonly)
01558         continue;
01559       if (IMPDecl->getInstanceMethod(Prop->getSetterName()))
01560         continue;
01561     }
01562     if (ObjCPropertyImplDecl *PID =
01563         IMPDecl->FindPropertyImplIvarDecl(Prop->getIdentifier())) {
01564       Diag(Prop->getLocation(), diag::warn_no_autosynthesis_shared_ivar_property)
01565         << Prop->getIdentifier();
01566       if (!PID->getLocation().isInvalid())
01567         Diag(PID->getLocation(), diag::note_property_synthesize);
01568       continue;
01569     }
01570     ObjCPropertyDecl *PropInSuperClass = SuperPropMap[Prop->getIdentifier()];
01571     if (ObjCProtocolDecl *Proto =
01572           dyn_cast<ObjCProtocolDecl>(Prop->getDeclContext())) {
01573       // We won't auto-synthesize properties declared in protocols.
01574       // Suppress the warning if class's superclass implements property's
01575       // getter and implements property's setter (if readwrite property).
01576       // Or, if property is going to be implemented in its super class.
01577       if (!SuperClassImplementsProperty(IDecl, Prop) && !PropInSuperClass) {
01578         Diag(IMPDecl->getLocation(),
01579              diag::warn_auto_synthesizing_protocol_property)
01580           << Prop << Proto;
01581         Diag(Prop->getLocation(), diag::note_property_declare);
01582       }
01583       continue;
01584     }
01585     // If property to be implemented in the super class, ignore.
01586     if (PropInSuperClass) {
01587       if ((Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readwrite) &&
01588           (PropInSuperClass->getPropertyAttributes() &
01589            ObjCPropertyDecl::OBJC_PR_readonly) &&
01590           !IMPDecl->getInstanceMethod(Prop->getSetterName()) &&
01591           !IDecl->HasUserDeclaredSetterMethod(Prop)) {
01592         Diag(Prop->getLocation(), diag::warn_no_autosynthesis_property)
01593         << Prop->getIdentifier();
01594         Diag(PropInSuperClass->getLocation(), diag::note_property_declare);
01595       }
01596       else {
01597         Diag(Prop->getLocation(), diag::warn_autosynthesis_property_in_superclass)
01598         << Prop->getIdentifier();
01599         Diag(PropInSuperClass->getLocation(), diag::note_property_declare);
01600         Diag(IMPDecl->getLocation(), diag::note_while_in_implementation);
01601       }
01602       continue;
01603     }
01604     // We use invalid SourceLocations for the synthesized ivars since they
01605     // aren't really synthesized at a particular location; they just exist.
01606     // Saying that they are located at the @implementation isn't really going
01607     // to help users.
01608     ObjCPropertyImplDecl *PIDecl = dyn_cast_or_null<ObjCPropertyImplDecl>(
01609       ActOnPropertyImplDecl(S, SourceLocation(), SourceLocation(),
01610                             true,
01611                             /* property = */ Prop->getIdentifier(),
01612                             /* ivar = */ Prop->getDefaultSynthIvarName(Context),
01613                             Prop->getLocation()));
01614     if (PIDecl) {
01615       Diag(Prop->getLocation(), diag::warn_missing_explicit_synthesis);
01616       Diag(IMPDecl->getLocation(), diag::note_while_in_implementation);
01617     }
01618   }
01619 }
01620 
01621 void Sema::DefaultSynthesizeProperties(Scope *S, Decl *D) {
01622   if (!LangOpts.ObjCDefaultSynthProperties || LangOpts.ObjCRuntime.isFragile())
01623     return;
01624   ObjCImplementationDecl *IC=dyn_cast_or_null<ObjCImplementationDecl>(D);
01625   if (!IC)
01626     return;
01627   if (ObjCInterfaceDecl* IDecl = IC->getClassInterface())
01628     if (!IDecl->isObjCRequiresPropertyDefs())
01629       DefaultSynthesizeProperties(S, IC, IDecl);
01630 }
01631 
01632 static void DiagnoseUnimplementedAccessor(Sema &S,
01633                                           ObjCInterfaceDecl *PrimaryClass,
01634                                           Selector Method,
01635                                           ObjCImplDecl* IMPDecl,
01636                                           ObjCContainerDecl *CDecl,
01637                                           ObjCCategoryDecl *C,
01638                                           ObjCPropertyDecl *Prop,
01639                                           Sema::SelectorSet &SMap) {
01640   // When reporting on missing property setter/getter implementation in
01641   // categories, do not report when they are declared in primary class,
01642   // class's protocol, or one of it super classes. This is because,
01643   // the class is going to implement them.
01644   if (!SMap.count(Method) &&
01645       (PrimaryClass == nullptr ||
01646        !PrimaryClass->lookupPropertyAccessor(Method, C))) {
01647         S.Diag(IMPDecl->getLocation(),
01648                isa<ObjCCategoryDecl>(CDecl) ?
01649                diag::warn_setter_getter_impl_required_in_category :
01650                diag::warn_setter_getter_impl_required)
01651             << Prop->getDeclName() << Method;
01652         S.Diag(Prop->getLocation(),
01653              diag::note_property_declare);
01654         if (S.LangOpts.ObjCDefaultSynthProperties &&
01655             S.LangOpts.ObjCRuntime.isNonFragile())
01656           if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CDecl))
01657             if (const ObjCInterfaceDecl *RID = ID->isObjCRequiresPropertyDefs())
01658             S.Diag(RID->getLocation(), diag::note_suppressed_class_declare);
01659       }
01660 }
01661 
01662 void Sema::DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
01663                                            ObjCContainerDecl *CDecl,
01664                                            bool SynthesizeProperties) {
01665   ObjCContainerDecl::PropertyMap PropMap;
01666   ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
01667 
01668   if (!SynthesizeProperties) {
01669     ObjCContainerDecl::PropertyMap NoNeedToImplPropMap;
01670     // Gather properties which need not be implemented in this class
01671     // or category.
01672     if (!IDecl)
01673       if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
01674         // For categories, no need to implement properties declared in
01675         // its primary class (and its super classes) if property is
01676         // declared in one of those containers.
01677         if ((IDecl = C->getClassInterface())) {
01678           ObjCInterfaceDecl::PropertyDeclOrder PO;
01679           IDecl->collectPropertiesToImplement(NoNeedToImplPropMap, PO);
01680         }
01681       }
01682     if (IDecl)
01683       CollectSuperClassPropertyImplementations(IDecl, NoNeedToImplPropMap);
01684     
01685     CollectImmediateProperties(CDecl, PropMap, NoNeedToImplPropMap);
01686   }
01687 
01688   // Scan the @interface to see if any of the protocols it adopts
01689   // require an explicit implementation, via attribute
01690   // 'objc_protocol_requires_explicit_implementation'.
01691   if (IDecl) {
01692     std::unique_ptr<ObjCContainerDecl::PropertyMap> LazyMap;
01693 
01694     for (auto *PDecl : IDecl->all_referenced_protocols()) {
01695       if (!PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
01696         continue;
01697       // Lazily construct a set of all the properties in the @interface
01698       // of the class, without looking at the superclass.  We cannot
01699       // use the call to CollectImmediateProperties() above as that
01700       // utilizes information from the super class's properties as well
01701       // as scans the adopted protocols.  This work only triggers for protocols
01702       // with the attribute, which is very rare, and only occurs when
01703       // analyzing the @implementation.
01704       if (!LazyMap) {
01705         ObjCContainerDecl::PropertyMap NoNeedToImplPropMap;
01706         LazyMap.reset(new ObjCContainerDecl::PropertyMap());
01707         CollectImmediateProperties(CDecl, *LazyMap, NoNeedToImplPropMap,
01708                                    /* IncludeProtocols */ false);
01709       }
01710       // Add the properties of 'PDecl' to the list of properties that
01711       // need to be implemented.
01712       for (auto *PropDecl : PDecl->properties()) {
01713         if ((*LazyMap)[PropDecl->getIdentifier()])
01714           continue;
01715         PropMap[PropDecl->getIdentifier()] = PropDecl;
01716       }
01717     }
01718   }
01719 
01720   if (PropMap.empty())
01721     return;
01722 
01723   llvm::DenseSet<ObjCPropertyDecl *> PropImplMap;
01724   for (const auto *I : IMPDecl->property_impls())
01725     PropImplMap.insert(I->getPropertyDecl());
01726 
01727   SelectorSet InsMap;
01728   // Collect property accessors implemented in current implementation.
01729   for (const auto *I : IMPDecl->instance_methods())
01730     InsMap.insert(I->getSelector());
01731   
01732   ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
01733   ObjCInterfaceDecl *PrimaryClass = nullptr;
01734   if (C && !C->IsClassExtension())
01735     if ((PrimaryClass = C->getClassInterface()))
01736       // Report unimplemented properties in the category as well.
01737       if (ObjCImplDecl *IMP = PrimaryClass->getImplementation()) {
01738         // When reporting on missing setter/getters, do not report when
01739         // setter/getter is implemented in category's primary class
01740         // implementation.
01741         for (const auto *I : IMP->instance_methods())
01742           InsMap.insert(I->getSelector());
01743       }
01744 
01745   for (ObjCContainerDecl::PropertyMap::iterator
01746        P = PropMap.begin(), E = PropMap.end(); P != E; ++P) {
01747     ObjCPropertyDecl *Prop = P->second;
01748     // Is there a matching propery synthesize/dynamic?
01749     if (Prop->isInvalidDecl() ||
01750         Prop->getPropertyImplementation() == ObjCPropertyDecl::Optional ||
01751         PropImplMap.count(Prop) ||
01752         Prop->getAvailability() == AR_Unavailable)
01753       continue;
01754 
01755     // Diagnose unimplemented getters and setters.
01756     DiagnoseUnimplementedAccessor(*this,
01757           PrimaryClass, Prop->getGetterName(), IMPDecl, CDecl, C, Prop, InsMap);
01758     if (!Prop->isReadOnly())
01759       DiagnoseUnimplementedAccessor(*this,
01760                                     PrimaryClass, Prop->getSetterName(),
01761                                     IMPDecl, CDecl, C, Prop, InsMap);
01762   }
01763 }
01764 
01765 void Sema::diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl) {
01766   for (const auto *propertyImpl : impDecl->property_impls()) {
01767     const auto *property = propertyImpl->getPropertyDecl();
01768 
01769     // Warn about null_resettable properties with synthesized setters,
01770     // because the setter won't properly handle nil.
01771     if (propertyImpl->getPropertyImplementation()
01772           == ObjCPropertyImplDecl::Synthesize &&
01773         (property->getPropertyAttributes() &
01774          ObjCPropertyDecl::OBJC_PR_null_resettable) &&
01775         property->getGetterMethodDecl() &&
01776         property->getSetterMethodDecl()) {
01777       auto *getterMethod = property->getGetterMethodDecl();
01778       auto *setterMethod = property->getSetterMethodDecl();
01779       if (!impDecl->getInstanceMethod(setterMethod->getSelector()) &&
01780           !impDecl->getInstanceMethod(getterMethod->getSelector())) {
01781         SourceLocation loc = propertyImpl->getLocation();
01782         if (loc.isInvalid())
01783           loc = impDecl->getLocStart();
01784 
01785         Diag(loc, diag::warn_null_resettable_setter)
01786           << setterMethod->getSelector() << property->getDeclName();
01787       }
01788     }
01789   }
01790 }
01791 
01792 void
01793 Sema::AtomicPropertySetterGetterRules (ObjCImplDecl* IMPDecl,
01794                                        ObjCContainerDecl* IDecl) {
01795   // Rules apply in non-GC mode only
01796   if (getLangOpts().getGC() != LangOptions::NonGC)
01797     return;
01798   for (const auto *Property : IDecl->properties()) {
01799     ObjCMethodDecl *GetterMethod = nullptr;
01800     ObjCMethodDecl *SetterMethod = nullptr;
01801     bool LookedUpGetterSetter = false;
01802 
01803     unsigned Attributes = Property->getPropertyAttributes();
01804     unsigned AttributesAsWritten = Property->getPropertyAttributesAsWritten();
01805 
01806     if (!(AttributesAsWritten & ObjCPropertyDecl::OBJC_PR_atomic) &&
01807         !(AttributesAsWritten & ObjCPropertyDecl::OBJC_PR_nonatomic)) {
01808       GetterMethod = IMPDecl->getInstanceMethod(Property->getGetterName());
01809       SetterMethod = IMPDecl->getInstanceMethod(Property->getSetterName());
01810       LookedUpGetterSetter = true;
01811       if (GetterMethod) {
01812         Diag(GetterMethod->getLocation(),
01813              diag::warn_default_atomic_custom_getter_setter)
01814           << Property->getIdentifier() << 0;
01815         Diag(Property->getLocation(), diag::note_property_declare);
01816       }
01817       if (SetterMethod) {
01818         Diag(SetterMethod->getLocation(),
01819              diag::warn_default_atomic_custom_getter_setter)
01820           << Property->getIdentifier() << 1;
01821         Diag(Property->getLocation(), diag::note_property_declare);
01822       }
01823     }
01824 
01825     // We only care about readwrite atomic property.
01826     if ((Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) ||
01827         !(Attributes & ObjCPropertyDecl::OBJC_PR_readwrite))
01828       continue;
01829     if (const ObjCPropertyImplDecl *PIDecl
01830          = IMPDecl->FindPropertyImplDecl(Property->getIdentifier())) {
01831       if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
01832         continue;
01833       if (!LookedUpGetterSetter) {
01834         GetterMethod = IMPDecl->getInstanceMethod(Property->getGetterName());
01835         SetterMethod = IMPDecl->getInstanceMethod(Property->getSetterName());
01836       }
01837       if ((GetterMethod && !SetterMethod) || (!GetterMethod && SetterMethod)) {
01838         SourceLocation MethodLoc =
01839           (GetterMethod ? GetterMethod->getLocation()
01840                         : SetterMethod->getLocation());
01841         Diag(MethodLoc, diag::warn_atomic_property_rule)
01842           << Property->getIdentifier() << (GetterMethod != nullptr)
01843           << (SetterMethod != nullptr);
01844         // fixit stuff.
01845         if (!AttributesAsWritten) {
01846           if (Property->getLParenLoc().isValid()) {
01847             // @property () ... case.
01848             SourceRange PropSourceRange(Property->getAtLoc(), 
01849                                         Property->getLParenLoc());
01850             Diag(Property->getLocation(), diag::note_atomic_property_fixup_suggest) <<
01851               FixItHint::CreateReplacement(PropSourceRange, "@property (nonatomic");
01852           }
01853           else {
01854             //@property id etc.
01855             SourceLocation endLoc = 
01856               Property->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
01857             endLoc = endLoc.getLocWithOffset(-1);
01858             SourceRange PropSourceRange(Property->getAtLoc(), endLoc);
01859             Diag(Property->getLocation(), diag::note_atomic_property_fixup_suggest) <<
01860               FixItHint::CreateReplacement(PropSourceRange, "@property (nonatomic) ");
01861           }
01862         }
01863         else if (!(AttributesAsWritten & ObjCPropertyDecl::OBJC_PR_atomic)) {
01864           // @property () ... case.
01865           SourceLocation endLoc = Property->getLParenLoc();
01866           SourceRange PropSourceRange(Property->getAtLoc(), endLoc);
01867           Diag(Property->getLocation(), diag::note_atomic_property_fixup_suggest) <<
01868            FixItHint::CreateReplacement(PropSourceRange, "@property (nonatomic, ");
01869         }
01870         else
01871           Diag(MethodLoc, diag::note_atomic_property_fixup_suggest);
01872         Diag(Property->getLocation(), diag::note_property_declare);
01873       }
01874     }
01875   }
01876 }
01877 
01878 void Sema::DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D) {
01879   if (getLangOpts().getGC() == LangOptions::GCOnly)
01880     return;
01881 
01882   for (const auto *PID : D->property_impls()) {
01883     const ObjCPropertyDecl *PD = PID->getPropertyDecl();
01884     if (PD && !PD->hasAttr<NSReturnsNotRetainedAttr>() &&
01885         !D->getInstanceMethod(PD->getGetterName())) {
01886       ObjCMethodDecl *method = PD->getGetterMethodDecl();
01887       if (!method)
01888         continue;
01889       ObjCMethodFamily family = method->getMethodFamily();
01890       if (family == OMF_alloc || family == OMF_copy ||
01891           family == OMF_mutableCopy || family == OMF_new) {
01892         if (getLangOpts().ObjCAutoRefCount)
01893           Diag(PD->getLocation(), diag::err_cocoa_naming_owned_rule);
01894         else
01895           Diag(PD->getLocation(), diag::warn_cocoa_naming_owned_rule);
01896 
01897         // Look for a getter explicitly declared alongside the property.
01898         // If we find one, use its location for the note.
01899         SourceLocation noteLoc = PD->getLocation();
01900         SourceLocation fixItLoc;
01901         for (auto *getterRedecl : method->redecls()) {
01902           if (getterRedecl->isImplicit())
01903             continue;
01904           if (getterRedecl->getDeclContext() != PD->getDeclContext())
01905             continue;
01906           noteLoc = getterRedecl->getLocation();
01907           fixItLoc = getterRedecl->getLocEnd();
01908         }
01909 
01910         Preprocessor &PP = getPreprocessor();
01911         TokenValue tokens[] = {
01912           tok::kw___attribute, tok::l_paren, tok::l_paren,
01913           PP.getIdentifierInfo("objc_method_family"), tok::l_paren,
01914           PP.getIdentifierInfo("none"), tok::r_paren,
01915           tok::r_paren, tok::r_paren
01916         };
01917         StringRef spelling = "__attribute__((objc_method_family(none)))";
01918         StringRef macroName = PP.getLastMacroWithSpelling(noteLoc, tokens);
01919         if (!macroName.empty())
01920           spelling = macroName;
01921 
01922         auto noteDiag = Diag(noteLoc, diag::note_cocoa_naming_declare_family)
01923             << method->getDeclName() << spelling;
01924         if (fixItLoc.isValid()) {
01925           SmallString<64> fixItText(" ");
01926           fixItText += spelling;
01927           noteDiag << FixItHint::CreateInsertion(fixItLoc, fixItText);
01928         }
01929       }
01930     }
01931   }
01932 }
01933 
01934 void Sema::DiagnoseMissingDesignatedInitOverrides(
01935                                             const ObjCImplementationDecl *ImplD,
01936                                             const ObjCInterfaceDecl *IFD) {
01937   assert(IFD->hasDesignatedInitializers());
01938   const ObjCInterfaceDecl *SuperD = IFD->getSuperClass();
01939   if (!SuperD)
01940     return;
01941 
01942   SelectorSet InitSelSet;
01943   for (const auto *I : ImplD->instance_methods())
01944     if (I->getMethodFamily() == OMF_init)
01945       InitSelSet.insert(I->getSelector());
01946 
01947   SmallVector<const ObjCMethodDecl *, 8> DesignatedInits;
01948   SuperD->getDesignatedInitializers(DesignatedInits);
01949   for (SmallVector<const ObjCMethodDecl *, 8>::iterator
01950          I = DesignatedInits.begin(), E = DesignatedInits.end(); I != E; ++I) {
01951     const ObjCMethodDecl *MD = *I;
01952     if (!InitSelSet.count(MD->getSelector())) {
01953       bool Ignore = false;
01954       if (auto *IMD = IFD->getInstanceMethod(MD->getSelector())) {
01955         Ignore = IMD->isUnavailable();
01956       }
01957       if (!Ignore) {
01958         Diag(ImplD->getLocation(),
01959              diag::warn_objc_implementation_missing_designated_init_override)
01960           << MD->getSelector();
01961         Diag(MD->getLocation(), diag::note_objc_designated_init_marked_here);
01962       }
01963     }
01964   }
01965 }
01966 
01967 /// AddPropertyAttrs - Propagates attributes from a property to the
01968 /// implicitly-declared getter or setter for that property.
01969 static void AddPropertyAttrs(Sema &S, ObjCMethodDecl *PropertyMethod,
01970                              ObjCPropertyDecl *Property) {
01971   // Should we just clone all attributes over?
01972   for (const auto *A : Property->attrs()) {
01973     if (isa<DeprecatedAttr>(A) || 
01974         isa<UnavailableAttr>(A) || 
01975         isa<AvailabilityAttr>(A))
01976       PropertyMethod->addAttr(A->clone(S.Context));
01977   }
01978 }
01979 
01980 /// ProcessPropertyDecl - Make sure that any user-defined setter/getter methods
01981 /// have the property type and issue diagnostics if they don't.
01982 /// Also synthesize a getter/setter method if none exist (and update the
01983 /// appropriate lookup tables. FIXME: Should reconsider if adding synthesized
01984 /// methods is the "right" thing to do.
01985 void Sema::ProcessPropertyDecl(ObjCPropertyDecl *property,
01986                                ObjCContainerDecl *CD,
01987                                ObjCPropertyDecl *redeclaredProperty,
01988                                ObjCContainerDecl *lexicalDC) {
01989 
01990   ObjCMethodDecl *GetterMethod, *SetterMethod;
01991 
01992   if (CD->isInvalidDecl())
01993     return;
01994 
01995   GetterMethod = CD->getInstanceMethod(property->getGetterName());
01996   SetterMethod = CD->getInstanceMethod(property->getSetterName());
01997   DiagnosePropertyAccessorMismatch(property, GetterMethod,
01998                                    property->getLocation());
01999 
02000   if (SetterMethod) {
02001     ObjCPropertyDecl::PropertyAttributeKind CAttr =
02002       property->getPropertyAttributes();
02003     if ((!(CAttr & ObjCPropertyDecl::OBJC_PR_readonly)) &&
02004         Context.getCanonicalType(SetterMethod->getReturnType()) !=
02005             Context.VoidTy)
02006       Diag(SetterMethod->getLocation(), diag::err_setter_type_void);
02007     if (SetterMethod->param_size() != 1 ||
02008         !Context.hasSameUnqualifiedType(
02009           (*SetterMethod->param_begin())->getType().getNonReferenceType(), 
02010           property->getType().getNonReferenceType())) {
02011       Diag(property->getLocation(),
02012            diag::warn_accessor_property_type_mismatch)
02013         << property->getDeclName()
02014         << SetterMethod->getSelector();
02015       Diag(SetterMethod->getLocation(), diag::note_declared_at);
02016     }
02017   }
02018 
02019   // Synthesize getter/setter methods if none exist.
02020   // Find the default getter and if one not found, add one.
02021   // FIXME: The synthesized property we set here is misleading. We almost always
02022   // synthesize these methods unless the user explicitly provided prototypes
02023   // (which is odd, but allowed). Sema should be typechecking that the
02024   // declarations jive in that situation (which it is not currently).
02025   if (!GetterMethod) {
02026     // No instance method of same name as property getter name was found.
02027     // Declare a getter method and add it to the list of methods
02028     // for this class.
02029     SourceLocation Loc = redeclaredProperty ? 
02030       redeclaredProperty->getLocation() :
02031       property->getLocation();
02032 
02033     // If the property is null_resettable, the getter returns nonnull.
02034     QualType resultTy = property->getType();
02035     if (property->getPropertyAttributes() &
02036         ObjCPropertyDecl::OBJC_PR_null_resettable) {
02037       QualType modifiedTy = resultTy;
02038       if (auto nullability = AttributedType::stripOuterNullability(modifiedTy)) {
02039         if (*nullability == NullabilityKind::Unspecified)
02040           resultTy = Context.getAttributedType(AttributedType::attr_nonnull,
02041                                                modifiedTy, modifiedTy);
02042       }
02043     }
02044 
02045     GetterMethod = ObjCMethodDecl::Create(Context, Loc, Loc,
02046                              property->getGetterName(),
02047                              resultTy, nullptr, CD,
02048                              /*isInstance=*/true, /*isVariadic=*/false,
02049                              /*isPropertyAccessor=*/true,
02050                              /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
02051                              (property->getPropertyImplementation() ==
02052                               ObjCPropertyDecl::Optional) ?
02053                              ObjCMethodDecl::Optional :
02054                              ObjCMethodDecl::Required);
02055     CD->addDecl(GetterMethod);
02056 
02057     AddPropertyAttrs(*this, GetterMethod, property);
02058 
02059     // FIXME: Eventually this shouldn't be needed, as the lexical context
02060     // and the real context should be the same.
02061     if (lexicalDC)
02062       GetterMethod->setLexicalDeclContext(lexicalDC);
02063     if (property->hasAttr<NSReturnsNotRetainedAttr>())
02064       GetterMethod->addAttr(NSReturnsNotRetainedAttr::CreateImplicit(Context,
02065                                                                      Loc));
02066     
02067     if (property->hasAttr<ObjCReturnsInnerPointerAttr>())
02068       GetterMethod->addAttr(
02069         ObjCReturnsInnerPointerAttr::CreateImplicit(Context, Loc));
02070     
02071     if (const SectionAttr *SA = property->getAttr<SectionAttr>())
02072       GetterMethod->addAttr(
02073           SectionAttr::CreateImplicit(Context, SectionAttr::GNU_section,
02074                                       SA->getName(), Loc));
02075 
02076     if (getLangOpts().ObjCAutoRefCount)
02077       CheckARCMethodDecl(GetterMethod);
02078   } else
02079     // A user declared getter will be synthesize when @synthesize of
02080     // the property with the same name is seen in the @implementation
02081     GetterMethod->setPropertyAccessor(true);
02082   property->setGetterMethodDecl(GetterMethod);
02083 
02084   // Skip setter if property is read-only.
02085   if (!property->isReadOnly()) {
02086     // Find the default setter and if one not found, add one.
02087     if (!SetterMethod) {
02088       // No instance method of same name as property setter name was found.
02089       // Declare a setter method and add it to the list of methods
02090       // for this class.
02091       SourceLocation Loc = redeclaredProperty ? 
02092         redeclaredProperty->getLocation() :
02093         property->getLocation();
02094 
02095       SetterMethod =
02096         ObjCMethodDecl::Create(Context, Loc, Loc,
02097                                property->getSetterName(), Context.VoidTy,
02098                                nullptr, CD, /*isInstance=*/true,
02099                                /*isVariadic=*/false,
02100                                /*isPropertyAccessor=*/true,
02101                                /*isImplicitlyDeclared=*/true,
02102                                /*isDefined=*/false,
02103                                (property->getPropertyImplementation() ==
02104                                 ObjCPropertyDecl::Optional) ?
02105                                 ObjCMethodDecl::Optional :
02106                                 ObjCMethodDecl::Required);
02107 
02108       // If the property is null_resettable, the setter accepts a
02109       // nullable value.
02110       QualType paramTy = property->getType().getUnqualifiedType();
02111       if (property->getPropertyAttributes() &
02112           ObjCPropertyDecl::OBJC_PR_null_resettable) {
02113         QualType modifiedTy = paramTy;
02114         if (auto nullability = AttributedType::stripOuterNullability(modifiedTy)){
02115           if (*nullability == NullabilityKind::Unspecified)
02116             paramTy = Context.getAttributedType(AttributedType::attr_nullable,
02117                                                 modifiedTy, modifiedTy);
02118         }
02119       }
02120 
02121       // Invent the arguments for the setter. We don't bother making a
02122       // nice name for the argument.
02123       ParmVarDecl *Argument = ParmVarDecl::Create(Context, SetterMethod,
02124                                                   Loc, Loc,
02125                                                   property->getIdentifier(),
02126                                                   paramTy,
02127                                                   /*TInfo=*/nullptr,
02128                                                   SC_None,
02129                                                   nullptr);
02130       SetterMethod->setMethodParams(Context, Argument, None);
02131 
02132       AddPropertyAttrs(*this, SetterMethod, property);
02133 
02134       CD->addDecl(SetterMethod);
02135       // FIXME: Eventually this shouldn't be needed, as the lexical context
02136       // and the real context should be the same.
02137       if (lexicalDC)
02138         SetterMethod->setLexicalDeclContext(lexicalDC);
02139       if (const SectionAttr *SA = property->getAttr<SectionAttr>())
02140         SetterMethod->addAttr(
02141             SectionAttr::CreateImplicit(Context, SectionAttr::GNU_section,
02142                                         SA->getName(), Loc));
02143       // It's possible for the user to have set a very odd custom
02144       // setter selector that causes it to have a method family.
02145       if (getLangOpts().ObjCAutoRefCount)
02146         CheckARCMethodDecl(SetterMethod);
02147     } else
02148       // A user declared setter will be synthesize when @synthesize of
02149       // the property with the same name is seen in the @implementation
02150       SetterMethod->setPropertyAccessor(true);
02151     property->setSetterMethodDecl(SetterMethod);
02152   }
02153   // Add any synthesized methods to the global pool. This allows us to
02154   // handle the following, which is supported by GCC (and part of the design).
02155   //
02156   // @interface Foo
02157   // @property double bar;
02158   // @end
02159   //
02160   // void thisIsUnfortunate() {
02161   //   id foo;
02162   //   double bar = [foo bar];
02163   // }
02164   //
02165   if (GetterMethod)
02166     AddInstanceMethodToGlobalPool(GetterMethod);
02167   if (SetterMethod)
02168     AddInstanceMethodToGlobalPool(SetterMethod);
02169 
02170   ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(CD);
02171   if (!CurrentClass) {
02172     if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(CD))
02173       CurrentClass = Cat->getClassInterface();
02174     else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(CD))
02175       CurrentClass = Impl->getClassInterface();
02176   }
02177   if (GetterMethod)
02178     CheckObjCMethodOverrides(GetterMethod, CurrentClass, Sema::RTC_Unknown);
02179   if (SetterMethod)
02180     CheckObjCMethodOverrides(SetterMethod, CurrentClass, Sema::RTC_Unknown);
02181 }
02182 
02183 void Sema::CheckObjCPropertyAttributes(Decl *PDecl,
02184                                        SourceLocation Loc,
02185                                        unsigned &Attributes,
02186                                        bool propertyInPrimaryClass) {
02187   // FIXME: Improve the reported location.
02188   if (!PDecl || PDecl->isInvalidDecl())
02189     return;
02190   
02191   if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
02192       (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
02193     Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02194     << "readonly" << "readwrite";
02195   
02196   ObjCPropertyDecl *PropertyDecl = cast<ObjCPropertyDecl>(PDecl);
02197   QualType PropertyTy = PropertyDecl->getType();
02198   unsigned PropertyOwnership = getOwnershipRule(Attributes);
02199 
02200   // 'readonly' property with no obvious lifetime.
02201   // its life time will be determined by its backing ivar.
02202   if (getLangOpts().ObjCAutoRefCount &&
02203       Attributes & ObjCDeclSpec::DQ_PR_readonly &&
02204       PropertyTy->isObjCRetainableType() &&
02205       !PropertyOwnership)
02206     return;
02207 
02208   // Check for copy or retain on non-object types.
02209   if ((Attributes & (ObjCDeclSpec::DQ_PR_weak | ObjCDeclSpec::DQ_PR_copy |
02210                     ObjCDeclSpec::DQ_PR_retain | ObjCDeclSpec::DQ_PR_strong)) &&
02211       !PropertyTy->isObjCRetainableType() &&
02212       !PropertyDecl->hasAttr<ObjCNSObjectAttr>()) {
02213     Diag(Loc, diag::err_objc_property_requires_object)
02214       << (Attributes & ObjCDeclSpec::DQ_PR_weak ? "weak" :
02215           Attributes & ObjCDeclSpec::DQ_PR_copy ? "copy" : "retain (or strong)");
02216     Attributes &= ~(ObjCDeclSpec::DQ_PR_weak   | ObjCDeclSpec::DQ_PR_copy |
02217                     ObjCDeclSpec::DQ_PR_retain | ObjCDeclSpec::DQ_PR_strong);
02218     PropertyDecl->setInvalidDecl();
02219   }
02220 
02221   // Check for more than one of { assign, copy, retain }.
02222   if (Attributes & ObjCDeclSpec::DQ_PR_assign) {
02223     if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
02224       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02225         << "assign" << "copy";
02226       Attributes &= ~ObjCDeclSpec::DQ_PR_copy;
02227     }
02228     if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
02229       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02230         << "assign" << "retain";
02231       Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
02232     }
02233     if (Attributes & ObjCDeclSpec::DQ_PR_strong) {
02234       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02235         << "assign" << "strong";
02236       Attributes &= ~ObjCDeclSpec::DQ_PR_strong;
02237     }
02238     if (getLangOpts().ObjCAutoRefCount  &&
02239         (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
02240       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02241         << "assign" << "weak";
02242       Attributes &= ~ObjCDeclSpec::DQ_PR_weak;
02243     }
02244     if (PropertyDecl->hasAttr<IBOutletCollectionAttr>())
02245       Diag(Loc, diag::warn_iboutletcollection_property_assign);
02246   } else if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) {
02247     if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
02248       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02249         << "unsafe_unretained" << "copy";
02250       Attributes &= ~ObjCDeclSpec::DQ_PR_copy;
02251     }
02252     if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
02253       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02254         << "unsafe_unretained" << "retain";
02255       Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
02256     }
02257     if (Attributes & ObjCDeclSpec::DQ_PR_strong) {
02258       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02259         << "unsafe_unretained" << "strong";
02260       Attributes &= ~ObjCDeclSpec::DQ_PR_strong;
02261     }
02262     if (getLangOpts().ObjCAutoRefCount  &&
02263         (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
02264       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02265         << "unsafe_unretained" << "weak";
02266       Attributes &= ~ObjCDeclSpec::DQ_PR_weak;
02267     }
02268   } else if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
02269     if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
02270       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02271         << "copy" << "retain";
02272       Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
02273     }
02274     if (Attributes & ObjCDeclSpec::DQ_PR_strong) {
02275       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02276         << "copy" << "strong";
02277       Attributes &= ~ObjCDeclSpec::DQ_PR_strong;
02278     }
02279     if (Attributes & ObjCDeclSpec::DQ_PR_weak) {
02280       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02281         << "copy" << "weak";
02282       Attributes &= ~ObjCDeclSpec::DQ_PR_weak;
02283     }
02284   }
02285   else if ((Attributes & ObjCDeclSpec::DQ_PR_retain) &&
02286            (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
02287       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02288         << "retain" << "weak";
02289       Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
02290   }
02291   else if ((Attributes & ObjCDeclSpec::DQ_PR_strong) &&
02292            (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
02293       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02294         << "strong" << "weak";
02295       Attributes &= ~ObjCDeclSpec::DQ_PR_weak;
02296   }
02297 
02298   if (Attributes & ObjCDeclSpec::DQ_PR_weak) {
02299     // 'weak' and 'nonnull' are mutually exclusive.
02300     if (auto nullability = PropertyTy->getNullability(Context)) {
02301       if (*nullability == NullabilityKind::NonNull)
02302         Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02303           << "nonnull" << "weak";
02304     } else {
02305         PropertyTy =
02306           Context.getAttributedType(
02307             AttributedType::getNullabilityAttrKind(NullabilityKind::Nullable),
02308             PropertyTy, PropertyTy);
02309         TypeSourceInfo *TSInfo = PropertyDecl->getTypeSourceInfo();
02310         PropertyDecl->setType(PropertyTy, TSInfo);
02311     }
02312   }
02313 
02314   if ((Attributes & ObjCDeclSpec::DQ_PR_atomic) &&
02315       (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)) {
02316       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
02317         << "atomic" << "nonatomic";
02318       Attributes &= ~ObjCDeclSpec::DQ_PR_atomic;
02319   }
02320 
02321   // Warn if user supplied no assignment attribute, property is
02322   // readwrite, and this is an object type.
02323   if (!(Attributes & (ObjCDeclSpec::DQ_PR_assign | ObjCDeclSpec::DQ_PR_copy |
02324                       ObjCDeclSpec::DQ_PR_unsafe_unretained |
02325                       ObjCDeclSpec::DQ_PR_retain | ObjCDeclSpec::DQ_PR_strong |
02326                       ObjCDeclSpec::DQ_PR_weak)) &&
02327       PropertyTy->isObjCObjectPointerType()) {
02328       if (getLangOpts().ObjCAutoRefCount)
02329         // With arc,  @property definitions should default to (strong) when 
02330         // not specified; including when property is 'readonly'.
02331         PropertyDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong);
02332       else if (!(Attributes & ObjCDeclSpec::DQ_PR_readonly)) {
02333         bool isAnyClassTy = 
02334           (PropertyTy->isObjCClassType() || 
02335            PropertyTy->isObjCQualifiedClassType());
02336         // In non-gc, non-arc mode, 'Class' is treated as a 'void *' no need to
02337         // issue any warning.
02338         if (isAnyClassTy && getLangOpts().getGC() == LangOptions::NonGC)
02339           ;
02340         else if (propertyInPrimaryClass) {
02341           // Don't issue warning on property with no life time in class 
02342           // extension as it is inherited from property in primary class.
02343           // Skip this warning in gc-only mode.
02344           if (getLangOpts().getGC() != LangOptions::GCOnly)
02345             Diag(Loc, diag::warn_objc_property_no_assignment_attribute);
02346 
02347           // If non-gc code warn that this is likely inappropriate.
02348           if (getLangOpts().getGC() == LangOptions::NonGC)
02349             Diag(Loc, diag::warn_objc_property_default_assign_on_object);
02350         }
02351       }
02352 
02353     // FIXME: Implement warning dependent on NSCopying being
02354     // implemented. See also:
02355     // <rdar://5168496&4855821&5607453&5096644&4947311&5698469&4947014&5168496>
02356     // (please trim this list while you are at it).
02357   }
02358 
02359   if (!(Attributes & ObjCDeclSpec::DQ_PR_copy)
02360       &&!(Attributes & ObjCDeclSpec::DQ_PR_readonly)
02361       && getLangOpts().getGC() == LangOptions::GCOnly
02362       && PropertyTy->isBlockPointerType())
02363     Diag(Loc, diag::warn_objc_property_copy_missing_on_block);
02364   else if ((Attributes & ObjCDeclSpec::DQ_PR_retain) &&
02365            !(Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
02366            !(Attributes & ObjCDeclSpec::DQ_PR_strong) &&
02367            PropertyTy->isBlockPointerType())
02368       Diag(Loc, diag::warn_objc_property_retain_of_block);
02369   
02370   if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
02371       (Attributes & ObjCDeclSpec::DQ_PR_setter))
02372     Diag(Loc, diag::warn_objc_readonly_property_has_setter);
02373       
02374 }