Bug Summary

File:clang/lib/Sema/SemaObjCProperty.cpp
Warning:line 2154, column 14
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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