xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaObjCProperty.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1 //===--- SemaObjCProperty.cpp - Semantic Analysis for ObjC @property ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for Objective C @property and
10 //  @synthesize declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTMutationListener.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/AST/ExprObjC.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Lex/Lexer.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/Sema/Initialization.h"
22 #include "clang/Sema/SemaInternal.h"
23 #include "clang/Sema/SemaObjC.h"
24 #include "llvm/ADT/DenseSet.h"
25 #include "llvm/ADT/SmallString.h"
26 
27 using namespace clang;
28 
29 //===----------------------------------------------------------------------===//
30 // Grammar actions.
31 //===----------------------------------------------------------------------===//
32 
33 /// getImpliedARCOwnership - Given a set of property attributes and a
34 /// type, infer an expected lifetime.  The type's ownership qualification
35 /// is not considered.
36 ///
37 /// Returns OCL_None if the attributes as stated do not imply an ownership.
38 /// Never returns OCL_Autoreleasing.
39 static Qualifiers::ObjCLifetime
getImpliedARCOwnership(ObjCPropertyAttribute::Kind attrs,QualType type)40 getImpliedARCOwnership(ObjCPropertyAttribute::Kind attrs, QualType type) {
41   // retain, strong, copy, weak, and unsafe_unretained are only legal
42   // on properties of retainable pointer type.
43   if (attrs &
44       (ObjCPropertyAttribute::kind_retain | ObjCPropertyAttribute::kind_strong |
45        ObjCPropertyAttribute::kind_copy)) {
46     return Qualifiers::OCL_Strong;
47   } else if (attrs & ObjCPropertyAttribute::kind_weak) {
48     return Qualifiers::OCL_Weak;
49   } else if (attrs & ObjCPropertyAttribute::kind_unsafe_unretained) {
50     return Qualifiers::OCL_ExplicitNone;
51   }
52 
53   // assign can appear on other types, so we have to check the
54   // property type.
55   if (attrs & ObjCPropertyAttribute::kind_assign &&
56       type->isObjCRetainableType()) {
57     return Qualifiers::OCL_ExplicitNone;
58   }
59 
60   return Qualifiers::OCL_None;
61 }
62 
63 /// Check the internal consistency of a property declaration with
64 /// an explicit ownership qualifier.
checkPropertyDeclWithOwnership(Sema & S,ObjCPropertyDecl * property)65 static void checkPropertyDeclWithOwnership(Sema &S,
66                                            ObjCPropertyDecl *property) {
67   if (property->isInvalidDecl()) return;
68 
69   ObjCPropertyAttribute::Kind propertyKind = property->getPropertyAttributes();
70   Qualifiers::ObjCLifetime propertyLifetime
71     = property->getType().getObjCLifetime();
72 
73   assert(propertyLifetime != Qualifiers::OCL_None);
74 
75   Qualifiers::ObjCLifetime expectedLifetime
76     = getImpliedARCOwnership(propertyKind, property->getType());
77   if (!expectedLifetime) {
78     // We have a lifetime qualifier but no dominating property
79     // attribute.  That's okay, but restore reasonable invariants by
80     // setting the property attribute according to the lifetime
81     // qualifier.
82     ObjCPropertyAttribute::Kind attr;
83     if (propertyLifetime == Qualifiers::OCL_Strong) {
84       attr = ObjCPropertyAttribute::kind_strong;
85     } else if (propertyLifetime == Qualifiers::OCL_Weak) {
86       attr = ObjCPropertyAttribute::kind_weak;
87     } else {
88       assert(propertyLifetime == Qualifiers::OCL_ExplicitNone);
89       attr = ObjCPropertyAttribute::kind_unsafe_unretained;
90     }
91     property->setPropertyAttributes(attr);
92     return;
93   }
94 
95   if (propertyLifetime == expectedLifetime) return;
96 
97   property->setInvalidDecl();
98   S.Diag(property->getLocation(),
99          diag::err_arc_inconsistent_property_ownership)
100     << property->getDeclName()
101     << expectedLifetime
102     << propertyLifetime;
103 }
104 
105 /// Check this Objective-C property against a property declared in the
106 /// given protocol.
107 static void
CheckPropertyAgainstProtocol(Sema & S,ObjCPropertyDecl * Prop,ObjCProtocolDecl * Proto,llvm::SmallPtrSetImpl<ObjCProtocolDecl * > & Known)108 CheckPropertyAgainstProtocol(Sema &S, ObjCPropertyDecl *Prop,
109                              ObjCProtocolDecl *Proto,
110                              llvm::SmallPtrSetImpl<ObjCProtocolDecl *> &Known) {
111   // Have we seen this protocol before?
112   if (!Known.insert(Proto).second)
113     return;
114 
115   // Look for a property with the same name.
116   if (ObjCPropertyDecl *ProtoProp = Proto->getProperty(
117           Prop->getIdentifier(), Prop->isInstanceProperty())) {
118     S.ObjC().DiagnosePropertyMismatch(Prop, ProtoProp, Proto->getIdentifier(),
119                                       true);
120     return;
121   }
122 
123   // Check this property against any protocols we inherit.
124   for (auto *P : Proto->protocols())
125     CheckPropertyAgainstProtocol(S, Prop, P, Known);
126 }
127 
deducePropertyOwnershipFromType(Sema & S,QualType T)128 static unsigned deducePropertyOwnershipFromType(Sema &S, QualType T) {
129   // In GC mode, just look for the __weak qualifier.
130   if (S.getLangOpts().getGC() != LangOptions::NonGC) {
131     if (T.isObjCGCWeak())
132       return ObjCPropertyAttribute::kind_weak;
133 
134     // In ARC/MRC, look for an explicit ownership qualifier.
135     // For some reason, this only applies to __weak.
136   } else if (auto ownership = T.getObjCLifetime()) {
137     switch (ownership) {
138     case Qualifiers::OCL_Weak:
139       return ObjCPropertyAttribute::kind_weak;
140     case Qualifiers::OCL_Strong:
141       return ObjCPropertyAttribute::kind_strong;
142     case Qualifiers::OCL_ExplicitNone:
143       return ObjCPropertyAttribute::kind_unsafe_unretained;
144     case Qualifiers::OCL_Autoreleasing:
145     case Qualifiers::OCL_None:
146       return 0;
147     }
148     llvm_unreachable("bad qualifier");
149   }
150 
151   return 0;
152 }
153 
154 static const unsigned OwnershipMask =
155     (ObjCPropertyAttribute::kind_assign | ObjCPropertyAttribute::kind_retain |
156      ObjCPropertyAttribute::kind_copy | ObjCPropertyAttribute::kind_weak |
157      ObjCPropertyAttribute::kind_strong |
158      ObjCPropertyAttribute::kind_unsafe_unretained);
159 
getOwnershipRule(unsigned attr)160 static unsigned getOwnershipRule(unsigned attr) {
161   unsigned result = attr & OwnershipMask;
162 
163   // From an ownership perspective, assign and unsafe_unretained are
164   // identical; make sure one also implies the other.
165   if (result & (ObjCPropertyAttribute::kind_assign |
166                 ObjCPropertyAttribute::kind_unsafe_unretained)) {
167     result |= ObjCPropertyAttribute::kind_assign |
168               ObjCPropertyAttribute::kind_unsafe_unretained;
169   }
170 
171   return result;
172 }
173 
ActOnProperty(Scope * S,SourceLocation AtLoc,SourceLocation LParenLoc,FieldDeclarator & FD,ObjCDeclSpec & ODS,Selector GetterSel,Selector SetterSel,tok::ObjCKeywordKind MethodImplKind,DeclContext * lexicalDC)174 Decl *SemaObjC::ActOnProperty(Scope *S, SourceLocation AtLoc,
175                               SourceLocation LParenLoc, FieldDeclarator &FD,
176                               ObjCDeclSpec &ODS, Selector GetterSel,
177                               Selector SetterSel,
178                               tok::ObjCKeywordKind MethodImplKind,
179                               DeclContext *lexicalDC) {
180   unsigned Attributes = ODS.getPropertyAttributes();
181   FD.D.setObjCWeakProperty((Attributes & ObjCPropertyAttribute::kind_weak) !=
182                            0);
183   TypeSourceInfo *TSI = SemaRef.GetTypeForDeclarator(FD.D);
184   QualType T = TSI->getType();
185   if (!getOwnershipRule(Attributes)) {
186     Attributes |= deducePropertyOwnershipFromType(SemaRef, T);
187   }
188   bool isReadWrite = ((Attributes & ObjCPropertyAttribute::kind_readwrite) ||
189                       // default is readwrite!
190                       !(Attributes & ObjCPropertyAttribute::kind_readonly));
191 
192   // Proceed with constructing the ObjCPropertyDecls.
193   ObjCContainerDecl *ClassDecl = cast<ObjCContainerDecl>(SemaRef.CurContext);
194   ObjCPropertyDecl *Res = nullptr;
195   if (ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
196     if (CDecl->IsClassExtension()) {
197       Res = HandlePropertyInClassExtension(S, AtLoc, LParenLoc,
198                                            FD,
199                                            GetterSel, ODS.getGetterNameLoc(),
200                                            SetterSel, ODS.getSetterNameLoc(),
201                                            isReadWrite, Attributes,
202                                            ODS.getPropertyAttributes(),
203                                            T, TSI, MethodImplKind);
204       if (!Res)
205         return nullptr;
206     }
207   }
208 
209   if (!Res) {
210     Res = CreatePropertyDecl(S, ClassDecl, AtLoc, LParenLoc, FD,
211                              GetterSel, ODS.getGetterNameLoc(), SetterSel,
212                              ODS.getSetterNameLoc(), isReadWrite, Attributes,
213                              ODS.getPropertyAttributes(), T, TSI,
214                              MethodImplKind);
215     if (lexicalDC)
216       Res->setLexicalDeclContext(lexicalDC);
217   }
218 
219   // Validate the attributes on the @property.
220   CheckObjCPropertyAttributes(Res, AtLoc, Attributes,
221                               (isa<ObjCInterfaceDecl>(ClassDecl) ||
222                                isa<ObjCProtocolDecl>(ClassDecl)));
223 
224   // Check consistency if the type has explicit ownership qualification.
225   if (Res->getType().getObjCLifetime())
226     checkPropertyDeclWithOwnership(SemaRef, Res);
227 
228   llvm::SmallPtrSet<ObjCProtocolDecl *, 16> KnownProtos;
229   if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
230     // For a class, compare the property against a property in our superclass.
231     bool FoundInSuper = false;
232     ObjCInterfaceDecl *CurrentInterfaceDecl = IFace;
233     while (ObjCInterfaceDecl *Super = CurrentInterfaceDecl->getSuperClass()) {
234       if (ObjCPropertyDecl *SuperProp = Super->getProperty(
235               Res->getIdentifier(), Res->isInstanceProperty())) {
236         DiagnosePropertyMismatch(Res, SuperProp, Super->getIdentifier(), false);
237         FoundInSuper = true;
238         break;
239       }
240       CurrentInterfaceDecl = Super;
241     }
242 
243     if (FoundInSuper) {
244       // Also compare the property against a property in our protocols.
245       for (auto *P : CurrentInterfaceDecl->protocols()) {
246         CheckPropertyAgainstProtocol(SemaRef, Res, P, KnownProtos);
247       }
248     } else {
249       // Slower path: look in all protocols we referenced.
250       for (auto *P : IFace->all_referenced_protocols()) {
251         CheckPropertyAgainstProtocol(SemaRef, Res, P, KnownProtos);
252       }
253     }
254   } else if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
255     // We don't check if class extension. Because properties in class extension
256     // are meant to override some of the attributes and checking has already done
257     // when property in class extension is constructed.
258     if (!Cat->IsClassExtension())
259       for (auto *P : Cat->protocols())
260         CheckPropertyAgainstProtocol(SemaRef, Res, P, KnownProtos);
261   } else {
262     ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(ClassDecl);
263     for (auto *P : Proto->protocols())
264       CheckPropertyAgainstProtocol(SemaRef, Res, P, KnownProtos);
265   }
266 
267   SemaRef.ActOnDocumentableDecl(Res);
268   return Res;
269 }
270 
271 static ObjCPropertyAttribute::Kind
makePropertyAttributesAsWritten(unsigned Attributes)272 makePropertyAttributesAsWritten(unsigned Attributes) {
273   unsigned attributesAsWritten = 0;
274   if (Attributes & ObjCPropertyAttribute::kind_readonly)
275     attributesAsWritten |= ObjCPropertyAttribute::kind_readonly;
276   if (Attributes & ObjCPropertyAttribute::kind_readwrite)
277     attributesAsWritten |= ObjCPropertyAttribute::kind_readwrite;
278   if (Attributes & ObjCPropertyAttribute::kind_getter)
279     attributesAsWritten |= ObjCPropertyAttribute::kind_getter;
280   if (Attributes & ObjCPropertyAttribute::kind_setter)
281     attributesAsWritten |= ObjCPropertyAttribute::kind_setter;
282   if (Attributes & ObjCPropertyAttribute::kind_assign)
283     attributesAsWritten |= ObjCPropertyAttribute::kind_assign;
284   if (Attributes & ObjCPropertyAttribute::kind_retain)
285     attributesAsWritten |= ObjCPropertyAttribute::kind_retain;
286   if (Attributes & ObjCPropertyAttribute::kind_strong)
287     attributesAsWritten |= ObjCPropertyAttribute::kind_strong;
288   if (Attributes & ObjCPropertyAttribute::kind_weak)
289     attributesAsWritten |= ObjCPropertyAttribute::kind_weak;
290   if (Attributes & ObjCPropertyAttribute::kind_copy)
291     attributesAsWritten |= ObjCPropertyAttribute::kind_copy;
292   if (Attributes & ObjCPropertyAttribute::kind_unsafe_unretained)
293     attributesAsWritten |= ObjCPropertyAttribute::kind_unsafe_unretained;
294   if (Attributes & ObjCPropertyAttribute::kind_nonatomic)
295     attributesAsWritten |= ObjCPropertyAttribute::kind_nonatomic;
296   if (Attributes & ObjCPropertyAttribute::kind_atomic)
297     attributesAsWritten |= ObjCPropertyAttribute::kind_atomic;
298   if (Attributes & ObjCPropertyAttribute::kind_class)
299     attributesAsWritten |= ObjCPropertyAttribute::kind_class;
300   if (Attributes & ObjCPropertyAttribute::kind_direct)
301     attributesAsWritten |= ObjCPropertyAttribute::kind_direct;
302 
303   return (ObjCPropertyAttribute::Kind)attributesAsWritten;
304 }
305 
LocPropertyAttribute(ASTContext & Context,const char * attrName,SourceLocation LParenLoc,SourceLocation & Loc)306 static bool LocPropertyAttribute( ASTContext &Context, const char *attrName,
307                                  SourceLocation LParenLoc, SourceLocation &Loc) {
308   if (LParenLoc.isMacroID())
309     return false;
310 
311   SourceManager &SM = Context.getSourceManager();
312   std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(LParenLoc);
313   // Try to load the file buffer.
314   bool invalidTemp = false;
315   StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
316   if (invalidTemp)
317     return false;
318   const char *tokenBegin = file.data() + locInfo.second;
319 
320   // Lex from the start of the given location.
321   Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
322               Context.getLangOpts(),
323               file.begin(), tokenBegin, file.end());
324   Token Tok;
325   do {
326     lexer.LexFromRawLexer(Tok);
327     if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == attrName) {
328       Loc = Tok.getLocation();
329       return true;
330     }
331   } while (Tok.isNot(tok::r_paren));
332   return false;
333 }
334 
335 /// Check for a mismatch in the atomicity of the given properties.
checkAtomicPropertyMismatch(Sema & S,ObjCPropertyDecl * OldProperty,ObjCPropertyDecl * NewProperty,bool PropagateAtomicity)336 static void checkAtomicPropertyMismatch(Sema &S,
337                                         ObjCPropertyDecl *OldProperty,
338                                         ObjCPropertyDecl *NewProperty,
339                                         bool PropagateAtomicity) {
340   // If the atomicity of both matches, we're done.
341   bool OldIsAtomic = (OldProperty->getPropertyAttributes() &
342                       ObjCPropertyAttribute::kind_nonatomic) == 0;
343   bool NewIsAtomic = (NewProperty->getPropertyAttributes() &
344                       ObjCPropertyAttribute::kind_nonatomic) == 0;
345   if (OldIsAtomic == NewIsAtomic) return;
346 
347   // Determine whether the given property is readonly and implicitly
348   // atomic.
349   auto isImplicitlyReadonlyAtomic = [](ObjCPropertyDecl *Property) -> bool {
350     // Is it readonly?
351     auto Attrs = Property->getPropertyAttributes();
352     if ((Attrs & ObjCPropertyAttribute::kind_readonly) == 0)
353       return false;
354 
355     // Is it nonatomic?
356     if (Attrs & ObjCPropertyAttribute::kind_nonatomic)
357       return false;
358 
359     // Was 'atomic' specified directly?
360     if (Property->getPropertyAttributesAsWritten() &
361         ObjCPropertyAttribute::kind_atomic)
362       return false;
363 
364     return true;
365   };
366 
367   // If we're allowed to propagate atomicity, and the new property did
368   // not specify atomicity at all, propagate.
369   const unsigned AtomicityMask = (ObjCPropertyAttribute::kind_atomic |
370                                   ObjCPropertyAttribute::kind_nonatomic);
371   if (PropagateAtomicity &&
372       ((NewProperty->getPropertyAttributesAsWritten() & AtomicityMask) == 0)) {
373     unsigned Attrs = NewProperty->getPropertyAttributes();
374     Attrs = Attrs & ~AtomicityMask;
375     if (OldIsAtomic)
376       Attrs |= ObjCPropertyAttribute::kind_atomic;
377     else
378       Attrs |= ObjCPropertyAttribute::kind_nonatomic;
379 
380     NewProperty->overwritePropertyAttributes(Attrs);
381     return;
382   }
383 
384   // One of the properties is atomic; if it's a readonly property, and
385   // 'atomic' wasn't explicitly specified, we're okay.
386   if ((OldIsAtomic && isImplicitlyReadonlyAtomic(OldProperty)) ||
387       (NewIsAtomic && isImplicitlyReadonlyAtomic(NewProperty)))
388     return;
389 
390   // Diagnose the conflict.
391   const IdentifierInfo *OldContextName;
392   auto *OldDC = OldProperty->getDeclContext();
393   if (auto Category = dyn_cast<ObjCCategoryDecl>(OldDC))
394     OldContextName = Category->getClassInterface()->getIdentifier();
395   else
396     OldContextName = cast<ObjCContainerDecl>(OldDC)->getIdentifier();
397 
398   S.Diag(NewProperty->getLocation(), diag::warn_property_attribute)
399     << NewProperty->getDeclName() << "atomic"
400     << OldContextName;
401   S.Diag(OldProperty->getLocation(), diag::note_property_declare);
402 }
403 
HandlePropertyInClassExtension(Scope * S,SourceLocation AtLoc,SourceLocation LParenLoc,FieldDeclarator & FD,Selector GetterSel,SourceLocation GetterNameLoc,Selector SetterSel,SourceLocation SetterNameLoc,const bool isReadWrite,unsigned & Attributes,const unsigned AttributesAsWritten,QualType T,TypeSourceInfo * TSI,tok::ObjCKeywordKind MethodImplKind)404 ObjCPropertyDecl *SemaObjC::HandlePropertyInClassExtension(
405     Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc,
406     FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc,
407     Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite,
408     unsigned &Attributes, const unsigned AttributesAsWritten, QualType T,
409     TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind) {
410   ObjCCategoryDecl *CDecl = cast<ObjCCategoryDecl>(SemaRef.CurContext);
411   // Diagnose if this property is already in continuation class.
412   DeclContext *DC = SemaRef.CurContext;
413   const IdentifierInfo *PropertyId = FD.D.getIdentifier();
414   ObjCInterfaceDecl *CCPrimary = CDecl->getClassInterface();
415 
416   // We need to look in the @interface to see if the @property was
417   // already declared.
418   if (!CCPrimary) {
419     Diag(CDecl->getLocation(), diag::err_continuation_class);
420     return nullptr;
421   }
422 
423   bool isClassProperty =
424       (AttributesAsWritten & ObjCPropertyAttribute::kind_class) ||
425       (Attributes & ObjCPropertyAttribute::kind_class);
426 
427   // Find the property in the extended class's primary class or
428   // extensions.
429   ObjCPropertyDecl *PIDecl = CCPrimary->FindPropertyVisibleInPrimaryClass(
430       PropertyId, ObjCPropertyDecl::getQueryKind(isClassProperty));
431 
432   // If we found a property in an extension, complain.
433   if (PIDecl && isa<ObjCCategoryDecl>(PIDecl->getDeclContext())) {
434     Diag(AtLoc, diag::err_duplicate_property);
435     Diag(PIDecl->getLocation(), diag::note_property_declare);
436     return nullptr;
437   }
438 
439   // Check for consistency with the previous declaration, if there is one.
440   if (PIDecl) {
441     // A readonly property declared in the primary class can be refined
442     // by adding a readwrite property within an extension.
443     // Anything else is an error.
444     if (!(PIDecl->isReadOnly() && isReadWrite)) {
445       // Tailor the diagnostics for the common case where a readwrite
446       // property is declared both in the @interface and the continuation.
447       // This is a common error where the user often intended the original
448       // declaration to be readonly.
449       unsigned diag =
450           (Attributes & ObjCPropertyAttribute::kind_readwrite) &&
451                   (PIDecl->getPropertyAttributesAsWritten() &
452                    ObjCPropertyAttribute::kind_readwrite)
453               ? diag::err_use_continuation_class_redeclaration_readwrite
454               : diag::err_use_continuation_class;
455       Diag(AtLoc, diag)
456         << CCPrimary->getDeclName();
457       Diag(PIDecl->getLocation(), diag::note_property_declare);
458       return nullptr;
459     }
460 
461     // Check for consistency of getters.
462     if (PIDecl->getGetterName() != GetterSel) {
463      // If the getter was written explicitly, complain.
464      if (AttributesAsWritten & ObjCPropertyAttribute::kind_getter) {
465        Diag(AtLoc, diag::warn_property_redecl_getter_mismatch)
466            << PIDecl->getGetterName() << GetterSel;
467        Diag(PIDecl->getLocation(), diag::note_property_declare);
468      }
469 
470       // Always adopt the getter from the original declaration.
471       GetterSel = PIDecl->getGetterName();
472       Attributes |= ObjCPropertyAttribute::kind_getter;
473     }
474 
475     // Check consistency of ownership.
476     unsigned ExistingOwnership
477       = getOwnershipRule(PIDecl->getPropertyAttributes());
478     unsigned NewOwnership = getOwnershipRule(Attributes);
479     if (ExistingOwnership && NewOwnership != ExistingOwnership) {
480       // If the ownership was written explicitly, complain.
481       if (getOwnershipRule(AttributesAsWritten)) {
482         Diag(AtLoc, diag::warn_property_attr_mismatch);
483         Diag(PIDecl->getLocation(), diag::note_property_declare);
484       }
485 
486       // Take the ownership from the original property.
487       Attributes = (Attributes & ~OwnershipMask) | ExistingOwnership;
488     }
489 
490     // If the redeclaration is 'weak' but the original property is not,
491     if ((Attributes & ObjCPropertyAttribute::kind_weak) &&
492         !(PIDecl->getPropertyAttributesAsWritten() &
493           ObjCPropertyAttribute::kind_weak) &&
494         PIDecl->getType()->getAs<ObjCObjectPointerType>() &&
495         PIDecl->getType().getObjCLifetime() == Qualifiers::OCL_None) {
496       Diag(AtLoc, diag::warn_property_implicitly_mismatched);
497       Diag(PIDecl->getLocation(), diag::note_property_declare);
498     }
499   }
500 
501   // Create a new ObjCPropertyDecl with the DeclContext being
502   // the class extension.
503   ObjCPropertyDecl *PDecl = CreatePropertyDecl(S, CDecl, AtLoc, LParenLoc,
504                                                FD, GetterSel, GetterNameLoc,
505                                                SetterSel, SetterNameLoc,
506                                                isReadWrite,
507                                                Attributes, AttributesAsWritten,
508                                                T, TSI, MethodImplKind, DC);
509   ASTContext &Context = getASTContext();
510   // If there was no declaration of a property with the same name in
511   // the primary class, we're done.
512   if (!PIDecl) {
513     ProcessPropertyDecl(PDecl);
514     return PDecl;
515   }
516 
517   if (!Context.hasSameType(PIDecl->getType(), PDecl->getType())) {
518     bool IncompatibleObjC = false;
519     QualType ConvertedType;
520     // Relax the strict type matching for property type in continuation class.
521     // Allow property object type of continuation class to be different as long
522     // as it narrows the object type in its primary class property. Note that
523     // this conversion is safe only because the wider type is for a 'readonly'
524     // property in primary class and 'narrowed' type for a 'readwrite' property
525     // in continuation class.
526     QualType PrimaryClassPropertyT = Context.getCanonicalType(PIDecl->getType());
527     QualType ClassExtPropertyT = Context.getCanonicalType(PDecl->getType());
528     if (!isa<ObjCObjectPointerType>(PrimaryClassPropertyT) ||
529         !isa<ObjCObjectPointerType>(ClassExtPropertyT) ||
530         (!SemaRef.isObjCPointerConversion(ClassExtPropertyT,
531                                           PrimaryClassPropertyT, ConvertedType,
532                                           IncompatibleObjC)) ||
533         IncompatibleObjC) {
534       Diag(AtLoc,
535           diag::err_type_mismatch_continuation_class) << PDecl->getType();
536       Diag(PIDecl->getLocation(), diag::note_property_declare);
537       return nullptr;
538     }
539   }
540 
541   // Check that atomicity of property in class extension matches the previous
542   // declaration.
543   checkAtomicPropertyMismatch(SemaRef, PIDecl, PDecl, true);
544 
545   // Make sure getter/setter are appropriately synthesized.
546   ProcessPropertyDecl(PDecl);
547   return PDecl;
548 }
549 
CreatePropertyDecl(Scope * S,ObjCContainerDecl * CDecl,SourceLocation AtLoc,SourceLocation LParenLoc,FieldDeclarator & FD,Selector GetterSel,SourceLocation GetterNameLoc,Selector SetterSel,SourceLocation SetterNameLoc,const bool isReadWrite,const unsigned Attributes,const unsigned AttributesAsWritten,QualType T,TypeSourceInfo * TInfo,tok::ObjCKeywordKind MethodImplKind,DeclContext * lexicalDC)550 ObjCPropertyDecl *SemaObjC::CreatePropertyDecl(
551     Scope *S, ObjCContainerDecl *CDecl, SourceLocation AtLoc,
552     SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel,
553     SourceLocation GetterNameLoc, Selector SetterSel,
554     SourceLocation SetterNameLoc, const bool isReadWrite,
555     const unsigned Attributes, const unsigned AttributesAsWritten, QualType T,
556     TypeSourceInfo *TInfo, tok::ObjCKeywordKind MethodImplKind,
557     DeclContext *lexicalDC) {
558   ASTContext &Context = getASTContext();
559   const IdentifierInfo *PropertyId = FD.D.getIdentifier();
560 
561   // Property defaults to 'assign' if it is readwrite, unless this is ARC
562   // and the type is retainable.
563   bool isAssign;
564   if (Attributes & (ObjCPropertyAttribute::kind_assign |
565                     ObjCPropertyAttribute::kind_unsafe_unretained)) {
566     isAssign = true;
567   } else if (getOwnershipRule(Attributes) || !isReadWrite) {
568     isAssign = false;
569   } else {
570     isAssign = (!getLangOpts().ObjCAutoRefCount ||
571                 !T->isObjCRetainableType());
572   }
573 
574   // Issue a warning if property is 'assign' as default and its
575   // object, which is gc'able conforms to NSCopying protocol
576   if (getLangOpts().getGC() != LangOptions::NonGC && isAssign &&
577       !(Attributes & ObjCPropertyAttribute::kind_assign)) {
578     if (const ObjCObjectPointerType *ObjPtrTy =
579           T->getAs<ObjCObjectPointerType>()) {
580       ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
581       if (IDecl)
582         if (ObjCProtocolDecl* PNSCopying =
583             LookupProtocol(&Context.Idents.get("NSCopying"), AtLoc))
584           if (IDecl->ClassImplementsProtocol(PNSCopying, true))
585             Diag(AtLoc, diag::warn_implements_nscopying) << PropertyId;
586     }
587   }
588 
589   if (T->isObjCObjectType()) {
590     SourceLocation StarLoc = TInfo->getTypeLoc().getEndLoc();
591     StarLoc = SemaRef.getLocForEndOfToken(StarLoc);
592     Diag(FD.D.getIdentifierLoc(), diag::err_statically_allocated_object)
593       << FixItHint::CreateInsertion(StarLoc, "*");
594     T = Context.getObjCObjectPointerType(T);
595     SourceLocation TLoc = TInfo->getTypeLoc().getBeginLoc();
596     TInfo = Context.getTrivialTypeSourceInfo(T, TLoc);
597   }
598 
599   DeclContext *DC = CDecl;
600   ObjCPropertyDecl *PDecl = ObjCPropertyDecl::Create(Context, DC,
601                                                      FD.D.getIdentifierLoc(),
602                                                      PropertyId, AtLoc,
603                                                      LParenLoc, T, TInfo);
604 
605   bool isClassProperty =
606       (AttributesAsWritten & ObjCPropertyAttribute::kind_class) ||
607       (Attributes & ObjCPropertyAttribute::kind_class);
608   // Class property and instance property can have the same name.
609   if (ObjCPropertyDecl *prevDecl = ObjCPropertyDecl::findPropertyDecl(
610           DC, PropertyId, ObjCPropertyDecl::getQueryKind(isClassProperty))) {
611     Diag(PDecl->getLocation(), diag::err_duplicate_property);
612     Diag(prevDecl->getLocation(), diag::note_property_declare);
613     PDecl->setInvalidDecl();
614   }
615   else {
616     DC->addDecl(PDecl);
617     if (lexicalDC)
618       PDecl->setLexicalDeclContext(lexicalDC);
619   }
620 
621   if (T->isArrayType() || T->isFunctionType()) {
622     Diag(AtLoc, diag::err_property_type) << T;
623     PDecl->setInvalidDecl();
624   }
625 
626   // Regardless of setter/getter attribute, we save the default getter/setter
627   // selector names in anticipation of declaration of setter/getter methods.
628   PDecl->setGetterName(GetterSel, GetterNameLoc);
629   PDecl->setSetterName(SetterSel, SetterNameLoc);
630   PDecl->setPropertyAttributesAsWritten(
631                           makePropertyAttributesAsWritten(AttributesAsWritten));
632 
633   SemaRef.ProcessDeclAttributes(S, PDecl, FD.D);
634 
635   if (Attributes & ObjCPropertyAttribute::kind_readonly)
636     PDecl->setPropertyAttributes(ObjCPropertyAttribute::kind_readonly);
637 
638   if (Attributes & ObjCPropertyAttribute::kind_getter)
639     PDecl->setPropertyAttributes(ObjCPropertyAttribute::kind_getter);
640 
641   if (Attributes & ObjCPropertyAttribute::kind_setter)
642     PDecl->setPropertyAttributes(ObjCPropertyAttribute::kind_setter);
643 
644   if (isReadWrite)
645     PDecl->setPropertyAttributes(ObjCPropertyAttribute::kind_readwrite);
646 
647   if (Attributes & ObjCPropertyAttribute::kind_retain)
648     PDecl->setPropertyAttributes(ObjCPropertyAttribute::kind_retain);
649 
650   if (Attributes & ObjCPropertyAttribute::kind_strong)
651     PDecl->setPropertyAttributes(ObjCPropertyAttribute::kind_strong);
652 
653   if (Attributes & ObjCPropertyAttribute::kind_weak)
654     PDecl->setPropertyAttributes(ObjCPropertyAttribute::kind_weak);
655 
656   if (Attributes & ObjCPropertyAttribute::kind_copy)
657     PDecl->setPropertyAttributes(ObjCPropertyAttribute::kind_copy);
658 
659   if (Attributes & ObjCPropertyAttribute::kind_unsafe_unretained)
660     PDecl->setPropertyAttributes(ObjCPropertyAttribute::kind_unsafe_unretained);
661 
662   if (isAssign)
663     PDecl->setPropertyAttributes(ObjCPropertyAttribute::kind_assign);
664 
665   // In the semantic attributes, one of nonatomic or atomic is always set.
666   if (Attributes & ObjCPropertyAttribute::kind_nonatomic)
667     PDecl->setPropertyAttributes(ObjCPropertyAttribute::kind_nonatomic);
668   else
669     PDecl->setPropertyAttributes(ObjCPropertyAttribute::kind_atomic);
670 
671   // 'unsafe_unretained' is alias for 'assign'.
672   if (Attributes & ObjCPropertyAttribute::kind_unsafe_unretained)
673     PDecl->setPropertyAttributes(ObjCPropertyAttribute::kind_assign);
674   if (isAssign)
675     PDecl->setPropertyAttributes(ObjCPropertyAttribute::kind_unsafe_unretained);
676 
677   if (MethodImplKind == tok::objc_required)
678     PDecl->setPropertyImplementation(ObjCPropertyDecl::Required);
679   else if (MethodImplKind == tok::objc_optional)
680     PDecl->setPropertyImplementation(ObjCPropertyDecl::Optional);
681 
682   if (Attributes & ObjCPropertyAttribute::kind_nullability)
683     PDecl->setPropertyAttributes(ObjCPropertyAttribute::kind_nullability);
684 
685   if (Attributes & ObjCPropertyAttribute::kind_null_resettable)
686     PDecl->setPropertyAttributes(ObjCPropertyAttribute::kind_null_resettable);
687 
688   if (Attributes & ObjCPropertyAttribute::kind_class)
689     PDecl->setPropertyAttributes(ObjCPropertyAttribute::kind_class);
690 
691   if ((Attributes & ObjCPropertyAttribute::kind_direct) ||
692       CDecl->hasAttr<ObjCDirectMembersAttr>()) {
693     if (isa<ObjCProtocolDecl>(CDecl)) {
694       Diag(PDecl->getLocation(), diag::err_objc_direct_on_protocol) << true;
695     } else if (getLangOpts().ObjCRuntime.allowsDirectDispatch()) {
696       PDecl->setPropertyAttributes(ObjCPropertyAttribute::kind_direct);
697     } else {
698       Diag(PDecl->getLocation(), diag::warn_objc_direct_property_ignored)
699           << PDecl->getDeclName();
700     }
701   }
702 
703   return PDecl;
704 }
705 
checkARCPropertyImpl(Sema & S,SourceLocation propertyImplLoc,ObjCPropertyDecl * property,ObjCIvarDecl * ivar)706 static void checkARCPropertyImpl(Sema &S, SourceLocation propertyImplLoc,
707                                  ObjCPropertyDecl *property,
708                                  ObjCIvarDecl *ivar) {
709   if (property->isInvalidDecl() || ivar->isInvalidDecl()) return;
710 
711   QualType ivarType = ivar->getType();
712   Qualifiers::ObjCLifetime ivarLifetime = ivarType.getObjCLifetime();
713 
714   // The lifetime implied by the property's attributes.
715   Qualifiers::ObjCLifetime propertyLifetime =
716     getImpliedARCOwnership(property->getPropertyAttributes(),
717                            property->getType());
718 
719   // We're fine if they match.
720   if (propertyLifetime == ivarLifetime) return;
721 
722   // None isn't a valid lifetime for an object ivar in ARC, and
723   // __autoreleasing is never valid; don't diagnose twice.
724   if ((ivarLifetime == Qualifiers::OCL_None &&
725        S.getLangOpts().ObjCAutoRefCount) ||
726       ivarLifetime == Qualifiers::OCL_Autoreleasing)
727     return;
728 
729   // If the ivar is private, and it's implicitly __unsafe_unretained
730   // because of its type, then pretend it was actually implicitly
731   // __strong.  This is only sound because we're processing the
732   // property implementation before parsing any method bodies.
733   if (ivarLifetime == Qualifiers::OCL_ExplicitNone &&
734       propertyLifetime == Qualifiers::OCL_Strong &&
735       ivar->getAccessControl() == ObjCIvarDecl::Private) {
736     SplitQualType split = ivarType.split();
737     if (split.Quals.hasObjCLifetime()) {
738       assert(ivarType->isObjCARCImplicitlyUnretainedType());
739       split.Quals.setObjCLifetime(Qualifiers::OCL_Strong);
740       ivarType = S.Context.getQualifiedType(split);
741       ivar->setType(ivarType);
742       return;
743     }
744   }
745 
746   switch (propertyLifetime) {
747   case Qualifiers::OCL_Strong:
748     S.Diag(ivar->getLocation(), diag::err_arc_strong_property_ownership)
749       << property->getDeclName()
750       << ivar->getDeclName()
751       << ivarLifetime;
752     break;
753 
754   case Qualifiers::OCL_Weak:
755     S.Diag(ivar->getLocation(), diag::err_weak_property)
756       << property->getDeclName()
757       << ivar->getDeclName();
758     break;
759 
760   case Qualifiers::OCL_ExplicitNone:
761     S.Diag(ivar->getLocation(), diag::err_arc_assign_property_ownership)
762         << property->getDeclName() << ivar->getDeclName()
763         << ((property->getPropertyAttributesAsWritten() &
764              ObjCPropertyAttribute::kind_assign) != 0);
765     break;
766 
767   case Qualifiers::OCL_Autoreleasing:
768     llvm_unreachable("properties cannot be autoreleasing");
769 
770   case Qualifiers::OCL_None:
771     // Any other property should be ignored.
772     return;
773   }
774 
775   S.Diag(property->getLocation(), diag::note_property_declare);
776   if (propertyImplLoc.isValid())
777     S.Diag(propertyImplLoc, diag::note_property_synthesize);
778 }
779 
780 /// setImpliedPropertyAttributeForReadOnlyProperty -
781 /// This routine evaludates life-time attributes for a 'readonly'
782 /// property with no known lifetime of its own, using backing
783 /// 'ivar's attribute, if any. If no backing 'ivar', property's
784 /// life-time is assumed 'strong'.
setImpliedPropertyAttributeForReadOnlyProperty(ObjCPropertyDecl * property,ObjCIvarDecl * ivar)785 static void setImpliedPropertyAttributeForReadOnlyProperty(
786               ObjCPropertyDecl *property, ObjCIvarDecl *ivar) {
787   Qualifiers::ObjCLifetime propertyLifetime =
788     getImpliedARCOwnership(property->getPropertyAttributes(),
789                            property->getType());
790   if (propertyLifetime != Qualifiers::OCL_None)
791     return;
792 
793   if (!ivar) {
794     // if no backing ivar, make property 'strong'.
795     property->setPropertyAttributes(ObjCPropertyAttribute::kind_strong);
796     return;
797   }
798   // property assumes owenership of backing ivar.
799   QualType ivarType = ivar->getType();
800   Qualifiers::ObjCLifetime ivarLifetime = ivarType.getObjCLifetime();
801   if (ivarLifetime == Qualifiers::OCL_Strong)
802     property->setPropertyAttributes(ObjCPropertyAttribute::kind_strong);
803   else if (ivarLifetime == Qualifiers::OCL_Weak)
804     property->setPropertyAttributes(ObjCPropertyAttribute::kind_weak);
805 }
806 
isIncompatiblePropertyAttribute(unsigned Attr1,unsigned Attr2,ObjCPropertyAttribute::Kind Kind)807 static bool isIncompatiblePropertyAttribute(unsigned Attr1, unsigned Attr2,
808                                             ObjCPropertyAttribute::Kind Kind) {
809   return (Attr1 & Kind) != (Attr2 & Kind);
810 }
811 
areIncompatiblePropertyAttributes(unsigned Attr1,unsigned Attr2,unsigned Kinds)812 static bool areIncompatiblePropertyAttributes(unsigned Attr1, unsigned Attr2,
813                                               unsigned Kinds) {
814   return ((Attr1 & Kinds) != 0) != ((Attr2 & Kinds) != 0);
815 }
816 
817 /// SelectPropertyForSynthesisFromProtocols - Finds the most appropriate
818 /// property declaration that should be synthesised in all of the inherited
819 /// protocols. It also diagnoses properties declared in inherited protocols with
820 /// mismatched types or attributes, since any of them can be candidate for
821 /// synthesis.
822 static ObjCPropertyDecl *
SelectPropertyForSynthesisFromProtocols(Sema & S,SourceLocation AtLoc,ObjCInterfaceDecl * ClassDecl,ObjCPropertyDecl * Property)823 SelectPropertyForSynthesisFromProtocols(Sema &S, SourceLocation AtLoc,
824                                         ObjCInterfaceDecl *ClassDecl,
825                                         ObjCPropertyDecl *Property) {
826   assert(isa<ObjCProtocolDecl>(Property->getDeclContext()) &&
827          "Expected a property from a protocol");
828   ObjCInterfaceDecl::ProtocolPropertySet ProtocolSet;
829   ObjCInterfaceDecl::PropertyDeclOrder Properties;
830   for (const auto *PI : ClassDecl->all_referenced_protocols()) {
831     if (const ObjCProtocolDecl *PDecl = PI->getDefinition())
832       PDecl->collectInheritedProtocolProperties(Property, ProtocolSet,
833                                                 Properties);
834   }
835   if (ObjCInterfaceDecl *SDecl = ClassDecl->getSuperClass()) {
836     while (SDecl) {
837       for (const auto *PI : SDecl->all_referenced_protocols()) {
838         if (const ObjCProtocolDecl *PDecl = PI->getDefinition())
839           PDecl->collectInheritedProtocolProperties(Property, ProtocolSet,
840                                                     Properties);
841       }
842       SDecl = SDecl->getSuperClass();
843     }
844   }
845 
846   if (Properties.empty())
847     return Property;
848 
849   ObjCPropertyDecl *OriginalProperty = Property;
850   size_t SelectedIndex = 0;
851   for (const auto &Prop : llvm::enumerate(Properties)) {
852     // Select the 'readwrite' property if such property exists.
853     if (Property->isReadOnly() && !Prop.value()->isReadOnly()) {
854       Property = Prop.value();
855       SelectedIndex = Prop.index();
856     }
857   }
858   if (Property != OriginalProperty) {
859     // Check that the old property is compatible with the new one.
860     Properties[SelectedIndex] = OriginalProperty;
861   }
862 
863   QualType RHSType = S.Context.getCanonicalType(Property->getType());
864   unsigned OriginalAttributes = Property->getPropertyAttributesAsWritten();
865   enum MismatchKind {
866     IncompatibleType = 0,
867     HasNoExpectedAttribute,
868     HasUnexpectedAttribute,
869     DifferentGetter,
870     DifferentSetter
871   };
872   // Represents a property from another protocol that conflicts with the
873   // selected declaration.
874   struct MismatchingProperty {
875     const ObjCPropertyDecl *Prop;
876     MismatchKind Kind;
877     StringRef AttributeName;
878   };
879   SmallVector<MismatchingProperty, 4> Mismatches;
880   for (ObjCPropertyDecl *Prop : Properties) {
881     // Verify the property attributes.
882     unsigned Attr = Prop->getPropertyAttributesAsWritten();
883     if (Attr != OriginalAttributes) {
884       auto Diag = [&](bool OriginalHasAttribute, StringRef AttributeName) {
885         MismatchKind Kind = OriginalHasAttribute ? HasNoExpectedAttribute
886                                                  : HasUnexpectedAttribute;
887         Mismatches.push_back({Prop, Kind, AttributeName});
888       };
889       // The ownership might be incompatible unless the property has no explicit
890       // ownership.
891       bool HasOwnership =
892           (Attr & (ObjCPropertyAttribute::kind_retain |
893                    ObjCPropertyAttribute::kind_strong |
894                    ObjCPropertyAttribute::kind_copy |
895                    ObjCPropertyAttribute::kind_assign |
896                    ObjCPropertyAttribute::kind_unsafe_unretained |
897                    ObjCPropertyAttribute::kind_weak)) != 0;
898       if (HasOwnership &&
899           isIncompatiblePropertyAttribute(OriginalAttributes, Attr,
900                                           ObjCPropertyAttribute::kind_copy)) {
901         Diag(OriginalAttributes & ObjCPropertyAttribute::kind_copy, "copy");
902         continue;
903       }
904       if (HasOwnership && areIncompatiblePropertyAttributes(
905                               OriginalAttributes, Attr,
906                               ObjCPropertyAttribute::kind_retain |
907                                   ObjCPropertyAttribute::kind_strong)) {
908         Diag(OriginalAttributes & (ObjCPropertyAttribute::kind_retain |
909                                    ObjCPropertyAttribute::kind_strong),
910              "retain (or strong)");
911         continue;
912       }
913       if (isIncompatiblePropertyAttribute(OriginalAttributes, Attr,
914                                           ObjCPropertyAttribute::kind_atomic)) {
915         Diag(OriginalAttributes & ObjCPropertyAttribute::kind_atomic, "atomic");
916         continue;
917       }
918     }
919     if (Property->getGetterName() != Prop->getGetterName()) {
920       Mismatches.push_back({Prop, DifferentGetter, ""});
921       continue;
922     }
923     if (!Property->isReadOnly() && !Prop->isReadOnly() &&
924         Property->getSetterName() != Prop->getSetterName()) {
925       Mismatches.push_back({Prop, DifferentSetter, ""});
926       continue;
927     }
928     QualType LHSType = S.Context.getCanonicalType(Prop->getType());
929     if (!S.Context.propertyTypesAreCompatible(LHSType, RHSType)) {
930       bool IncompatibleObjC = false;
931       QualType ConvertedType;
932       if (!S.isObjCPointerConversion(RHSType, LHSType, ConvertedType, IncompatibleObjC)
933           || IncompatibleObjC) {
934         Mismatches.push_back({Prop, IncompatibleType, ""});
935         continue;
936       }
937     }
938   }
939 
940   if (Mismatches.empty())
941     return Property;
942 
943   // Diagnose incompability.
944   {
945     bool HasIncompatibleAttributes = false;
946     for (const auto &Note : Mismatches)
947       HasIncompatibleAttributes =
948           Note.Kind != IncompatibleType ? true : HasIncompatibleAttributes;
949     // Promote the warning to an error if there are incompatible attributes or
950     // incompatible types together with readwrite/readonly incompatibility.
951     auto Diag = S.Diag(Property->getLocation(),
952                        Property != OriginalProperty || HasIncompatibleAttributes
953                            ? diag::err_protocol_property_mismatch
954                            : diag::warn_protocol_property_mismatch);
955     Diag << Mismatches[0].Kind;
956     switch (Mismatches[0].Kind) {
957     case IncompatibleType:
958       Diag << Property->getType();
959       break;
960     case HasNoExpectedAttribute:
961     case HasUnexpectedAttribute:
962       Diag << Mismatches[0].AttributeName;
963       break;
964     case DifferentGetter:
965       Diag << Property->getGetterName();
966       break;
967     case DifferentSetter:
968       Diag << Property->getSetterName();
969       break;
970     }
971   }
972   for (const auto &Note : Mismatches) {
973     auto Diag =
974         S.Diag(Note.Prop->getLocation(), diag::note_protocol_property_declare)
975         << Note.Kind;
976     switch (Note.Kind) {
977     case IncompatibleType:
978       Diag << Note.Prop->getType();
979       break;
980     case HasNoExpectedAttribute:
981     case HasUnexpectedAttribute:
982       Diag << Note.AttributeName;
983       break;
984     case DifferentGetter:
985       Diag << Note.Prop->getGetterName();
986       break;
987     case DifferentSetter:
988       Diag << Note.Prop->getSetterName();
989       break;
990     }
991   }
992   if (AtLoc.isValid())
993     S.Diag(AtLoc, diag::note_property_synthesize);
994 
995   return Property;
996 }
997 
998 /// Determine whether any storage attributes were written on the property.
hasWrittenStorageAttribute(ObjCPropertyDecl * Prop,ObjCPropertyQueryKind QueryKind)999 static bool hasWrittenStorageAttribute(ObjCPropertyDecl *Prop,
1000                                        ObjCPropertyQueryKind QueryKind) {
1001   if (Prop->getPropertyAttributesAsWritten() & OwnershipMask) return true;
1002 
1003   // If this is a readwrite property in a class extension that refines
1004   // a readonly property in the original class definition, check it as
1005   // well.
1006 
1007   // If it's a readonly property, we're not interested.
1008   if (Prop->isReadOnly()) return false;
1009 
1010   // Is it declared in an extension?
1011   auto Category = dyn_cast<ObjCCategoryDecl>(Prop->getDeclContext());
1012   if (!Category || !Category->IsClassExtension()) return false;
1013 
1014   // Find the corresponding property in the primary class definition.
1015   auto OrigClass = Category->getClassInterface();
1016   for (auto *Found : OrigClass->lookup(Prop->getDeclName())) {
1017     if (ObjCPropertyDecl *OrigProp = dyn_cast<ObjCPropertyDecl>(Found))
1018       return OrigProp->getPropertyAttributesAsWritten() & OwnershipMask;
1019   }
1020 
1021   // Look through all of the protocols.
1022   for (const auto *Proto : OrigClass->all_referenced_protocols()) {
1023     if (ObjCPropertyDecl *OrigProp = Proto->FindPropertyDeclaration(
1024             Prop->getIdentifier(), QueryKind))
1025       return OrigProp->getPropertyAttributesAsWritten() & OwnershipMask;
1026   }
1027 
1028   return false;
1029 }
1030 
1031 /// Create a synthesized property accessor stub inside the \@implementation.
1032 static ObjCMethodDecl *
RedeclarePropertyAccessor(ASTContext & Context,ObjCImplementationDecl * Impl,ObjCMethodDecl * AccessorDecl,SourceLocation AtLoc,SourceLocation PropertyLoc)1033 RedeclarePropertyAccessor(ASTContext &Context, ObjCImplementationDecl *Impl,
1034                           ObjCMethodDecl *AccessorDecl, SourceLocation AtLoc,
1035                           SourceLocation PropertyLoc) {
1036   ObjCMethodDecl *Decl = AccessorDecl;
1037   ObjCMethodDecl *ImplDecl = ObjCMethodDecl::Create(
1038       Context, AtLoc.isValid() ? AtLoc : Decl->getBeginLoc(),
1039       PropertyLoc.isValid() ? PropertyLoc : Decl->getEndLoc(),
1040       Decl->getSelector(), Decl->getReturnType(),
1041       Decl->getReturnTypeSourceInfo(), Impl, Decl->isInstanceMethod(),
1042       Decl->isVariadic(), Decl->isPropertyAccessor(),
1043       /* isSynthesized*/ true, Decl->isImplicit(), Decl->isDefined(),
1044       Decl->getImplementationControl(), Decl->hasRelatedResultType());
1045   ImplDecl->getMethodFamily();
1046   if (Decl->hasAttrs())
1047     ImplDecl->setAttrs(Decl->getAttrs());
1048   ImplDecl->setSelfDecl(Decl->getSelfDecl());
1049   ImplDecl->setCmdDecl(Decl->getCmdDecl());
1050   SmallVector<SourceLocation, 1> SelLocs;
1051   Decl->getSelectorLocs(SelLocs);
1052   ImplDecl->setMethodParams(Context, Decl->parameters(), SelLocs);
1053   ImplDecl->setLexicalDeclContext(Impl);
1054   ImplDecl->setDefined(false);
1055   return ImplDecl;
1056 }
1057 
1058 /// ActOnPropertyImplDecl - This routine performs semantic checks and
1059 /// builds the AST node for a property implementation declaration; declared
1060 /// as \@synthesize or \@dynamic.
1061 ///
ActOnPropertyImplDecl(Scope * S,SourceLocation AtLoc,SourceLocation PropertyLoc,bool Synthesize,IdentifierInfo * PropertyId,IdentifierInfo * PropertyIvar,SourceLocation PropertyIvarLoc,ObjCPropertyQueryKind QueryKind)1062 Decl *SemaObjC::ActOnPropertyImplDecl(
1063     Scope *S, SourceLocation AtLoc, SourceLocation PropertyLoc, bool Synthesize,
1064     IdentifierInfo *PropertyId, IdentifierInfo *PropertyIvar,
1065     SourceLocation PropertyIvarLoc, ObjCPropertyQueryKind QueryKind) {
1066   ASTContext &Context = getASTContext();
1067   ObjCContainerDecl *ClassImpDecl =
1068       dyn_cast<ObjCContainerDecl>(SemaRef.CurContext);
1069   // Make sure we have a context for the property implementation declaration.
1070   if (!ClassImpDecl) {
1071     Diag(AtLoc, diag::err_missing_property_context);
1072     return nullptr;
1073   }
1074   if (PropertyIvarLoc.isInvalid())
1075     PropertyIvarLoc = PropertyLoc;
1076   SourceLocation PropertyDiagLoc = PropertyLoc;
1077   if (PropertyDiagLoc.isInvalid())
1078     PropertyDiagLoc = ClassImpDecl->getBeginLoc();
1079   ObjCPropertyDecl *property = nullptr;
1080   ObjCInterfaceDecl *IDecl = nullptr;
1081   // Find the class or category class where this property must have
1082   // a declaration.
1083   ObjCImplementationDecl *IC = nullptr;
1084   ObjCCategoryImplDecl *CatImplClass = nullptr;
1085   if ((IC = dyn_cast<ObjCImplementationDecl>(ClassImpDecl))) {
1086     IDecl = IC->getClassInterface();
1087     // We always synthesize an interface for an implementation
1088     // without an interface decl. So, IDecl is always non-zero.
1089     assert(IDecl &&
1090            "ActOnPropertyImplDecl - @implementation without @interface");
1091 
1092     // Look for this property declaration in the @implementation's @interface
1093     property = IDecl->FindPropertyDeclaration(PropertyId, QueryKind);
1094     if (!property) {
1095       Diag(PropertyLoc, diag::err_bad_property_decl) << IDecl->getDeclName();
1096       return nullptr;
1097     }
1098     if (property->isClassProperty() && Synthesize) {
1099       Diag(PropertyLoc, diag::err_synthesize_on_class_property) << PropertyId;
1100       return nullptr;
1101     }
1102     unsigned PIkind = property->getPropertyAttributesAsWritten();
1103     if ((PIkind & (ObjCPropertyAttribute::kind_atomic |
1104                    ObjCPropertyAttribute::kind_nonatomic)) == 0) {
1105       if (AtLoc.isValid())
1106         Diag(AtLoc, diag::warn_implicit_atomic_property);
1107       else
1108         Diag(IC->getLocation(), diag::warn_auto_implicit_atomic_property);
1109       Diag(property->getLocation(), diag::note_property_declare);
1110     }
1111 
1112     if (const ObjCCategoryDecl *CD =
1113         dyn_cast<ObjCCategoryDecl>(property->getDeclContext())) {
1114       if (!CD->IsClassExtension()) {
1115         Diag(PropertyLoc, diag::err_category_property) << CD->getDeclName();
1116         Diag(property->getLocation(), diag::note_property_declare);
1117         return nullptr;
1118       }
1119     }
1120     if (Synthesize && (PIkind & ObjCPropertyAttribute::kind_readonly) &&
1121         property->hasAttr<IBOutletAttr>() && !AtLoc.isValid()) {
1122       bool ReadWriteProperty = false;
1123       // Search into the class extensions and see if 'readonly property is
1124       // redeclared 'readwrite', then no warning is to be issued.
1125       for (auto *Ext : IDecl->known_extensions()) {
1126         DeclContext::lookup_result R = Ext->lookup(property->getDeclName());
1127         if (auto *ExtProp = R.find_first<ObjCPropertyDecl>()) {
1128           PIkind = ExtProp->getPropertyAttributesAsWritten();
1129           if (PIkind & ObjCPropertyAttribute::kind_readwrite) {
1130             ReadWriteProperty = true;
1131             break;
1132           }
1133         }
1134       }
1135 
1136       if (!ReadWriteProperty) {
1137         Diag(property->getLocation(), diag::warn_auto_readonly_iboutlet_property)
1138             << property;
1139         SourceLocation readonlyLoc;
1140         if (LocPropertyAttribute(Context, "readonly",
1141                                  property->getLParenLoc(), readonlyLoc)) {
1142           SourceLocation endLoc =
1143             readonlyLoc.getLocWithOffset(strlen("readonly")-1);
1144           SourceRange ReadonlySourceRange(readonlyLoc, endLoc);
1145           Diag(property->getLocation(),
1146                diag::note_auto_readonly_iboutlet_fixup_suggest) <<
1147           FixItHint::CreateReplacement(ReadonlySourceRange, "readwrite");
1148         }
1149       }
1150     }
1151     if (Synthesize && isa<ObjCProtocolDecl>(property->getDeclContext()))
1152       property = SelectPropertyForSynthesisFromProtocols(SemaRef, AtLoc, IDecl,
1153                                                          property);
1154 
1155   } else if ((CatImplClass = dyn_cast<ObjCCategoryImplDecl>(ClassImpDecl))) {
1156     if (Synthesize) {
1157       Diag(AtLoc, diag::err_synthesize_category_decl);
1158       return nullptr;
1159     }
1160     IDecl = CatImplClass->getClassInterface();
1161     if (!IDecl) {
1162       Diag(AtLoc, diag::err_missing_property_interface);
1163       return nullptr;
1164     }
1165     ObjCCategoryDecl *Category =
1166     IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier());
1167 
1168     // If category for this implementation not found, it is an error which
1169     // has already been reported eralier.
1170     if (!Category)
1171       return nullptr;
1172     // Look for this property declaration in @implementation's category
1173     property = Category->FindPropertyDeclaration(PropertyId, QueryKind);
1174     if (!property) {
1175       Diag(PropertyLoc, diag::err_bad_category_property_decl)
1176       << Category->getDeclName();
1177       return nullptr;
1178     }
1179   } else {
1180     Diag(AtLoc, diag::err_bad_property_context);
1181     return nullptr;
1182   }
1183   ObjCIvarDecl *Ivar = nullptr;
1184   bool CompleteTypeErr = false;
1185   bool compat = true;
1186   // Check that we have a valid, previously declared ivar for @synthesize
1187   if (Synthesize) {
1188     // @synthesize
1189     if (!PropertyIvar)
1190       PropertyIvar = PropertyId;
1191     // Check that this is a previously declared 'ivar' in 'IDecl' interface
1192     ObjCInterfaceDecl *ClassDeclared;
1193     Ivar = IDecl->lookupInstanceVariable(PropertyIvar, ClassDeclared);
1194     QualType PropType = property->getType();
1195     QualType PropertyIvarType = PropType.getNonReferenceType();
1196 
1197     if (SemaRef.RequireCompleteType(PropertyDiagLoc, PropertyIvarType,
1198                                     diag::err_incomplete_synthesized_property,
1199                                     property->getDeclName())) {
1200       Diag(property->getLocation(), diag::note_property_declare);
1201       CompleteTypeErr = true;
1202     }
1203 
1204     if (getLangOpts().ObjCAutoRefCount &&
1205         (property->getPropertyAttributesAsWritten() &
1206          ObjCPropertyAttribute::kind_readonly) &&
1207         PropertyIvarType->isObjCRetainableType()) {
1208       setImpliedPropertyAttributeForReadOnlyProperty(property, Ivar);
1209     }
1210 
1211     ObjCPropertyAttribute::Kind kind = property->getPropertyAttributes();
1212 
1213     bool isARCWeak = false;
1214     if (kind & ObjCPropertyAttribute::kind_weak) {
1215       // Add GC __weak to the ivar type if the property is weak.
1216       if (getLangOpts().getGC() != LangOptions::NonGC) {
1217         assert(!getLangOpts().ObjCAutoRefCount);
1218         if (PropertyIvarType.isObjCGCStrong()) {
1219           Diag(PropertyDiagLoc, diag::err_gc_weak_property_strong_type);
1220           Diag(property->getLocation(), diag::note_property_declare);
1221         } else {
1222           PropertyIvarType =
1223             Context.getObjCGCQualType(PropertyIvarType, Qualifiers::Weak);
1224         }
1225 
1226       // Otherwise, check whether ARC __weak is enabled and works with
1227       // the property type.
1228       } else {
1229         if (!getLangOpts().ObjCWeak) {
1230           // Only complain here when synthesizing an ivar.
1231           if (!Ivar) {
1232             Diag(PropertyDiagLoc,
1233                  getLangOpts().ObjCWeakRuntime
1234                    ? diag::err_synthesizing_arc_weak_property_disabled
1235                    : diag::err_synthesizing_arc_weak_property_no_runtime);
1236             Diag(property->getLocation(), diag::note_property_declare);
1237           }
1238           CompleteTypeErr = true; // suppress later diagnostics about the ivar
1239         } else {
1240           isARCWeak = true;
1241           if (const ObjCObjectPointerType *ObjT =
1242                 PropertyIvarType->getAs<ObjCObjectPointerType>()) {
1243             const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl();
1244             if (ObjI && ObjI->isArcWeakrefUnavailable()) {
1245               Diag(property->getLocation(),
1246                    diag::err_arc_weak_unavailable_property)
1247                 << PropertyIvarType;
1248               Diag(ClassImpDecl->getLocation(), diag::note_implemented_by_class)
1249                 << ClassImpDecl->getName();
1250             }
1251           }
1252         }
1253       }
1254     }
1255 
1256     if (AtLoc.isInvalid()) {
1257       // Check when default synthesizing a property that there is
1258       // an ivar matching property name and issue warning; since this
1259       // is the most common case of not using an ivar used for backing
1260       // property in non-default synthesis case.
1261       ObjCInterfaceDecl *ClassDeclared=nullptr;
1262       ObjCIvarDecl *originalIvar =
1263       IDecl->lookupInstanceVariable(property->getIdentifier(),
1264                                     ClassDeclared);
1265       if (originalIvar) {
1266         Diag(PropertyDiagLoc,
1267              diag::warn_autosynthesis_property_ivar_match)
1268         << PropertyId << (Ivar == nullptr) << PropertyIvar
1269         << originalIvar->getIdentifier();
1270         Diag(property->getLocation(), diag::note_property_declare);
1271         Diag(originalIvar->getLocation(), diag::note_ivar_decl);
1272       }
1273     }
1274 
1275     if (!Ivar) {
1276       // In ARC, give the ivar a lifetime qualifier based on the
1277       // property attributes.
1278       if ((getLangOpts().ObjCAutoRefCount || isARCWeak) &&
1279           !PropertyIvarType.getObjCLifetime() &&
1280           PropertyIvarType->isObjCRetainableType()) {
1281 
1282         // It's an error if we have to do this and the user didn't
1283         // explicitly write an ownership attribute on the property.
1284         if (!hasWrittenStorageAttribute(property, QueryKind) &&
1285             !(kind & ObjCPropertyAttribute::kind_strong)) {
1286           Diag(PropertyDiagLoc,
1287                diag::err_arc_objc_property_default_assign_on_object);
1288           Diag(property->getLocation(), diag::note_property_declare);
1289         } else {
1290           Qualifiers::ObjCLifetime lifetime =
1291             getImpliedARCOwnership(kind, PropertyIvarType);
1292           assert(lifetime && "no lifetime for property?");
1293 
1294           Qualifiers qs;
1295           qs.addObjCLifetime(lifetime);
1296           PropertyIvarType = Context.getQualifiedType(PropertyIvarType, qs);
1297         }
1298       }
1299 
1300       Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
1301                                   PropertyIvarLoc,PropertyIvarLoc, PropertyIvar,
1302                                   PropertyIvarType, /*TInfo=*/nullptr,
1303                                   ObjCIvarDecl::Private,
1304                                   (Expr *)nullptr, true);
1305       if (SemaRef.RequireNonAbstractType(PropertyIvarLoc, PropertyIvarType,
1306                                          diag::err_abstract_type_in_decl,
1307                                          Sema::AbstractSynthesizedIvarType)) {
1308         Diag(property->getLocation(), diag::note_property_declare);
1309         // An abstract type is as bad as an incomplete type.
1310         CompleteTypeErr = true;
1311       }
1312       if (!CompleteTypeErr) {
1313         const RecordType *RecordTy = PropertyIvarType->getAs<RecordType>();
1314         if (RecordTy && RecordTy->getDecl()->hasFlexibleArrayMember()) {
1315           Diag(PropertyIvarLoc, diag::err_synthesize_variable_sized_ivar)
1316             << PropertyIvarType;
1317           CompleteTypeErr = true; // suppress later diagnostics about the ivar
1318         }
1319       }
1320       if (CompleteTypeErr)
1321         Ivar->setInvalidDecl();
1322       ClassImpDecl->addDecl(Ivar);
1323       IDecl->makeDeclVisibleInContext(Ivar);
1324 
1325       if (getLangOpts().ObjCRuntime.isFragile())
1326         Diag(PropertyDiagLoc, diag::err_missing_property_ivar_decl)
1327             << PropertyId;
1328       // Note! I deliberately want it to fall thru so, we have a
1329       // a property implementation and to avoid future warnings.
1330     } else if (getLangOpts().ObjCRuntime.isNonFragile() &&
1331                !declaresSameEntity(ClassDeclared, IDecl)) {
1332       Diag(PropertyDiagLoc, diag::err_ivar_in_superclass_use)
1333       << property->getDeclName() << Ivar->getDeclName()
1334       << ClassDeclared->getDeclName();
1335       Diag(Ivar->getLocation(), diag::note_previous_access_declaration)
1336       << Ivar << Ivar->getName();
1337       // Note! I deliberately want it to fall thru so more errors are caught.
1338     }
1339     property->setPropertyIvarDecl(Ivar);
1340 
1341     QualType IvarType = Context.getCanonicalType(Ivar->getType());
1342 
1343     // Check that type of property and its ivar are type compatible.
1344     if (!Context.hasSameType(PropertyIvarType, IvarType)) {
1345       if (isa<ObjCObjectPointerType>(PropertyIvarType)
1346           && isa<ObjCObjectPointerType>(IvarType))
1347         compat = Context.canAssignObjCInterfaces(
1348             PropertyIvarType->castAs<ObjCObjectPointerType>(),
1349             IvarType->castAs<ObjCObjectPointerType>());
1350       else {
1351         compat = (SemaRef.CheckAssignmentConstraints(
1352                       PropertyIvarLoc, PropertyIvarType, IvarType) ==
1353                   Sema::Compatible);
1354       }
1355       if (!compat) {
1356         Diag(PropertyDiagLoc, diag::err_property_ivar_type)
1357           << property->getDeclName() << PropType
1358           << Ivar->getDeclName() << IvarType;
1359         Diag(Ivar->getLocation(), diag::note_ivar_decl);
1360         // Note! I deliberately want it to fall thru so, we have a
1361         // a property implementation and to avoid future warnings.
1362       }
1363       else {
1364         // FIXME! Rules for properties are somewhat different that those
1365         // for assignments. Use a new routine to consolidate all cases;
1366         // specifically for property redeclarations as well as for ivars.
1367         QualType lhsType =Context.getCanonicalType(PropertyIvarType).getUnqualifiedType();
1368         QualType rhsType =Context.getCanonicalType(IvarType).getUnqualifiedType();
1369         if (lhsType != rhsType &&
1370             lhsType->isArithmeticType()) {
1371           Diag(PropertyDiagLoc, diag::err_property_ivar_type)
1372             << property->getDeclName() << PropType
1373             << Ivar->getDeclName() << IvarType;
1374           Diag(Ivar->getLocation(), diag::note_ivar_decl);
1375           // Fall thru - see previous comment
1376         }
1377       }
1378       // __weak is explicit. So it works on Canonical type.
1379       if ((PropType.isObjCGCWeak() && !IvarType.isObjCGCWeak() &&
1380            getLangOpts().getGC() != LangOptions::NonGC)) {
1381         Diag(PropertyDiagLoc, diag::err_weak_property)
1382         << property->getDeclName() << Ivar->getDeclName();
1383         Diag(Ivar->getLocation(), diag::note_ivar_decl);
1384         // Fall thru - see previous comment
1385       }
1386       // Fall thru - see previous comment
1387       if ((property->getType()->isObjCObjectPointerType() ||
1388            PropType.isObjCGCStrong()) && IvarType.isObjCGCWeak() &&
1389           getLangOpts().getGC() != LangOptions::NonGC) {
1390         Diag(PropertyDiagLoc, diag::err_strong_property)
1391         << property->getDeclName() << Ivar->getDeclName();
1392         // Fall thru - see previous comment
1393       }
1394     }
1395     if (getLangOpts().ObjCAutoRefCount || isARCWeak ||
1396         Ivar->getType().getObjCLifetime())
1397       checkARCPropertyImpl(SemaRef, PropertyLoc, property, Ivar);
1398   } else if (PropertyIvar)
1399     // @dynamic
1400     Diag(PropertyDiagLoc, diag::err_dynamic_property_ivar_decl);
1401 
1402   assert (property && "ActOnPropertyImplDecl - property declaration missing");
1403   ObjCPropertyImplDecl *PIDecl = ObjCPropertyImplDecl::Create(
1404       Context, SemaRef.CurContext, AtLoc, PropertyLoc, property,
1405       (Synthesize ? ObjCPropertyImplDecl::Synthesize
1406                   : ObjCPropertyImplDecl::Dynamic),
1407       Ivar, PropertyIvarLoc);
1408 
1409   if (CompleteTypeErr || !compat)
1410     PIDecl->setInvalidDecl();
1411 
1412   if (ObjCMethodDecl *getterMethod = property->getGetterMethodDecl()) {
1413     getterMethod->createImplicitParams(Context, IDecl);
1414 
1415     // Redeclare the getter within the implementation as DeclContext.
1416     if (Synthesize) {
1417       // If the method hasn't been overridden, create a synthesized implementation.
1418       ObjCMethodDecl *OMD = ClassImpDecl->getMethod(
1419           getterMethod->getSelector(), getterMethod->isInstanceMethod());
1420       if (!OMD)
1421         OMD = RedeclarePropertyAccessor(Context, IC, getterMethod, AtLoc,
1422                                         PropertyLoc);
1423       PIDecl->setGetterMethodDecl(OMD);
1424     }
1425 
1426     if (getLangOpts().CPlusPlus && Synthesize && !CompleteTypeErr &&
1427         Ivar->getType()->isRecordType()) {
1428       // For Objective-C++, need to synthesize the AST for the IVAR object to be
1429       // returned by the getter as it must conform to C++'s copy-return rules.
1430       // FIXME. Eventually we want to do this for Objective-C as well.
1431       Sema::SynthesizedFunctionScope Scope(SemaRef, getterMethod);
1432       ImplicitParamDecl *SelfDecl = getterMethod->getSelfDecl();
1433       DeclRefExpr *SelfExpr = new (Context)
1434           DeclRefExpr(Context, SelfDecl, false, SelfDecl->getType(), VK_LValue,
1435                       PropertyDiagLoc);
1436       SemaRef.MarkDeclRefReferenced(SelfExpr);
1437       Expr *LoadSelfExpr = ImplicitCastExpr::Create(
1438           Context, SelfDecl->getType(), CK_LValueToRValue, SelfExpr, nullptr,
1439           VK_PRValue, FPOptionsOverride());
1440       Expr *IvarRefExpr =
1441         new (Context) ObjCIvarRefExpr(Ivar,
1442                                       Ivar->getUsageType(SelfDecl->getType()),
1443                                       PropertyDiagLoc,
1444                                       Ivar->getLocation(),
1445                                       LoadSelfExpr, true, true);
1446       ExprResult Res = SemaRef.PerformCopyInitialization(
1447           InitializedEntity::InitializeResult(PropertyDiagLoc,
1448                                               getterMethod->getReturnType()),
1449           PropertyDiagLoc, IvarRefExpr);
1450       if (!Res.isInvalid()) {
1451         Expr *ResExpr = Res.getAs<Expr>();
1452         if (ResExpr)
1453           ResExpr = SemaRef.MaybeCreateExprWithCleanups(ResExpr);
1454         PIDecl->setGetterCXXConstructor(ResExpr);
1455       }
1456     }
1457     if (property->hasAttr<NSReturnsNotRetainedAttr>() &&
1458         !getterMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
1459       Diag(getterMethod->getLocation(),
1460            diag::warn_property_getter_owning_mismatch);
1461       Diag(property->getLocation(), diag::note_property_declare);
1462     }
1463     if (getLangOpts().ObjCAutoRefCount && Synthesize)
1464       switch (getterMethod->getMethodFamily()) {
1465         case OMF_retain:
1466         case OMF_retainCount:
1467         case OMF_release:
1468         case OMF_autorelease:
1469           Diag(getterMethod->getLocation(), diag::err_arc_illegal_method_def)
1470             << 1 << getterMethod->getSelector();
1471           break;
1472         default:
1473           break;
1474       }
1475   }
1476 
1477   if (ObjCMethodDecl *setterMethod = property->getSetterMethodDecl()) {
1478     setterMethod->createImplicitParams(Context, IDecl);
1479 
1480     // Redeclare the setter within the implementation as DeclContext.
1481     if (Synthesize) {
1482       ObjCMethodDecl *OMD = ClassImpDecl->getMethod(
1483           setterMethod->getSelector(), setterMethod->isInstanceMethod());
1484       if (!OMD)
1485         OMD = RedeclarePropertyAccessor(Context, IC, setterMethod,
1486                                         AtLoc, PropertyLoc);
1487       PIDecl->setSetterMethodDecl(OMD);
1488     }
1489 
1490     if (getLangOpts().CPlusPlus && Synthesize && !CompleteTypeErr &&
1491         Ivar->getType()->isRecordType()) {
1492       // FIXME. Eventually we want to do this for Objective-C as well.
1493       Sema::SynthesizedFunctionScope Scope(SemaRef, setterMethod);
1494       ImplicitParamDecl *SelfDecl = setterMethod->getSelfDecl();
1495       DeclRefExpr *SelfExpr = new (Context)
1496           DeclRefExpr(Context, SelfDecl, false, SelfDecl->getType(), VK_LValue,
1497                       PropertyDiagLoc);
1498       SemaRef.MarkDeclRefReferenced(SelfExpr);
1499       Expr *LoadSelfExpr = ImplicitCastExpr::Create(
1500           Context, SelfDecl->getType(), CK_LValueToRValue, SelfExpr, nullptr,
1501           VK_PRValue, FPOptionsOverride());
1502       Expr *lhs =
1503         new (Context) ObjCIvarRefExpr(Ivar,
1504                                       Ivar->getUsageType(SelfDecl->getType()),
1505                                       PropertyDiagLoc,
1506                                       Ivar->getLocation(),
1507                                       LoadSelfExpr, true, true);
1508       ObjCMethodDecl::param_iterator P = setterMethod->param_begin();
1509       ParmVarDecl *Param = (*P);
1510       QualType T = Param->getType().getNonReferenceType();
1511       DeclRefExpr *rhs = new (Context)
1512           DeclRefExpr(Context, Param, false, T, VK_LValue, PropertyDiagLoc);
1513       SemaRef.MarkDeclRefReferenced(rhs);
1514       ExprResult Res =
1515           SemaRef.BuildBinOp(S, PropertyDiagLoc, BO_Assign, lhs, rhs);
1516       if (property->getPropertyAttributes() &
1517           ObjCPropertyAttribute::kind_atomic) {
1518         Expr *callExpr = Res.getAs<Expr>();
1519         if (const CXXOperatorCallExpr *CXXCE =
1520               dyn_cast_or_null<CXXOperatorCallExpr>(callExpr))
1521           if (const FunctionDecl *FuncDecl = CXXCE->getDirectCallee())
1522             if (!FuncDecl->isTrivial())
1523               if (property->getType()->isReferenceType()) {
1524                 Diag(PropertyDiagLoc,
1525                      diag::err_atomic_property_nontrivial_assign_op)
1526                     << property->getType();
1527                 Diag(FuncDecl->getBeginLoc(), diag::note_callee_decl)
1528                     << FuncDecl;
1529               }
1530       }
1531       PIDecl->setSetterCXXAssignment(Res.getAs<Expr>());
1532     }
1533   }
1534 
1535   if (IC) {
1536     if (Synthesize)
1537       if (ObjCPropertyImplDecl *PPIDecl =
1538           IC->FindPropertyImplIvarDecl(PropertyIvar)) {
1539         Diag(PropertyLoc, diag::err_duplicate_ivar_use)
1540         << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
1541         << PropertyIvar;
1542         Diag(PPIDecl->getLocation(), diag::note_previous_use);
1543       }
1544 
1545     if (ObjCPropertyImplDecl *PPIDecl
1546         = IC->FindPropertyImplDecl(PropertyId, QueryKind)) {
1547       Diag(PropertyLoc, diag::err_property_implemented) << PropertyId;
1548       Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
1549       return nullptr;
1550     }
1551     IC->addPropertyImplementation(PIDecl);
1552     if (getLangOpts().ObjCDefaultSynthProperties &&
1553         getLangOpts().ObjCRuntime.isNonFragile() &&
1554         !IDecl->isObjCRequiresPropertyDefs()) {
1555       // Diagnose if an ivar was lazily synthesdized due to a previous
1556       // use and if 1) property is @dynamic or 2) property is synthesized
1557       // but it requires an ivar of different name.
1558       ObjCInterfaceDecl *ClassDeclared=nullptr;
1559       ObjCIvarDecl *Ivar = nullptr;
1560       if (!Synthesize)
1561         Ivar = IDecl->lookupInstanceVariable(PropertyId, ClassDeclared);
1562       else {
1563         if (PropertyIvar && PropertyIvar != PropertyId)
1564           Ivar = IDecl->lookupInstanceVariable(PropertyId, ClassDeclared);
1565       }
1566       // Issue diagnostics only if Ivar belongs to current class.
1567       if (Ivar && Ivar->getSynthesize() &&
1568           declaresSameEntity(IC->getClassInterface(), ClassDeclared)) {
1569         Diag(Ivar->getLocation(), diag::err_undeclared_var_use)
1570         << PropertyId;
1571         Ivar->setInvalidDecl();
1572       }
1573     }
1574   } else {
1575     if (Synthesize)
1576       if (ObjCPropertyImplDecl *PPIDecl =
1577           CatImplClass->FindPropertyImplIvarDecl(PropertyIvar)) {
1578         Diag(PropertyDiagLoc, diag::err_duplicate_ivar_use)
1579         << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
1580         << PropertyIvar;
1581         Diag(PPIDecl->getLocation(), diag::note_previous_use);
1582       }
1583 
1584     if (ObjCPropertyImplDecl *PPIDecl =
1585         CatImplClass->FindPropertyImplDecl(PropertyId, QueryKind)) {
1586       Diag(PropertyDiagLoc, diag::err_property_implemented) << PropertyId;
1587       Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
1588       return nullptr;
1589     }
1590     CatImplClass->addPropertyImplementation(PIDecl);
1591   }
1592 
1593   if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic &&
1594       PIDecl->getPropertyDecl() &&
1595       PIDecl->getPropertyDecl()->isDirectProperty()) {
1596     Diag(PropertyLoc, diag::err_objc_direct_dynamic_property);
1597     Diag(PIDecl->getPropertyDecl()->getLocation(),
1598          diag::note_previous_declaration);
1599     return nullptr;
1600   }
1601 
1602   return PIDecl;
1603 }
1604 
1605 //===----------------------------------------------------------------------===//
1606 // Helper methods.
1607 //===----------------------------------------------------------------------===//
1608 
1609 /// DiagnosePropertyMismatch - Compares two properties for their
1610 /// attributes and types and warns on a variety of inconsistencies.
1611 ///
DiagnosePropertyMismatch(ObjCPropertyDecl * Property,ObjCPropertyDecl * SuperProperty,const IdentifierInfo * inheritedName,bool OverridingProtocolProperty)1612 void SemaObjC::DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
1613                                         ObjCPropertyDecl *SuperProperty,
1614                                         const IdentifierInfo *inheritedName,
1615                                         bool OverridingProtocolProperty) {
1616   ASTContext &Context = getASTContext();
1617   ObjCPropertyAttribute::Kind CAttr = Property->getPropertyAttributes();
1618   ObjCPropertyAttribute::Kind SAttr = SuperProperty->getPropertyAttributes();
1619 
1620   // We allow readonly properties without an explicit ownership
1621   // (assign/unsafe_unretained/weak/retain/strong/copy) in super class
1622   // to be overridden by a property with any explicit ownership in the subclass.
1623   if (!OverridingProtocolProperty &&
1624       !getOwnershipRule(SAttr) && getOwnershipRule(CAttr))
1625     ;
1626   else {
1627     if ((CAttr & ObjCPropertyAttribute::kind_readonly) &&
1628         (SAttr & ObjCPropertyAttribute::kind_readwrite))
1629       Diag(Property->getLocation(), diag::warn_readonly_property)
1630         << Property->getDeclName() << inheritedName;
1631     if ((CAttr & ObjCPropertyAttribute::kind_copy) !=
1632         (SAttr & ObjCPropertyAttribute::kind_copy))
1633       Diag(Property->getLocation(), diag::warn_property_attribute)
1634         << Property->getDeclName() << "copy" << inheritedName;
1635     else if (!(SAttr & ObjCPropertyAttribute::kind_readonly)) {
1636       unsigned CAttrRetain = (CAttr & (ObjCPropertyAttribute::kind_retain |
1637                                        ObjCPropertyAttribute::kind_strong));
1638       unsigned SAttrRetain = (SAttr & (ObjCPropertyAttribute::kind_retain |
1639                                        ObjCPropertyAttribute::kind_strong));
1640       bool CStrong = (CAttrRetain != 0);
1641       bool SStrong = (SAttrRetain != 0);
1642       if (CStrong != SStrong)
1643         Diag(Property->getLocation(), diag::warn_property_attribute)
1644           << Property->getDeclName() << "retain (or strong)" << inheritedName;
1645     }
1646   }
1647 
1648   // Check for nonatomic; note that nonatomic is effectively
1649   // meaningless for readonly properties, so don't diagnose if the
1650   // atomic property is 'readonly'.
1651   checkAtomicPropertyMismatch(SemaRef, SuperProperty, Property, false);
1652   // Readonly properties from protocols can be implemented as "readwrite"
1653   // with a custom setter name.
1654   if (Property->getSetterName() != SuperProperty->getSetterName() &&
1655       !(SuperProperty->isReadOnly() &&
1656         isa<ObjCProtocolDecl>(SuperProperty->getDeclContext()))) {
1657     Diag(Property->getLocation(), diag::warn_property_attribute)
1658       << Property->getDeclName() << "setter" << inheritedName;
1659     Diag(SuperProperty->getLocation(), diag::note_property_declare);
1660   }
1661   if (Property->getGetterName() != SuperProperty->getGetterName()) {
1662     Diag(Property->getLocation(), diag::warn_property_attribute)
1663       << Property->getDeclName() << "getter" << inheritedName;
1664     Diag(SuperProperty->getLocation(), diag::note_property_declare);
1665   }
1666 
1667   QualType LHSType =
1668     Context.getCanonicalType(SuperProperty->getType());
1669   QualType RHSType =
1670     Context.getCanonicalType(Property->getType());
1671 
1672   if (!Context.propertyTypesAreCompatible(LHSType, RHSType)) {
1673     // Do cases not handled in above.
1674     // FIXME. For future support of covariant property types, revisit this.
1675     bool IncompatibleObjC = false;
1676     QualType ConvertedType;
1677     if (!SemaRef.isObjCPointerConversion(RHSType, LHSType, ConvertedType,
1678                                          IncompatibleObjC) ||
1679         IncompatibleObjC) {
1680       Diag(Property->getLocation(), diag::warn_property_types_are_incompatible)
1681           << Property->getType() << SuperProperty->getType() << inheritedName;
1682       Diag(SuperProperty->getLocation(), diag::note_property_declare);
1683     }
1684   }
1685 }
1686 
DiagnosePropertyAccessorMismatch(ObjCPropertyDecl * property,ObjCMethodDecl * GetterMethod,SourceLocation Loc)1687 bool SemaObjC::DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *property,
1688                                                 ObjCMethodDecl *GetterMethod,
1689                                                 SourceLocation Loc) {
1690   ASTContext &Context = getASTContext();
1691   if (!GetterMethod)
1692     return false;
1693   QualType GetterType = GetterMethod->getReturnType().getNonReferenceType();
1694   QualType PropertyRValueType =
1695       property->getType().getNonReferenceType().getAtomicUnqualifiedType();
1696   bool compat = Context.hasSameType(PropertyRValueType, GetterType);
1697   if (!compat) {
1698     const ObjCObjectPointerType *propertyObjCPtr = nullptr;
1699     const ObjCObjectPointerType *getterObjCPtr = nullptr;
1700     if ((propertyObjCPtr =
1701              PropertyRValueType->getAs<ObjCObjectPointerType>()) &&
1702         (getterObjCPtr = GetterType->getAs<ObjCObjectPointerType>()))
1703       compat = Context.canAssignObjCInterfaces(getterObjCPtr, propertyObjCPtr);
1704     else if (SemaRef.CheckAssignmentConstraints(
1705                  Loc, GetterType, PropertyRValueType) != Sema::Compatible) {
1706       Diag(Loc, diag::err_property_accessor_type)
1707           << property->getDeclName() << PropertyRValueType
1708           << GetterMethod->getSelector() << GetterType;
1709       Diag(GetterMethod->getLocation(), diag::note_declared_at);
1710       return true;
1711     } else {
1712       compat = true;
1713       QualType lhsType = Context.getCanonicalType(PropertyRValueType);
1714       QualType rhsType =Context.getCanonicalType(GetterType).getUnqualifiedType();
1715       if (lhsType != rhsType && lhsType->isArithmeticType())
1716         compat = false;
1717     }
1718   }
1719 
1720   if (!compat) {
1721     Diag(Loc, diag::warn_accessor_property_type_mismatch)
1722     << property->getDeclName()
1723     << GetterMethod->getSelector();
1724     Diag(GetterMethod->getLocation(), diag::note_declared_at);
1725     return true;
1726   }
1727 
1728   return false;
1729 }
1730 
1731 /// CollectImmediateProperties - This routine collects all properties in
1732 /// the class and its conforming protocols; but not those in its super class.
1733 static void
CollectImmediateProperties(ObjCContainerDecl * CDecl,ObjCContainerDecl::PropertyMap & PropMap,ObjCContainerDecl::PropertyMap & SuperPropMap,bool CollectClassPropsOnly=false,bool IncludeProtocols=true)1734 CollectImmediateProperties(ObjCContainerDecl *CDecl,
1735                            ObjCContainerDecl::PropertyMap &PropMap,
1736                            ObjCContainerDecl::PropertyMap &SuperPropMap,
1737                            bool CollectClassPropsOnly = false,
1738                            bool IncludeProtocols = true) {
1739   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1740     for (auto *Prop : IDecl->properties()) {
1741       if (CollectClassPropsOnly && !Prop->isClassProperty())
1742         continue;
1743       PropMap[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] =
1744           Prop;
1745     }
1746 
1747     // Collect the properties from visible extensions.
1748     for (auto *Ext : IDecl->visible_extensions())
1749       CollectImmediateProperties(Ext, PropMap, SuperPropMap,
1750                                  CollectClassPropsOnly, IncludeProtocols);
1751 
1752     if (IncludeProtocols) {
1753       // Scan through class's protocols.
1754       for (auto *PI : IDecl->all_referenced_protocols())
1755         CollectImmediateProperties(PI, PropMap, SuperPropMap,
1756                                    CollectClassPropsOnly);
1757     }
1758   }
1759   if (ObjCCategoryDecl *CATDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1760     for (auto *Prop : CATDecl->properties()) {
1761       if (CollectClassPropsOnly && !Prop->isClassProperty())
1762         continue;
1763       PropMap[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] =
1764           Prop;
1765     }
1766     if (IncludeProtocols) {
1767       // Scan through class's protocols.
1768       for (auto *PI : CATDecl->protocols())
1769         CollectImmediateProperties(PI, PropMap, SuperPropMap,
1770                                    CollectClassPropsOnly);
1771     }
1772   }
1773   else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1774     for (auto *Prop : PDecl->properties()) {
1775       if (CollectClassPropsOnly && !Prop->isClassProperty())
1776         continue;
1777       ObjCPropertyDecl *PropertyFromSuper =
1778           SuperPropMap[std::make_pair(Prop->getIdentifier(),
1779                                       Prop->isClassProperty())];
1780       // Exclude property for protocols which conform to class's super-class,
1781       // as super-class has to implement the property.
1782       if (!PropertyFromSuper ||
1783           PropertyFromSuper->getIdentifier() != Prop->getIdentifier()) {
1784         ObjCPropertyDecl *&PropEntry =
1785             PropMap[std::make_pair(Prop->getIdentifier(),
1786                                    Prop->isClassProperty())];
1787         if (!PropEntry)
1788           PropEntry = Prop;
1789       }
1790     }
1791     // Scan through protocol's protocols.
1792     for (auto *PI : PDecl->protocols())
1793       CollectImmediateProperties(PI, PropMap, SuperPropMap,
1794                                  CollectClassPropsOnly);
1795   }
1796 }
1797 
1798 /// CollectSuperClassPropertyImplementations - This routine collects list of
1799 /// properties to be implemented in super class(s) and also coming from their
1800 /// conforming protocols.
CollectSuperClassPropertyImplementations(ObjCInterfaceDecl * CDecl,ObjCInterfaceDecl::PropertyMap & PropMap)1801 static void CollectSuperClassPropertyImplementations(ObjCInterfaceDecl *CDecl,
1802                                     ObjCInterfaceDecl::PropertyMap &PropMap) {
1803   if (ObjCInterfaceDecl *SDecl = CDecl->getSuperClass()) {
1804     while (SDecl) {
1805       SDecl->collectPropertiesToImplement(PropMap);
1806       SDecl = SDecl->getSuperClass();
1807     }
1808   }
1809 }
1810 
1811 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
1812 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
1813 /// declared in class 'IFace'.
IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl * IFace,ObjCMethodDecl * Method,ObjCIvarDecl * IV)1814 bool SemaObjC::IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
1815                                               ObjCMethodDecl *Method,
1816                                               ObjCIvarDecl *IV) {
1817   if (!IV->getSynthesize())
1818     return false;
1819   ObjCMethodDecl *IMD = IFace->lookupMethod(Method->getSelector(),
1820                                             Method->isInstanceMethod());
1821   if (!IMD || !IMD->isPropertyAccessor())
1822     return false;
1823 
1824   // look up a property declaration whose one of its accessors is implemented
1825   // by this method.
1826   for (const auto *Property : IFace->instance_properties()) {
1827     if ((Property->getGetterName() == IMD->getSelector() ||
1828          Property->getSetterName() == IMD->getSelector()) &&
1829         (Property->getPropertyIvarDecl() == IV))
1830       return true;
1831   }
1832   // Also look up property declaration in class extension whose one of its
1833   // accessors is implemented by this method.
1834   for (const auto *Ext : IFace->known_extensions())
1835     for (const auto *Property : Ext->instance_properties())
1836       if ((Property->getGetterName() == IMD->getSelector() ||
1837            Property->getSetterName() == IMD->getSelector()) &&
1838           (Property->getPropertyIvarDecl() == IV))
1839         return true;
1840   return false;
1841 }
1842 
SuperClassImplementsProperty(ObjCInterfaceDecl * IDecl,ObjCPropertyDecl * Prop)1843 static bool SuperClassImplementsProperty(ObjCInterfaceDecl *IDecl,
1844                                          ObjCPropertyDecl *Prop) {
1845   bool SuperClassImplementsGetter = false;
1846   bool SuperClassImplementsSetter = false;
1847   if (Prop->getPropertyAttributes() & ObjCPropertyAttribute::kind_readonly)
1848     SuperClassImplementsSetter = true;
1849 
1850   while (IDecl->getSuperClass()) {
1851     ObjCInterfaceDecl *SDecl = IDecl->getSuperClass();
1852     if (!SuperClassImplementsGetter && SDecl->getInstanceMethod(Prop->getGetterName()))
1853       SuperClassImplementsGetter = true;
1854 
1855     if (!SuperClassImplementsSetter && SDecl->getInstanceMethod(Prop->getSetterName()))
1856       SuperClassImplementsSetter = true;
1857     if (SuperClassImplementsGetter && SuperClassImplementsSetter)
1858       return true;
1859     IDecl = IDecl->getSuperClass();
1860   }
1861   return false;
1862 }
1863 
1864 /// Default synthesizes all properties which must be synthesized
1865 /// in class's \@implementation.
DefaultSynthesizeProperties(Scope * S,ObjCImplDecl * IMPDecl,ObjCInterfaceDecl * IDecl,SourceLocation AtEnd)1866 void SemaObjC::DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
1867                                            ObjCInterfaceDecl *IDecl,
1868                                            SourceLocation AtEnd) {
1869   ASTContext &Context = getASTContext();
1870   ObjCInterfaceDecl::PropertyMap PropMap;
1871   IDecl->collectPropertiesToImplement(PropMap);
1872   if (PropMap.empty())
1873     return;
1874   ObjCInterfaceDecl::PropertyMap SuperPropMap;
1875   CollectSuperClassPropertyImplementations(IDecl, SuperPropMap);
1876 
1877   for (const auto &PropEntry : PropMap) {
1878     ObjCPropertyDecl *Prop = PropEntry.second;
1879     // Is there a matching property synthesize/dynamic?
1880     if (Prop->isInvalidDecl() ||
1881         Prop->isClassProperty() ||
1882         Prop->getPropertyImplementation() == ObjCPropertyDecl::Optional)
1883       continue;
1884     // Property may have been synthesized by user.
1885     if (IMPDecl->FindPropertyImplDecl(
1886             Prop->getIdentifier(), Prop->getQueryKind()))
1887       continue;
1888     ObjCMethodDecl *ImpMethod = IMPDecl->getInstanceMethod(Prop->getGetterName());
1889     if (ImpMethod && !ImpMethod->getBody()) {
1890       if (Prop->getPropertyAttributes() & ObjCPropertyAttribute::kind_readonly)
1891         continue;
1892       ImpMethod = IMPDecl->getInstanceMethod(Prop->getSetterName());
1893       if (ImpMethod && !ImpMethod->getBody())
1894         continue;
1895     }
1896     if (ObjCPropertyImplDecl *PID =
1897         IMPDecl->FindPropertyImplIvarDecl(Prop->getIdentifier())) {
1898       Diag(Prop->getLocation(), diag::warn_no_autosynthesis_shared_ivar_property)
1899         << Prop->getIdentifier();
1900       if (PID->getLocation().isValid())
1901         Diag(PID->getLocation(), diag::note_property_synthesize);
1902       continue;
1903     }
1904     ObjCPropertyDecl *PropInSuperClass =
1905         SuperPropMap[std::make_pair(Prop->getIdentifier(),
1906                                     Prop->isClassProperty())];
1907     if (ObjCProtocolDecl *Proto =
1908           dyn_cast<ObjCProtocolDecl>(Prop->getDeclContext())) {
1909       // We won't auto-synthesize properties declared in protocols.
1910       // Suppress the warning if class's superclass implements property's
1911       // getter and implements property's setter (if readwrite property).
1912       // Or, if property is going to be implemented in its super class.
1913       if (!SuperClassImplementsProperty(IDecl, Prop) && !PropInSuperClass) {
1914         Diag(IMPDecl->getLocation(),
1915              diag::warn_auto_synthesizing_protocol_property)
1916           << Prop << Proto;
1917         Diag(Prop->getLocation(), diag::note_property_declare);
1918         std::string FixIt =
1919             (Twine("@synthesize ") + Prop->getName() + ";\n\n").str();
1920         Diag(AtEnd, diag::note_add_synthesize_directive)
1921             << FixItHint::CreateInsertion(AtEnd, FixIt);
1922       }
1923       continue;
1924     }
1925     // If property to be implemented in the super class, ignore.
1926     if (PropInSuperClass) {
1927       if ((Prop->getPropertyAttributes() &
1928            ObjCPropertyAttribute::kind_readwrite) &&
1929           (PropInSuperClass->getPropertyAttributes() &
1930            ObjCPropertyAttribute::kind_readonly) &&
1931           !IMPDecl->getInstanceMethod(Prop->getSetterName()) &&
1932           !IDecl->HasUserDeclaredSetterMethod(Prop)) {
1933         Diag(Prop->getLocation(), diag::warn_no_autosynthesis_property)
1934         << Prop->getIdentifier();
1935         Diag(PropInSuperClass->getLocation(), diag::note_property_declare);
1936       } else {
1937         Diag(Prop->getLocation(), diag::warn_autosynthesis_property_in_superclass)
1938         << Prop->getIdentifier();
1939         Diag(PropInSuperClass->getLocation(), diag::note_property_declare);
1940         Diag(IMPDecl->getLocation(), diag::note_while_in_implementation);
1941       }
1942       continue;
1943     }
1944     // We use invalid SourceLocations for the synthesized ivars since they
1945     // aren't really synthesized at a particular location; they just exist.
1946     // Saying that they are located at the @implementation isn't really going
1947     // to help users.
1948     ObjCPropertyImplDecl *PIDecl = dyn_cast_or_null<ObjCPropertyImplDecl>(
1949       ActOnPropertyImplDecl(S, SourceLocation(), SourceLocation(),
1950                             true,
1951                             /* property = */ Prop->getIdentifier(),
1952                             /* ivar = */ Prop->getDefaultSynthIvarName(Context),
1953                             Prop->getLocation(), Prop->getQueryKind()));
1954     if (PIDecl && !Prop->isUnavailable()) {
1955       Diag(Prop->getLocation(), diag::warn_missing_explicit_synthesis);
1956       Diag(IMPDecl->getLocation(), diag::note_while_in_implementation);
1957     }
1958   }
1959 }
1960 
DefaultSynthesizeProperties(Scope * S,Decl * D,SourceLocation AtEnd)1961 void SemaObjC::DefaultSynthesizeProperties(Scope *S, Decl *D,
1962                                            SourceLocation AtEnd) {
1963   if (!getLangOpts().ObjCDefaultSynthProperties ||
1964       getLangOpts().ObjCRuntime.isFragile())
1965     return;
1966   ObjCImplementationDecl *IC=dyn_cast_or_null<ObjCImplementationDecl>(D);
1967   if (!IC)
1968     return;
1969   if (ObjCInterfaceDecl* IDecl = IC->getClassInterface())
1970     if (!IDecl->isObjCRequiresPropertyDefs())
1971       DefaultSynthesizeProperties(S, IC, IDecl, AtEnd);
1972 }
1973 
DiagnoseUnimplementedAccessor(Sema & S,ObjCInterfaceDecl * PrimaryClass,Selector Method,ObjCImplDecl * IMPDecl,ObjCContainerDecl * CDecl,ObjCCategoryDecl * C,ObjCPropertyDecl * Prop,llvm::SmallPtrSet<const ObjCMethodDecl *,8> & SMap)1974 static void DiagnoseUnimplementedAccessor(
1975     Sema &S, ObjCInterfaceDecl *PrimaryClass, Selector Method,
1976     ObjCImplDecl *IMPDecl, ObjCContainerDecl *CDecl, ObjCCategoryDecl *C,
1977     ObjCPropertyDecl *Prop,
1978     llvm::SmallPtrSet<const ObjCMethodDecl *, 8> &SMap) {
1979   // Check to see if we have a corresponding selector in SMap and with the
1980   // right method type.
1981   auto I = llvm::find_if(SMap, [&](const ObjCMethodDecl *x) {
1982     return x->getSelector() == Method &&
1983            x->isClassMethod() == Prop->isClassProperty();
1984   });
1985   // When reporting on missing property setter/getter implementation in
1986   // categories, do not report when they are declared in primary class,
1987   // class's protocol, or one of it super classes. This is because,
1988   // the class is going to implement them.
1989   if (I == SMap.end() &&
1990       (PrimaryClass == nullptr ||
1991        !PrimaryClass->lookupPropertyAccessor(Method, C,
1992                                              Prop->isClassProperty()))) {
1993     unsigned diag =
1994         isa<ObjCCategoryDecl>(CDecl)
1995             ? (Prop->isClassProperty()
1996                    ? diag::warn_impl_required_in_category_for_class_property
1997                    : diag::warn_setter_getter_impl_required_in_category)
1998             : (Prop->isClassProperty()
1999                    ? diag::warn_impl_required_for_class_property
2000                    : diag::warn_setter_getter_impl_required);
2001     S.Diag(IMPDecl->getLocation(), diag) << Prop->getDeclName() << Method;
2002     S.Diag(Prop->getLocation(), diag::note_property_declare);
2003     if (S.LangOpts.ObjCDefaultSynthProperties &&
2004         S.LangOpts.ObjCRuntime.isNonFragile())
2005       if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CDecl))
2006         if (const ObjCInterfaceDecl *RID = ID->isObjCRequiresPropertyDefs())
2007           S.Diag(RID->getLocation(), diag::note_suppressed_class_declare);
2008   }
2009 }
2010 
DiagnoseUnimplementedProperties(Scope * S,ObjCImplDecl * IMPDecl,ObjCContainerDecl * CDecl,bool SynthesizeProperties)2011 void SemaObjC::DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl *IMPDecl,
2012                                                ObjCContainerDecl *CDecl,
2013                                                bool SynthesizeProperties) {
2014   ObjCContainerDecl::PropertyMap PropMap;
2015   ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
2016 
2017   // Since we don't synthesize class properties, we should emit diagnose even
2018   // if SynthesizeProperties is true.
2019   ObjCContainerDecl::PropertyMap NoNeedToImplPropMap;
2020   // Gather properties which need not be implemented in this class
2021   // or category.
2022   if (!IDecl)
2023     if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2024       // For categories, no need to implement properties declared in
2025       // its primary class (and its super classes) if property is
2026       // declared in one of those containers.
2027       if ((IDecl = C->getClassInterface())) {
2028         IDecl->collectPropertiesToImplement(NoNeedToImplPropMap);
2029       }
2030     }
2031   if (IDecl)
2032     CollectSuperClassPropertyImplementations(IDecl, NoNeedToImplPropMap);
2033 
2034   // When SynthesizeProperties is true, we only check class properties.
2035   CollectImmediateProperties(CDecl, PropMap, NoNeedToImplPropMap,
2036                              SynthesizeProperties/*CollectClassPropsOnly*/);
2037 
2038   // Scan the @interface to see if any of the protocols it adopts
2039   // require an explicit implementation, via attribute
2040   // 'objc_protocol_requires_explicit_implementation'.
2041   if (IDecl) {
2042     std::unique_ptr<ObjCContainerDecl::PropertyMap> LazyMap;
2043 
2044     for (auto *PDecl : IDecl->all_referenced_protocols()) {
2045       if (!PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2046         continue;
2047       // Lazily construct a set of all the properties in the @interface
2048       // of the class, without looking at the superclass.  We cannot
2049       // use the call to CollectImmediateProperties() above as that
2050       // utilizes information from the super class's properties as well
2051       // as scans the adopted protocols.  This work only triggers for protocols
2052       // with the attribute, which is very rare, and only occurs when
2053       // analyzing the @implementation.
2054       if (!LazyMap) {
2055         ObjCContainerDecl::PropertyMap NoNeedToImplPropMap;
2056         LazyMap.reset(new ObjCContainerDecl::PropertyMap());
2057         CollectImmediateProperties(CDecl, *LazyMap, NoNeedToImplPropMap,
2058                                    /* CollectClassPropsOnly */ false,
2059                                    /* IncludeProtocols */ false);
2060       }
2061       // Add the properties of 'PDecl' to the list of properties that
2062       // need to be implemented.
2063       for (auto *PropDecl : PDecl->properties()) {
2064         if ((*LazyMap)[std::make_pair(PropDecl->getIdentifier(),
2065                                       PropDecl->isClassProperty())])
2066           continue;
2067         PropMap[std::make_pair(PropDecl->getIdentifier(),
2068                                PropDecl->isClassProperty())] = PropDecl;
2069       }
2070     }
2071   }
2072 
2073   if (PropMap.empty())
2074     return;
2075 
2076   llvm::DenseSet<ObjCPropertyDecl *> PropImplMap;
2077   for (const auto *I : IMPDecl->property_impls())
2078     PropImplMap.insert(I->getPropertyDecl());
2079 
2080   llvm::SmallPtrSet<const ObjCMethodDecl *, 8> InsMap;
2081   // Collect property accessors implemented in current implementation.
2082   for (const auto *I : IMPDecl->methods())
2083     InsMap.insert(I);
2084 
2085   ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
2086   ObjCInterfaceDecl *PrimaryClass = nullptr;
2087   if (C && !C->IsClassExtension())
2088     if ((PrimaryClass = C->getClassInterface()))
2089       // Report unimplemented properties in the category as well.
2090       if (ObjCImplDecl *IMP = PrimaryClass->getImplementation()) {
2091         // When reporting on missing setter/getters, do not report when
2092         // setter/getter is implemented in category's primary class
2093         // implementation.
2094         for (const auto *I : IMP->methods())
2095           InsMap.insert(I);
2096       }
2097 
2098   for (ObjCContainerDecl::PropertyMap::iterator
2099        P = PropMap.begin(), E = PropMap.end(); P != E; ++P) {
2100     ObjCPropertyDecl *Prop = P->second;
2101     // Is there a matching property synthesize/dynamic?
2102     if (Prop->isInvalidDecl() ||
2103         Prop->getPropertyImplementation() == ObjCPropertyDecl::Optional ||
2104         PropImplMap.count(Prop) ||
2105         Prop->getAvailability() == AR_Unavailable)
2106       continue;
2107 
2108     // Diagnose unimplemented getters and setters.
2109     DiagnoseUnimplementedAccessor(SemaRef, PrimaryClass, Prop->getGetterName(),
2110                                   IMPDecl, CDecl, C, Prop, InsMap);
2111     if (!Prop->isReadOnly())
2112       DiagnoseUnimplementedAccessor(SemaRef, PrimaryClass,
2113                                     Prop->getSetterName(), IMPDecl, CDecl, C,
2114                                     Prop, InsMap);
2115   }
2116 }
2117 
diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl * impDecl)2118 void SemaObjC::diagnoseNullResettableSynthesizedSetters(
2119     const ObjCImplDecl *impDecl) {
2120   for (const auto *propertyImpl : impDecl->property_impls()) {
2121     const auto *property = propertyImpl->getPropertyDecl();
2122     // Warn about null_resettable properties with synthesized setters,
2123     // because the setter won't properly handle nil.
2124     if (propertyImpl->getPropertyImplementation() ==
2125             ObjCPropertyImplDecl::Synthesize &&
2126         (property->getPropertyAttributes() &
2127          ObjCPropertyAttribute::kind_null_resettable) &&
2128         property->getGetterMethodDecl() && property->getSetterMethodDecl()) {
2129       auto *getterImpl = propertyImpl->getGetterMethodDecl();
2130       auto *setterImpl = propertyImpl->getSetterMethodDecl();
2131       if ((!getterImpl || getterImpl->isSynthesizedAccessorStub()) &&
2132           (!setterImpl || setterImpl->isSynthesizedAccessorStub())) {
2133         SourceLocation loc = propertyImpl->getLocation();
2134         if (loc.isInvalid())
2135           loc = impDecl->getBeginLoc();
2136 
2137         Diag(loc, diag::warn_null_resettable_setter)
2138           << setterImpl->getSelector() << property->getDeclName();
2139       }
2140     }
2141   }
2142 }
2143 
AtomicPropertySetterGetterRules(ObjCImplDecl * IMPDecl,ObjCInterfaceDecl * IDecl)2144 void SemaObjC::AtomicPropertySetterGetterRules(ObjCImplDecl *IMPDecl,
2145                                                ObjCInterfaceDecl *IDecl) {
2146   // Rules apply in non-GC mode only
2147   if (getLangOpts().getGC() != LangOptions::NonGC)
2148     return;
2149   ObjCContainerDecl::PropertyMap PM;
2150   for (auto *Prop : IDecl->properties())
2151     PM[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] = Prop;
2152   for (const auto *Ext : IDecl->known_extensions())
2153     for (auto *Prop : Ext->properties())
2154       PM[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] = Prop;
2155 
2156   for (ObjCContainerDecl::PropertyMap::iterator I = PM.begin(), E = PM.end();
2157        I != E; ++I) {
2158     const ObjCPropertyDecl *Property = I->second;
2159     ObjCMethodDecl *GetterMethod = nullptr;
2160     ObjCMethodDecl *SetterMethod = nullptr;
2161 
2162     unsigned Attributes = Property->getPropertyAttributes();
2163     unsigned AttributesAsWritten = Property->getPropertyAttributesAsWritten();
2164 
2165     if (!(AttributesAsWritten & ObjCPropertyAttribute::kind_atomic) &&
2166         !(AttributesAsWritten & ObjCPropertyAttribute::kind_nonatomic)) {
2167       GetterMethod = Property->isClassProperty() ?
2168                      IMPDecl->getClassMethod(Property->getGetterName()) :
2169                      IMPDecl->getInstanceMethod(Property->getGetterName());
2170       SetterMethod = Property->isClassProperty() ?
2171                      IMPDecl->getClassMethod(Property->getSetterName()) :
2172                      IMPDecl->getInstanceMethod(Property->getSetterName());
2173       if (GetterMethod && GetterMethod->isSynthesizedAccessorStub())
2174         GetterMethod = nullptr;
2175       if (SetterMethod && SetterMethod->isSynthesizedAccessorStub())
2176         SetterMethod = nullptr;
2177       if (GetterMethod) {
2178         Diag(GetterMethod->getLocation(),
2179              diag::warn_default_atomic_custom_getter_setter)
2180           << Property->getIdentifier() << 0;
2181         Diag(Property->getLocation(), diag::note_property_declare);
2182       }
2183       if (SetterMethod) {
2184         Diag(SetterMethod->getLocation(),
2185              diag::warn_default_atomic_custom_getter_setter)
2186           << Property->getIdentifier() << 1;
2187         Diag(Property->getLocation(), diag::note_property_declare);
2188       }
2189     }
2190 
2191     // We only care about readwrite atomic property.
2192     if ((Attributes & ObjCPropertyAttribute::kind_nonatomic) ||
2193         !(Attributes & ObjCPropertyAttribute::kind_readwrite))
2194       continue;
2195     if (const ObjCPropertyImplDecl *PIDecl = IMPDecl->FindPropertyImplDecl(
2196             Property->getIdentifier(), Property->getQueryKind())) {
2197       if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
2198         continue;
2199       GetterMethod = PIDecl->getGetterMethodDecl();
2200       SetterMethod = PIDecl->getSetterMethodDecl();
2201       if (GetterMethod && GetterMethod->isSynthesizedAccessorStub())
2202         GetterMethod = nullptr;
2203       if (SetterMethod && SetterMethod->isSynthesizedAccessorStub())
2204         SetterMethod = nullptr;
2205       if ((bool)GetterMethod ^ (bool)SetterMethod) {
2206         SourceLocation MethodLoc =
2207           (GetterMethod ? GetterMethod->getLocation()
2208                         : SetterMethod->getLocation());
2209         Diag(MethodLoc, diag::warn_atomic_property_rule)
2210           << Property->getIdentifier() << (GetterMethod != nullptr)
2211           << (SetterMethod != nullptr);
2212         // fixit stuff.
2213         if (Property->getLParenLoc().isValid() &&
2214             !(AttributesAsWritten & ObjCPropertyAttribute::kind_atomic)) {
2215           // @property () ... case.
2216           SourceLocation AfterLParen =
2217               SemaRef.getLocForEndOfToken(Property->getLParenLoc());
2218           StringRef NonatomicStr = AttributesAsWritten? "nonatomic, "
2219                                                       : "nonatomic";
2220           Diag(Property->getLocation(),
2221                diag::note_atomic_property_fixup_suggest)
2222             << FixItHint::CreateInsertion(AfterLParen, NonatomicStr);
2223         } else if (Property->getLParenLoc().isInvalid()) {
2224           //@property id etc.
2225           SourceLocation startLoc =
2226             Property->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
2227           Diag(Property->getLocation(),
2228                diag::note_atomic_property_fixup_suggest)
2229             << FixItHint::CreateInsertion(startLoc, "(nonatomic) ");
2230         } else
2231           Diag(MethodLoc, diag::note_atomic_property_fixup_suggest);
2232         Diag(Property->getLocation(), diag::note_property_declare);
2233       }
2234     }
2235   }
2236 }
2237 
DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl * D)2238 void SemaObjC::DiagnoseOwningPropertyGetterSynthesis(
2239     const ObjCImplementationDecl *D) {
2240   if (getLangOpts().getGC() == LangOptions::GCOnly)
2241     return;
2242 
2243   for (const auto *PID : D->property_impls()) {
2244     const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2245     if (PD && !PD->hasAttr<NSReturnsNotRetainedAttr>() &&
2246         !PD->isClassProperty()) {
2247       ObjCMethodDecl *IM = PID->getGetterMethodDecl();
2248       if (IM && !IM->isSynthesizedAccessorStub())
2249         continue;
2250       ObjCMethodDecl *method = PD->getGetterMethodDecl();
2251       if (!method)
2252         continue;
2253       ObjCMethodFamily family = method->getMethodFamily();
2254       if (family == OMF_alloc || family == OMF_copy ||
2255           family == OMF_mutableCopy || family == OMF_new) {
2256         if (getLangOpts().ObjCAutoRefCount)
2257           Diag(PD->getLocation(), diag::err_cocoa_naming_owned_rule);
2258         else
2259           Diag(PD->getLocation(), diag::warn_cocoa_naming_owned_rule);
2260 
2261         // Look for a getter explicitly declared alongside the property.
2262         // If we find one, use its location for the note.
2263         SourceLocation noteLoc = PD->getLocation();
2264         SourceLocation fixItLoc;
2265         for (auto *getterRedecl : method->redecls()) {
2266           if (getterRedecl->isImplicit())
2267             continue;
2268           if (getterRedecl->getDeclContext() != PD->getDeclContext())
2269             continue;
2270           noteLoc = getterRedecl->getLocation();
2271           fixItLoc = getterRedecl->getEndLoc();
2272         }
2273 
2274         Preprocessor &PP = SemaRef.getPreprocessor();
2275         TokenValue tokens[] = {
2276           tok::kw___attribute, tok::l_paren, tok::l_paren,
2277           PP.getIdentifierInfo("objc_method_family"), tok::l_paren,
2278           PP.getIdentifierInfo("none"), tok::r_paren,
2279           tok::r_paren, tok::r_paren
2280         };
2281         StringRef spelling = "__attribute__((objc_method_family(none)))";
2282         StringRef macroName = PP.getLastMacroWithSpelling(noteLoc, tokens);
2283         if (!macroName.empty())
2284           spelling = macroName;
2285 
2286         auto noteDiag = Diag(noteLoc, diag::note_cocoa_naming_declare_family)
2287             << method->getDeclName() << spelling;
2288         if (fixItLoc.isValid()) {
2289           SmallString<64> fixItText(" ");
2290           fixItText += spelling;
2291           noteDiag << FixItHint::CreateInsertion(fixItLoc, fixItText);
2292         }
2293       }
2294     }
2295   }
2296 }
2297 
DiagnoseMissingDesignatedInitOverrides(const ObjCImplementationDecl * ImplD,const ObjCInterfaceDecl * IFD)2298 void SemaObjC::DiagnoseMissingDesignatedInitOverrides(
2299     const ObjCImplementationDecl *ImplD, const ObjCInterfaceDecl *IFD) {
2300   assert(IFD->hasDesignatedInitializers());
2301   const ObjCInterfaceDecl *SuperD = IFD->getSuperClass();
2302   if (!SuperD)
2303     return;
2304 
2305   SelectorSet InitSelSet;
2306   for (const auto *I : ImplD->instance_methods())
2307     if (I->getMethodFamily() == OMF_init)
2308       InitSelSet.insert(I->getSelector());
2309 
2310   SmallVector<const ObjCMethodDecl *, 8> DesignatedInits;
2311   SuperD->getDesignatedInitializers(DesignatedInits);
2312   for (SmallVector<const ObjCMethodDecl *, 8>::iterator
2313          I = DesignatedInits.begin(), E = DesignatedInits.end(); I != E; ++I) {
2314     const ObjCMethodDecl *MD = *I;
2315     if (!InitSelSet.count(MD->getSelector())) {
2316       // Don't emit a diagnostic if the overriding method in the subclass is
2317       // marked as unavailable.
2318       bool Ignore = false;
2319       if (auto *IMD = IFD->getInstanceMethod(MD->getSelector())) {
2320         Ignore = IMD->isUnavailable();
2321       } else {
2322         // Check the methods declared in the class extensions too.
2323         for (auto *Ext : IFD->visible_extensions())
2324           if (auto *IMD = Ext->getInstanceMethod(MD->getSelector())) {
2325             Ignore = IMD->isUnavailable();
2326             break;
2327           }
2328       }
2329       if (!Ignore) {
2330         Diag(ImplD->getLocation(),
2331              diag::warn_objc_implementation_missing_designated_init_override)
2332           << MD->getSelector();
2333         Diag(MD->getLocation(), diag::note_objc_designated_init_marked_here);
2334       }
2335     }
2336   }
2337 }
2338 
2339 /// AddPropertyAttrs - Propagates attributes from a property to the
2340 /// implicitly-declared getter or setter for that property.
AddPropertyAttrs(Sema & S,ObjCMethodDecl * PropertyMethod,ObjCPropertyDecl * Property)2341 static void AddPropertyAttrs(Sema &S, ObjCMethodDecl *PropertyMethod,
2342                              ObjCPropertyDecl *Property) {
2343   // Should we just clone all attributes over?
2344   for (const auto *A : Property->attrs()) {
2345     if (isa<DeprecatedAttr>(A) ||
2346         isa<UnavailableAttr>(A) ||
2347         isa<AvailabilityAttr>(A))
2348       PropertyMethod->addAttr(A->clone(S.Context));
2349   }
2350 }
2351 
2352 /// ProcessPropertyDecl - Make sure that any user-defined setter/getter methods
2353 /// have the property type and issue diagnostics if they don't.
2354 /// Also synthesize a getter/setter method if none exist (and update the
2355 /// appropriate lookup tables.
ProcessPropertyDecl(ObjCPropertyDecl * property)2356 void SemaObjC::ProcessPropertyDecl(ObjCPropertyDecl *property) {
2357   ASTContext &Context = getASTContext();
2358   ObjCMethodDecl *GetterMethod, *SetterMethod;
2359   ObjCContainerDecl *CD = cast<ObjCContainerDecl>(property->getDeclContext());
2360   if (CD->isInvalidDecl())
2361     return;
2362 
2363   bool IsClassProperty = property->isClassProperty();
2364   GetterMethod = IsClassProperty ?
2365     CD->getClassMethod(property->getGetterName()) :
2366     CD->getInstanceMethod(property->getGetterName());
2367 
2368   // if setter or getter is not found in class extension, it might be
2369   // in the primary class.
2370   if (!GetterMethod)
2371     if (const ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CD))
2372       if (CatDecl->IsClassExtension())
2373         GetterMethod = IsClassProperty ? CatDecl->getClassInterface()->
2374                          getClassMethod(property->getGetterName()) :
2375                        CatDecl->getClassInterface()->
2376                          getInstanceMethod(property->getGetterName());
2377 
2378   SetterMethod = IsClassProperty ?
2379                  CD->getClassMethod(property->getSetterName()) :
2380                  CD->getInstanceMethod(property->getSetterName());
2381   if (!SetterMethod)
2382     if (const ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CD))
2383       if (CatDecl->IsClassExtension())
2384         SetterMethod = IsClassProperty ? CatDecl->getClassInterface()->
2385                           getClassMethod(property->getSetterName()) :
2386                        CatDecl->getClassInterface()->
2387                           getInstanceMethod(property->getSetterName());
2388   DiagnosePropertyAccessorMismatch(property, GetterMethod,
2389                                    property->getLocation());
2390 
2391   // synthesizing accessors must not result in a direct method that is not
2392   // monomorphic
2393   if (!GetterMethod) {
2394     if (const ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CD)) {
2395       auto *ExistingGetter = CatDecl->getClassInterface()->lookupMethod(
2396           property->getGetterName(), !IsClassProperty, true, false, CatDecl);
2397       if (ExistingGetter) {
2398         if (ExistingGetter->isDirectMethod() || property->isDirectProperty()) {
2399           Diag(property->getLocation(), diag::err_objc_direct_duplicate_decl)
2400               << property->isDirectProperty() << 1 /* property */
2401               << ExistingGetter->isDirectMethod()
2402               << ExistingGetter->getDeclName();
2403           Diag(ExistingGetter->getLocation(), diag::note_previous_declaration);
2404         }
2405       }
2406     }
2407   }
2408 
2409   if (!property->isReadOnly() && !SetterMethod) {
2410     if (const ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CD)) {
2411       auto *ExistingSetter = CatDecl->getClassInterface()->lookupMethod(
2412           property->getSetterName(), !IsClassProperty, true, false, CatDecl);
2413       if (ExistingSetter) {
2414         if (ExistingSetter->isDirectMethod() || property->isDirectProperty()) {
2415           Diag(property->getLocation(), diag::err_objc_direct_duplicate_decl)
2416               << property->isDirectProperty() << 1 /* property */
2417               << ExistingSetter->isDirectMethod()
2418               << ExistingSetter->getDeclName();
2419           Diag(ExistingSetter->getLocation(), diag::note_previous_declaration);
2420         }
2421       }
2422     }
2423   }
2424 
2425   if (!property->isReadOnly() && SetterMethod) {
2426     if (Context.getCanonicalType(SetterMethod->getReturnType()) !=
2427         Context.VoidTy)
2428       Diag(SetterMethod->getLocation(), diag::err_setter_type_void);
2429     if (SetterMethod->param_size() != 1 ||
2430         !Context.hasSameUnqualifiedType(
2431           (*SetterMethod->param_begin())->getType().getNonReferenceType(),
2432           property->getType().getNonReferenceType())) {
2433       Diag(property->getLocation(),
2434            diag::warn_accessor_property_type_mismatch)
2435         << property->getDeclName()
2436         << SetterMethod->getSelector();
2437       Diag(SetterMethod->getLocation(), diag::note_declared_at);
2438     }
2439   }
2440 
2441   // Synthesize getter/setter methods if none exist.
2442   // Find the default getter and if one not found, add one.
2443   // FIXME: The synthesized property we set here is misleading. We almost always
2444   // synthesize these methods unless the user explicitly provided prototypes
2445   // (which is odd, but allowed). Sema should be typechecking that the
2446   // declarations jive in that situation (which it is not currently).
2447   if (!GetterMethod) {
2448     // No instance/class method of same name as property getter name was found.
2449     // Declare a getter method and add it to the list of methods
2450     // for this class.
2451     SourceLocation Loc = property->getLocation();
2452 
2453     // The getter returns the declared property type with all qualifiers
2454     // removed.
2455     QualType resultTy = property->getType().getAtomicUnqualifiedType();
2456 
2457     // If the property is null_resettable, the getter returns nonnull.
2458     if (property->getPropertyAttributes() &
2459         ObjCPropertyAttribute::kind_null_resettable) {
2460       QualType modifiedTy = resultTy;
2461       if (auto nullability = AttributedType::stripOuterNullability(modifiedTy)) {
2462         if (*nullability == NullabilityKind::Unspecified)
2463           resultTy = Context.getAttributedType(attr::TypeNonNull,
2464                                                modifiedTy, modifiedTy);
2465       }
2466     }
2467 
2468     GetterMethod = ObjCMethodDecl::Create(
2469         Context, Loc, Loc, property->getGetterName(), resultTy, nullptr, CD,
2470         !IsClassProperty, /*isVariadic=*/false,
2471         /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
2472         /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
2473         (property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
2474             ? ObjCImplementationControl::Optional
2475             : ObjCImplementationControl::Required);
2476     CD->addDecl(GetterMethod);
2477 
2478     AddPropertyAttrs(SemaRef, GetterMethod, property);
2479 
2480     if (property->isDirectProperty())
2481       GetterMethod->addAttr(ObjCDirectAttr::CreateImplicit(Context, Loc));
2482 
2483     if (property->hasAttr<NSReturnsNotRetainedAttr>())
2484       GetterMethod->addAttr(NSReturnsNotRetainedAttr::CreateImplicit(Context,
2485                                                                      Loc));
2486 
2487     if (property->hasAttr<ObjCReturnsInnerPointerAttr>())
2488       GetterMethod->addAttr(
2489         ObjCReturnsInnerPointerAttr::CreateImplicit(Context, Loc));
2490 
2491     if (const SectionAttr *SA = property->getAttr<SectionAttr>())
2492       GetterMethod->addAttr(SectionAttr::CreateImplicit(
2493           Context, SA->getName(), Loc, SectionAttr::GNU_section));
2494 
2495     SemaRef.ProcessAPINotes(GetterMethod);
2496 
2497     if (getLangOpts().ObjCAutoRefCount)
2498       CheckARCMethodDecl(GetterMethod);
2499   } else
2500     // A user declared getter will be synthesize when @synthesize of
2501     // the property with the same name is seen in the @implementation
2502     GetterMethod->setPropertyAccessor(true);
2503 
2504   GetterMethod->createImplicitParams(Context,
2505                                      GetterMethod->getClassInterface());
2506   property->setGetterMethodDecl(GetterMethod);
2507 
2508   // Skip setter if property is read-only.
2509   if (!property->isReadOnly()) {
2510     // Find the default setter and if one not found, add one.
2511     if (!SetterMethod) {
2512       // No instance/class method of same name as property setter name was
2513       // found.
2514       // Declare a setter method and add it to the list of methods
2515       // for this class.
2516       SourceLocation Loc = property->getLocation();
2517 
2518       SetterMethod = ObjCMethodDecl::Create(
2519           Context, Loc, Loc, property->getSetterName(), Context.VoidTy, nullptr,
2520           CD, !IsClassProperty,
2521           /*isVariadic=*/false,
2522           /*isPropertyAccessor=*/true,
2523           /*isSynthesizedAccessorStub=*/false,
2524           /*isImplicitlyDeclared=*/true,
2525           /*isDefined=*/false,
2526           (property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
2527               ? ObjCImplementationControl::Optional
2528               : ObjCImplementationControl::Required);
2529 
2530       // Remove all qualifiers from the setter's parameter type.
2531       QualType paramTy =
2532           property->getType().getUnqualifiedType().getAtomicUnqualifiedType();
2533 
2534       // If the property is null_resettable, the setter accepts a
2535       // nullable value.
2536       if (property->getPropertyAttributes() &
2537           ObjCPropertyAttribute::kind_null_resettable) {
2538         QualType modifiedTy = paramTy;
2539         if (auto nullability = AttributedType::stripOuterNullability(modifiedTy)){
2540           if (*nullability == NullabilityKind::Unspecified)
2541             paramTy = Context.getAttributedType(attr::TypeNullable,
2542                                                 modifiedTy, modifiedTy);
2543         }
2544       }
2545 
2546       // Invent the arguments for the setter. We don't bother making a
2547       // nice name for the argument.
2548       ParmVarDecl *Argument = ParmVarDecl::Create(Context, SetterMethod,
2549                                                   Loc, Loc,
2550                                                   property->getIdentifier(),
2551                                                   paramTy,
2552                                                   /*TInfo=*/nullptr,
2553                                                   SC_None,
2554                                                   nullptr);
2555       SetterMethod->setMethodParams(Context, Argument, std::nullopt);
2556 
2557       AddPropertyAttrs(SemaRef, SetterMethod, property);
2558 
2559       if (property->isDirectProperty())
2560         SetterMethod->addAttr(ObjCDirectAttr::CreateImplicit(Context, Loc));
2561 
2562       CD->addDecl(SetterMethod);
2563       if (const SectionAttr *SA = property->getAttr<SectionAttr>())
2564         SetterMethod->addAttr(SectionAttr::CreateImplicit(
2565             Context, SA->getName(), Loc, SectionAttr::GNU_section));
2566 
2567       SemaRef.ProcessAPINotes(SetterMethod);
2568 
2569       // It's possible for the user to have set a very odd custom
2570       // setter selector that causes it to have a method family.
2571       if (getLangOpts().ObjCAutoRefCount)
2572         CheckARCMethodDecl(SetterMethod);
2573     } else
2574       // A user declared setter will be synthesize when @synthesize of
2575       // the property with the same name is seen in the @implementation
2576       SetterMethod->setPropertyAccessor(true);
2577 
2578     SetterMethod->createImplicitParams(Context,
2579                                        SetterMethod->getClassInterface());
2580     property->setSetterMethodDecl(SetterMethod);
2581   }
2582   // Add any synthesized methods to the global pool. This allows us to
2583   // handle the following, which is supported by GCC (and part of the design).
2584   //
2585   // @interface Foo
2586   // @property double bar;
2587   // @end
2588   //
2589   // void thisIsUnfortunate() {
2590   //   id foo;
2591   //   double bar = [foo bar];
2592   // }
2593   //
2594   if (!IsClassProperty) {
2595     if (GetterMethod)
2596       AddInstanceMethodToGlobalPool(GetterMethod);
2597     if (SetterMethod)
2598       AddInstanceMethodToGlobalPool(SetterMethod);
2599   } else {
2600     if (GetterMethod)
2601       AddFactoryMethodToGlobalPool(GetterMethod);
2602     if (SetterMethod)
2603       AddFactoryMethodToGlobalPool(SetterMethod);
2604   }
2605 
2606   ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(CD);
2607   if (!CurrentClass) {
2608     if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(CD))
2609       CurrentClass = Cat->getClassInterface();
2610     else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(CD))
2611       CurrentClass = Impl->getClassInterface();
2612   }
2613   if (GetterMethod)
2614     CheckObjCMethodOverrides(GetterMethod, CurrentClass, SemaObjC::RTC_Unknown);
2615   if (SetterMethod)
2616     CheckObjCMethodOverrides(SetterMethod, CurrentClass, SemaObjC::RTC_Unknown);
2617 }
2618 
CheckObjCPropertyAttributes(Decl * PDecl,SourceLocation Loc,unsigned & Attributes,bool propertyInPrimaryClass)2619 void SemaObjC::CheckObjCPropertyAttributes(Decl *PDecl, SourceLocation Loc,
2620                                            unsigned &Attributes,
2621                                            bool propertyInPrimaryClass) {
2622   // FIXME: Improve the reported location.
2623   if (!PDecl || PDecl->isInvalidDecl())
2624     return;
2625 
2626   if ((Attributes & ObjCPropertyAttribute::kind_readonly) &&
2627       (Attributes & ObjCPropertyAttribute::kind_readwrite))
2628     Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2629     << "readonly" << "readwrite";
2630 
2631   ObjCPropertyDecl *PropertyDecl = cast<ObjCPropertyDecl>(PDecl);
2632   QualType PropertyTy = PropertyDecl->getType();
2633 
2634   // Check for copy or retain on non-object types.
2635   if ((Attributes &
2636        (ObjCPropertyAttribute::kind_weak | ObjCPropertyAttribute::kind_copy |
2637         ObjCPropertyAttribute::kind_retain |
2638         ObjCPropertyAttribute::kind_strong)) &&
2639       !PropertyTy->isObjCRetainableType() &&
2640       !PropertyDecl->hasAttr<ObjCNSObjectAttr>()) {
2641     Diag(Loc, diag::err_objc_property_requires_object)
2642         << (Attributes & ObjCPropertyAttribute::kind_weak
2643                 ? "weak"
2644                 : Attributes & ObjCPropertyAttribute::kind_copy
2645                       ? "copy"
2646                       : "retain (or strong)");
2647     Attributes &=
2648         ~(ObjCPropertyAttribute::kind_weak | ObjCPropertyAttribute::kind_copy |
2649           ObjCPropertyAttribute::kind_retain |
2650           ObjCPropertyAttribute::kind_strong);
2651     PropertyDecl->setInvalidDecl();
2652   }
2653 
2654   // Check for assign on object types.
2655   if ((Attributes & ObjCPropertyAttribute::kind_assign) &&
2656       !(Attributes & ObjCPropertyAttribute::kind_unsafe_unretained) &&
2657       PropertyTy->isObjCRetainableType() &&
2658       !PropertyTy->isObjCARCImplicitlyUnretainedType()) {
2659     Diag(Loc, diag::warn_objc_property_assign_on_object);
2660   }
2661 
2662   // Check for more than one of { assign, copy, retain }.
2663   if (Attributes & ObjCPropertyAttribute::kind_assign) {
2664     if (Attributes & ObjCPropertyAttribute::kind_copy) {
2665       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2666         << "assign" << "copy";
2667       Attributes &= ~ObjCPropertyAttribute::kind_copy;
2668     }
2669     if (Attributes & ObjCPropertyAttribute::kind_retain) {
2670       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2671         << "assign" << "retain";
2672       Attributes &= ~ObjCPropertyAttribute::kind_retain;
2673     }
2674     if (Attributes & ObjCPropertyAttribute::kind_strong) {
2675       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2676         << "assign" << "strong";
2677       Attributes &= ~ObjCPropertyAttribute::kind_strong;
2678     }
2679     if (getLangOpts().ObjCAutoRefCount &&
2680         (Attributes & ObjCPropertyAttribute::kind_weak)) {
2681       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2682         << "assign" << "weak";
2683       Attributes &= ~ObjCPropertyAttribute::kind_weak;
2684     }
2685     if (PropertyDecl->hasAttr<IBOutletCollectionAttr>())
2686       Diag(Loc, diag::warn_iboutletcollection_property_assign);
2687   } else if (Attributes & ObjCPropertyAttribute::kind_unsafe_unretained) {
2688     if (Attributes & ObjCPropertyAttribute::kind_copy) {
2689       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2690         << "unsafe_unretained" << "copy";
2691       Attributes &= ~ObjCPropertyAttribute::kind_copy;
2692     }
2693     if (Attributes & ObjCPropertyAttribute::kind_retain) {
2694       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2695         << "unsafe_unretained" << "retain";
2696       Attributes &= ~ObjCPropertyAttribute::kind_retain;
2697     }
2698     if (Attributes & ObjCPropertyAttribute::kind_strong) {
2699       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2700         << "unsafe_unretained" << "strong";
2701       Attributes &= ~ObjCPropertyAttribute::kind_strong;
2702     }
2703     if (getLangOpts().ObjCAutoRefCount &&
2704         (Attributes & ObjCPropertyAttribute::kind_weak)) {
2705       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2706         << "unsafe_unretained" << "weak";
2707       Attributes &= ~ObjCPropertyAttribute::kind_weak;
2708     }
2709   } else if (Attributes & ObjCPropertyAttribute::kind_copy) {
2710     if (Attributes & ObjCPropertyAttribute::kind_retain) {
2711       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2712         << "copy" << "retain";
2713       Attributes &= ~ObjCPropertyAttribute::kind_retain;
2714     }
2715     if (Attributes & ObjCPropertyAttribute::kind_strong) {
2716       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2717         << "copy" << "strong";
2718       Attributes &= ~ObjCPropertyAttribute::kind_strong;
2719     }
2720     if (Attributes & ObjCPropertyAttribute::kind_weak) {
2721       Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2722         << "copy" << "weak";
2723       Attributes &= ~ObjCPropertyAttribute::kind_weak;
2724     }
2725   } else if ((Attributes & ObjCPropertyAttribute::kind_retain) &&
2726              (Attributes & ObjCPropertyAttribute::kind_weak)) {
2727     Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) << "retain"
2728                                                                << "weak";
2729     Attributes &= ~ObjCPropertyAttribute::kind_retain;
2730   } else if ((Attributes & ObjCPropertyAttribute::kind_strong) &&
2731              (Attributes & ObjCPropertyAttribute::kind_weak)) {
2732     Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) << "strong"
2733                                                                << "weak";
2734     Attributes &= ~ObjCPropertyAttribute::kind_weak;
2735   }
2736 
2737   if (Attributes & ObjCPropertyAttribute::kind_weak) {
2738     // 'weak' and 'nonnull' are mutually exclusive.
2739     if (auto nullability = PropertyTy->getNullability()) {
2740       if (*nullability == NullabilityKind::NonNull)
2741         Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2742           << "nonnull" << "weak";
2743     }
2744   }
2745 
2746   if ((Attributes & ObjCPropertyAttribute::kind_atomic) &&
2747       (Attributes & ObjCPropertyAttribute::kind_nonatomic)) {
2748     Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) << "atomic"
2749                                                                << "nonatomic";
2750     Attributes &= ~ObjCPropertyAttribute::kind_atomic;
2751   }
2752 
2753   // Warn if user supplied no assignment attribute, property is
2754   // readwrite, and this is an object type.
2755   if (!getOwnershipRule(Attributes) && PropertyTy->isObjCRetainableType()) {
2756     if (Attributes & ObjCPropertyAttribute::kind_readonly) {
2757       // do nothing
2758     } else if (getLangOpts().ObjCAutoRefCount) {
2759       // With arc, @property definitions should default to strong when
2760       // not specified.
2761       PropertyDecl->setPropertyAttributes(ObjCPropertyAttribute::kind_strong);
2762     } else if (PropertyTy->isObjCObjectPointerType()) {
2763       bool isAnyClassTy = (PropertyTy->isObjCClassType() ||
2764                            PropertyTy->isObjCQualifiedClassType());
2765       // In non-gc, non-arc mode, 'Class' is treated as a 'void *' no need to
2766       // issue any warning.
2767       if (isAnyClassTy && getLangOpts().getGC() == LangOptions::NonGC)
2768         ;
2769       else if (propertyInPrimaryClass) {
2770         // Don't issue warning on property with no life time in class
2771         // extension as it is inherited from property in primary class.
2772         // Skip this warning in gc-only mode.
2773         if (getLangOpts().getGC() != LangOptions::GCOnly)
2774           Diag(Loc, diag::warn_objc_property_no_assignment_attribute);
2775 
2776         // If non-gc code warn that this is likely inappropriate.
2777         if (getLangOpts().getGC() == LangOptions::NonGC)
2778           Diag(Loc, diag::warn_objc_property_default_assign_on_object);
2779       }
2780     }
2781 
2782     // FIXME: Implement warning dependent on NSCopying being
2783     // implemented.
2784   }
2785 
2786   if (!(Attributes & ObjCPropertyAttribute::kind_copy) &&
2787       !(Attributes & ObjCPropertyAttribute::kind_readonly) &&
2788       getLangOpts().getGC() == LangOptions::GCOnly &&
2789       PropertyTy->isBlockPointerType())
2790     Diag(Loc, diag::warn_objc_property_copy_missing_on_block);
2791   else if ((Attributes & ObjCPropertyAttribute::kind_retain) &&
2792            !(Attributes & ObjCPropertyAttribute::kind_readonly) &&
2793            !(Attributes & ObjCPropertyAttribute::kind_strong) &&
2794            PropertyTy->isBlockPointerType())
2795     Diag(Loc, diag::warn_objc_property_retain_of_block);
2796 
2797   if ((Attributes & ObjCPropertyAttribute::kind_readonly) &&
2798       (Attributes & ObjCPropertyAttribute::kind_setter))
2799     Diag(Loc, diag::warn_objc_readonly_property_has_setter);
2800 }
2801