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