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