clang 24.0.0git
IvarInvalidationChecker.cpp
Go to the documentation of this file.
1//===- IvarInvalidationChecker.cpp ------------------------------*- C++ -*-===//
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 checker implements annotation driven invalidation checking. If a class
10// contains a method annotated with 'objc_instance_variable_invalidator',
11// - (void) foo
12// __attribute__((annotate("objc_instance_variable_invalidator")));
13// all the "ivalidatable" instance variables of this class should be
14// invalidated. We call an instance variable ivalidatable if it is an object of
15// a class which contains an invalidation method. There could be multiple
16// methods annotated with such annotations per class, either one can be used
17// to invalidate the ivar. An ivar or property are considered to be
18// invalidated if they are being assigned 'nil' or an invalidation method has
19// been called on them. An invalidation method should either invalidate all
20// the ivars or call another invalidation method (on self).
21//
22// Partial invalidor annotation allows to address cases when ivars are
23// invalidated by other methods, which might or might not be called from
24// the invalidation method. The checker checks that each invalidation
25// method and all the partial methods cumulatively invalidate all ivars.
26// __attribute__((annotate("objc_instance_variable_invalidator_partial")));
27//
28//===----------------------------------------------------------------------===//
29
30#include "clang/AST/Attr.h"
31#include "clang/AST/DeclObjC.h"
37#include "llvm/ADT/DenseMap.h"
38#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/SetVector.h"
40#include "llvm/ADT/StringRef.h"
41
42using namespace clang;
43using namespace ento;
44
45namespace {
46struct ChecksFilter {
47 /// Check for missing invalidation method declarations.
48 bool check_MissingInvalidationMethod = false;
49 /// Check that all ivars are invalidated.
50 bool check_InstanceVariableInvalidation = false;
51
52 CheckerNameRef checkName_MissingInvalidationMethod;
53 CheckerNameRef checkName_InstanceVariableInvalidation;
54};
55
56class IvarInvalidationCheckerImpl {
57 typedef llvm::SmallSetVector<const ObjCMethodDecl*, 2> MethodSet;
58 typedef llvm::DenseMap<const ObjCMethodDecl*,
59 const ObjCIvarDecl*> MethToIvarMapTy;
60 typedef llvm::DenseMap<const ObjCPropertyDecl*,
61 const ObjCIvarDecl*> PropToIvarMapTy;
62 typedef llvm::DenseMap<const ObjCIvarDecl*,
63 const ObjCPropertyDecl*> IvarToPropMapTy;
64
65 struct InvalidationInfo {
66 /// Has the ivar been invalidated?
67 bool IsInvalidated = false;
68
69 /// The methods which can be used to invalidate the ivar.
70 MethodSet InvalidationMethods;
71
72 InvalidationInfo() = default;
73 void addInvalidationMethod(const ObjCMethodDecl *MD) {
74 InvalidationMethods.insert(MD);
75 }
76
77 bool needsInvalidation() const {
78 return !InvalidationMethods.empty();
79 }
80
81 bool hasMethod(const ObjCMethodDecl *MD) {
82 if (IsInvalidated)
83 return true;
84 if (llvm::is_contained(InvalidationMethods, MD)) {
85 IsInvalidated = true;
86 return true;
87 }
88 return false;
89 }
90 };
91
92 typedef llvm::DenseMap<const ObjCIvarDecl*, InvalidationInfo> IvarSet;
93
94 /// Statement visitor, which walks the method body and flags the ivars
95 /// referenced in it (either directly or via property).
96 class MethodCrawler : public ConstStmtVisitor<MethodCrawler> {
97 /// The set of Ivars which need to be invalidated.
98 IvarSet &IVars;
99
100 /// Flag is set as the result of a message send to another
101 /// invalidation method.
102 bool &CalledAnotherInvalidationMethod;
103
104 /// Property setter to ivar mapping.
105 const MethToIvarMapTy &PropertySetterToIvarMap;
106
107 /// Property getter to ivar mapping.
108 const MethToIvarMapTy &PropertyGetterToIvarMap;
109
110 /// Property to ivar mapping.
111 const PropToIvarMapTy &PropertyToIvarMap;
112
113 /// The invalidation method being currently processed.
114 const ObjCMethodDecl *InvalidationMethod;
115
116 ASTContext &Ctx;
117
118 /// Peel off parens, casts, OpaqueValueExpr, and PseudoObjectExpr.
119 const Expr *peel(const Expr *E) const;
120
121 /// Does this expression represent zero: '0'?
122 bool isZero(const Expr *E) const;
123
124 /// Mark the given ivar as invalidated.
125 void markInvalidated(const ObjCIvarDecl *Iv);
126
127 /// Checks if IvarRef refers to the tracked IVar, if yes, marks it as
128 /// invalidated.
129 void checkObjCIvarRefExpr(const ObjCIvarRefExpr *IvarRef);
130
131 /// Checks if ObjCPropertyRefExpr refers to the tracked IVar, if yes, marks
132 /// it as invalidated.
133 void checkObjCPropertyRefExpr(const ObjCPropertyRefExpr *PA);
134
135 /// Checks if ObjCMessageExpr refers to (is a getter for) the tracked IVar,
136 /// if yes, marks it as invalidated.
137 void checkObjCMessageExpr(const ObjCMessageExpr *ME);
138
139 /// Checks if the Expr refers to an ivar, if yes, marks it as invalidated.
140 void check(const Expr *E);
141
142 public:
143 MethodCrawler(IvarSet &InIVars,
144 bool &InCalledAnotherInvalidationMethod,
145 const MethToIvarMapTy &InPropertySetterToIvarMap,
146 const MethToIvarMapTy &InPropertyGetterToIvarMap,
147 const PropToIvarMapTy &InPropertyToIvarMap,
148 ASTContext &InCtx)
149 : IVars(InIVars),
150 CalledAnotherInvalidationMethod(InCalledAnotherInvalidationMethod),
151 PropertySetterToIvarMap(InPropertySetterToIvarMap),
152 PropertyGetterToIvarMap(InPropertyGetterToIvarMap),
153 PropertyToIvarMap(InPropertyToIvarMap),
154 InvalidationMethod(nullptr),
155 Ctx(InCtx) {}
156
157 void VisitStmt(const Stmt *S) { VisitChildren(S); }
158
159 void VisitBinaryOperator(const BinaryOperator *BO);
160
161 void VisitObjCMessageExpr(const ObjCMessageExpr *ME);
162
163 void VisitChildren(const Stmt *S) {
164 for (const auto *Child : S->children()) {
165 if (Child)
166 this->Visit(Child);
167 if (CalledAnotherInvalidationMethod)
168 return;
169 }
170 }
171 };
172
173 /// Check if the any of the methods inside the interface are annotated with
174 /// the invalidation annotation, update the IvarInfo accordingly.
175 /// \param LookForPartial is set when we are searching for partial
176 /// invalidators.
177 static void containsInvalidationMethod(const ObjCContainerDecl *D,
178 InvalidationInfo &Out,
179 bool LookForPartial);
180
181 /// Check if ivar should be tracked and add to TrackedIvars if positive.
182 /// Returns true if ivar should be tracked.
183 static bool trackIvar(const ObjCIvarDecl *Iv, IvarSet &TrackedIvars,
184 const ObjCIvarDecl **FirstIvarDecl);
185
186 /// Given the property declaration, and the list of tracked ivars, finds
187 /// the ivar backing the property when possible. Returns '0' when no such
188 /// ivar could be found.
189 static const ObjCIvarDecl *findPropertyBackingIvar(
190 const ObjCPropertyDecl *Prop,
191 const ObjCInterfaceDecl *InterfaceD,
192 IvarSet &TrackedIvars,
193 const ObjCIvarDecl **FirstIvarDecl);
194
195 /// Print ivar name or the property if the given ivar backs a property.
196 static void printIvar(llvm::raw_svector_ostream &os,
197 const ObjCIvarDecl *IvarDecl,
198 const IvarToPropMapTy &IvarToPopertyMap);
199
200 void reportNoInvalidationMethod(CheckerNameRef CheckName,
201 const ObjCIvarDecl *FirstIvarDecl,
202 const IvarToPropMapTy &IvarToPopertyMap,
203 const ObjCInterfaceDecl *InterfaceD,
204 bool MissingDeclaration) const;
205
206 void reportIvarNeedsInvalidation(const ObjCIvarDecl *IvarD,
207 const IvarToPropMapTy &IvarToPopertyMap,
208 const ObjCMethodDecl *MethodD) const;
209
210 AnalysisManager& Mgr;
211 BugReporter &BR;
212 /// Filter on the checks performed.
213 const ChecksFilter &Filter;
214
215public:
216 IvarInvalidationCheckerImpl(AnalysisManager& InMgr,
217 BugReporter &InBR,
218 const ChecksFilter &InFilter) :
219 Mgr (InMgr), BR(InBR), Filter(InFilter) {}
220
221 void visit(const ObjCImplementationDecl *D) const;
222};
223
224static bool isInvalidationMethod(const ObjCMethodDecl *M, bool LookForPartial) {
225 auto Wanted =
226 LookForPartial
227 ? llvm::StringLiteral("objc_instance_variable_invalidator_partial")
228 : llvm::StringLiteral("objc_instance_variable_invalidator");
229 auto IsWantedAnnotation = [Wanted](const AnnotateAttr *Ann) {
230 return Ann->getAnnotation() == Wanted;
231 };
232 return llvm::any_of(M->specific_attrs<AnnotateAttr>(), IsWantedAnnotation);
233}
234
235void IvarInvalidationCheckerImpl::containsInvalidationMethod(
236 const ObjCContainerDecl *D, InvalidationInfo &OutInfo, bool Partial) {
237
238 if (!D)
239 return;
240
241 assert(!isa<ObjCImplementationDecl>(D));
242 // TODO: Cache the results.
243
244 // Check all methods.
245 for (const auto *MDI : D->methods())
246 if (isInvalidationMethod(MDI, Partial))
247 OutInfo.addInvalidationMethod(
248 cast<ObjCMethodDecl>(MDI->getCanonicalDecl()));
249
250 // If interface, check all parent protocols and super.
251 if (const ObjCInterfaceDecl *InterfD = dyn_cast<ObjCInterfaceDecl>(D)) {
252
253 // Visit all protocols.
254 for (const auto *I : InterfD->protocols())
255 containsInvalidationMethod(I->getDefinition(), OutInfo, Partial);
256
257 // Visit all categories in case the invalidation method is declared in
258 // a category.
259 for (const auto *Ext : InterfD->visible_extensions())
260 containsInvalidationMethod(Ext, OutInfo, Partial);
261
262 containsInvalidationMethod(InterfD->getSuperClass(), OutInfo, Partial);
263 return;
264 }
265
266 // If protocol, check all parent protocols.
267 if (const ObjCProtocolDecl *ProtD = dyn_cast<ObjCProtocolDecl>(D)) {
268 for (const auto *I : ProtD->protocols()) {
269 containsInvalidationMethod(I->getDefinition(), OutInfo, Partial);
270 }
271 return;
272 }
273}
274
275bool IvarInvalidationCheckerImpl::trackIvar(const ObjCIvarDecl *Iv,
276 IvarSet &TrackedIvars,
277 const ObjCIvarDecl **FirstIvarDecl) {
278 QualType IvQTy = Iv->getType();
279 const ObjCObjectPointerType *IvTy = IvQTy->getAs<ObjCObjectPointerType>();
280 if (!IvTy)
281 return false;
282 const ObjCInterfaceDecl *IvInterf = IvTy->getInterfaceDecl();
283
284 InvalidationInfo Info;
285 containsInvalidationMethod(IvInterf, Info, /*LookForPartial*/ false);
286 if (Info.needsInvalidation()) {
287 const ObjCIvarDecl *I = cast<ObjCIvarDecl>(Iv->getCanonicalDecl());
288 TrackedIvars[I] = std::move(Info);
289 if (!*FirstIvarDecl)
290 *FirstIvarDecl = I;
291 return true;
292 }
293 return false;
294}
295
296const ObjCIvarDecl *IvarInvalidationCheckerImpl::findPropertyBackingIvar(
297 const ObjCPropertyDecl *Prop,
298 const ObjCInterfaceDecl *InterfaceD,
299 IvarSet &TrackedIvars,
300 const ObjCIvarDecl **FirstIvarDecl) {
301 const ObjCIvarDecl *IvarD = nullptr;
302
303 // Lookup for the synthesized case.
304 IvarD = Prop->getPropertyIvarDecl();
305 // We only track the ivars/properties that are defined in the current
306 // class (not the parent).
307 if (IvarD && IvarD->getContainingInterface() == InterfaceD) {
308 if (TrackedIvars.count(IvarD)) {
309 return IvarD;
310 }
311 // If the ivar is synthesized we still want to track it.
312 if (trackIvar(IvarD, TrackedIvars, FirstIvarDecl))
313 return IvarD;
314 }
315
316 // Lookup IVars named "_PropName"or "PropName" among the tracked Ivars.
317 StringRef PropName = Prop->getIdentifier()->getName();
318 for (const ObjCIvarDecl *Iv : llvm::make_first_range(TrackedIvars)) {
319 StringRef IvarName = Iv->getName();
320
321 if (IvarName == PropName)
322 return Iv;
323
324 SmallString<128> PropNameWithUnderscore;
325 {
326 llvm::raw_svector_ostream os(PropNameWithUnderscore);
327 os << '_' << PropName;
328 }
329 if (IvarName == PropNameWithUnderscore)
330 return Iv;
331 }
332
333 // Note, this is a possible source of false positives. We could look at the
334 // getter implementation to find the ivar when its name is not derived from
335 // the property name.
336 return nullptr;
337}
338
339void IvarInvalidationCheckerImpl::printIvar(llvm::raw_svector_ostream &os,
340 const ObjCIvarDecl *IvarDecl,
341 const IvarToPropMapTy &IvarToPopertyMap) {
342 if (IvarDecl->getSynthesize()) {
343 const ObjCPropertyDecl *PD = IvarToPopertyMap.lookup(IvarDecl);
344 assert(PD &&"Do we synthesize ivars for something other than properties?");
345 os << "Property "<< PD->getName() << " ";
346 } else {
347 os << "Instance variable "<< IvarDecl->getName() << " ";
348 }
349}
350
351// Check that the invalidatable interfaces with ivars/properties implement the
352// invalidation methods.
353void IvarInvalidationCheckerImpl::
354visit(const ObjCImplementationDecl *ImplD) const {
355 // Collect all ivars that need cleanup.
356 IvarSet Ivars;
357 // Record the first Ivar needing invalidation; used in reporting when only
358 // one ivar is sufficient. Cannot grab the first on the Ivars set to ensure
359 // deterministic output.
360 const ObjCIvarDecl *FirstIvarDecl = nullptr;
361 const ObjCInterfaceDecl *InterfaceD = ImplD->getClassInterface();
362
363 // Collect ivars declared in this class, its extensions and its implementation
364 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(InterfaceD);
365 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
366 Iv= Iv->getNextIvar())
367 trackIvar(Iv, Ivars, &FirstIvarDecl);
368
369 // Construct Property/Property Accessor to Ivar maps to assist checking if an
370 // ivar which is backing a property has been reset.
371 MethToIvarMapTy PropSetterToIvarMap;
372 MethToIvarMapTy PropGetterToIvarMap;
373 PropToIvarMapTy PropertyToIvarMap;
374 IvarToPropMapTy IvarToPopertyMap;
375
376 ObjCInterfaceDecl::PropertyMap PropMap;
377 InterfaceD->collectPropertiesToImplement(PropMap);
378
379 for (const ObjCPropertyDecl *PD : llvm::make_second_range(PropMap)) {
380 if (PD->isClassProperty())
381 continue;
382
383 const ObjCIvarDecl *ID = findPropertyBackingIvar(PD, InterfaceD, Ivars,
384 &FirstIvarDecl);
385 if (!ID)
386 continue;
387
388 // Store the mappings.
390 PropertyToIvarMap[PD] = ID;
391 IvarToPopertyMap[ID] = PD;
392
393 // Find the setter and the getter.
394 const ObjCMethodDecl *SetterD = PD->getSetterMethodDecl();
395 if (SetterD) {
396 SetterD = SetterD->getCanonicalDecl();
397 PropSetterToIvarMap[SetterD] = ID;
398 }
399
400 const ObjCMethodDecl *GetterD = PD->getGetterMethodDecl();
401 if (GetterD) {
402 GetterD = GetterD->getCanonicalDecl();
403 PropGetterToIvarMap[GetterD] = ID;
404 }
405 }
406
407 // If no ivars need invalidation, there is nothing to check here.
408 if (Ivars.empty())
409 return;
410
411 // Find all partial invalidation methods.
412 InvalidationInfo PartialInfo;
413 containsInvalidationMethod(InterfaceD, PartialInfo, /*LookForPartial*/ true);
414
415 // Remove ivars invalidated by the partial invalidation methods. They do not
416 // need to be invalidated in the regular invalidation methods.
417 bool AtImplementationContainsAtLeastOnePartialInvalidationMethod = false;
418 for (const ObjCMethodDecl *InterfD : PartialInfo.InvalidationMethods) {
419 // Get the corresponding method in the @implementation.
420 const ObjCMethodDecl *D = ImplD->getMethod(InterfD->getSelector(),
421 InterfD->isInstanceMethod());
422 if (Stmt *Body; D && (Body = D->getBody())) {
423 AtImplementationContainsAtLeastOnePartialInvalidationMethod = true;
424
425 bool CalledAnotherInvalidationMethod = false;
426 // The MethodCrowler is going to remove the invalidated ivars.
427 MethodCrawler(Ivars,
428 CalledAnotherInvalidationMethod,
429 PropSetterToIvarMap,
430 PropGetterToIvarMap,
431 PropertyToIvarMap,
432 BR.getContext()).VisitStmt(Body);
433 // If another invalidation method was called, trust that full invalidation
434 // has occurred.
435 if (CalledAnotherInvalidationMethod)
436 Ivars.clear();
437 }
438 }
439
440 // If all ivars have been invalidated by partial invalidators, there is
441 // nothing to check here.
442 if (Ivars.empty())
443 return;
444
445 // Find all invalidation methods in this @interface declaration and parents.
446 InvalidationInfo Info;
447 containsInvalidationMethod(InterfaceD, Info, /*LookForPartial*/ false);
448
449 // Report an error in case none of the invalidation methods are declared.
450 if (!Info.needsInvalidation() && !PartialInfo.needsInvalidation()) {
451 if (Filter.check_MissingInvalidationMethod)
452 reportNoInvalidationMethod(Filter.checkName_MissingInvalidationMethod,
453 FirstIvarDecl, IvarToPopertyMap, InterfaceD,
454 /*MissingDeclaration*/ true);
455 // If there are no invalidation methods, there is no ivar validation work
456 // to be done.
457 return;
458 }
459
460 // Only check if Ivars are invalidated when InstanceVariableInvalidation
461 // has been requested.
462 if (!Filter.check_InstanceVariableInvalidation)
463 return;
464
465 // Check that all ivars are invalidated by the invalidation methods.
466 bool AtImplementationContainsAtLeastOneInvalidationMethod = false;
467 for (const ObjCMethodDecl *InterfD : Info.InvalidationMethods) {
468 // Get the corresponding method in the @implementation.
469 const ObjCMethodDecl *D = ImplD->getMethod(InterfD->getSelector(),
470 InterfD->isInstanceMethod());
471 if (Stmt *Body; D && (Body = D->getBody())) {
472 AtImplementationContainsAtLeastOneInvalidationMethod = true;
473
474 // Get a copy of ivars needing invalidation.
475 IvarSet IvarsI = Ivars;
476
477 bool CalledAnotherInvalidationMethod = false;
478 MethodCrawler(IvarsI,
479 CalledAnotherInvalidationMethod,
480 PropSetterToIvarMap,
481 PropGetterToIvarMap,
482 PropertyToIvarMap,
483 BR.getContext()).VisitStmt(Body);
484 // If another invalidation method was called, trust that full invalidation
485 // has occurred.
486 if (CalledAnotherInvalidationMethod)
487 continue;
488
489 // Warn on the ivars that were not invalidated by the method.
490 for (const ObjCIvarDecl *Ivar : llvm::make_first_range(IvarsI))
491 reportIvarNeedsInvalidation(Ivar, IvarToPopertyMap, D);
492 }
493 }
494
495 // Report an error in case none of the invalidation methods are implemented.
496 if (!AtImplementationContainsAtLeastOneInvalidationMethod) {
497 if (AtImplementationContainsAtLeastOnePartialInvalidationMethod) {
498 // Warn on the ivars that were not invalidated by the prrtial
499 // invalidation methods.
500 for (const ObjCIvarDecl *Ivar : llvm::make_first_range(Ivars))
501 reportIvarNeedsInvalidation(Ivar, IvarToPopertyMap, nullptr);
502 } else {
503 // Otherwise, no invalidation methods were implemented.
504 reportNoInvalidationMethod(Filter.checkName_InstanceVariableInvalidation,
505 FirstIvarDecl, IvarToPopertyMap, InterfaceD,
506 /*MissingDeclaration*/ false);
507 }
508 }
509}
510
511void IvarInvalidationCheckerImpl::reportNoInvalidationMethod(
512 CheckerNameRef CheckName, const ObjCIvarDecl *FirstIvarDecl,
513 const IvarToPropMapTy &IvarToPopertyMap,
514 const ObjCInterfaceDecl *InterfaceD, bool MissingDeclaration) const {
515 SmallString<128> sbuf;
516 llvm::raw_svector_ostream os(sbuf);
517 assert(FirstIvarDecl);
518 printIvar(os, FirstIvarDecl, IvarToPopertyMap);
519 os << "needs to be invalidated; ";
520 if (MissingDeclaration)
521 os << "no invalidation method is declared for ";
522 else
523 os << "no invalidation method is defined in the @implementation for ";
524 os << InterfaceD->getName();
525
526 PathDiagnosticLocation IvarDecLocation =
528
529 BR.EmitBasicReport(FirstIvarDecl, CheckName, "Incomplete invalidation",
531 IvarDecLocation);
532}
533
534void IvarInvalidationCheckerImpl::
535reportIvarNeedsInvalidation(const ObjCIvarDecl *IvarD,
536 const IvarToPropMapTy &IvarToPopertyMap,
537 const ObjCMethodDecl *MethodD) const {
538 SmallString<128> sbuf;
539 llvm::raw_svector_ostream os(sbuf);
540 printIvar(os, IvarD, IvarToPopertyMap);
541 os << "needs to be invalidated or set to nil";
542 if (MethodD) {
543 PathDiagnosticLocation MethodDecLocation =
545 BR.getSourceManager(),
546 Mgr.getAnalysisDeclContext(MethodD));
547 BR.EmitBasicReport(MethodD, Filter.checkName_InstanceVariableInvalidation,
548 "Incomplete invalidation",
550 MethodDecLocation);
551 } else {
553 IvarD, Filter.checkName_InstanceVariableInvalidation,
554 "Incomplete invalidation", categories::CoreFoundationObjectiveC,
555 os.str(),
557 }
558}
559
560void IvarInvalidationCheckerImpl::MethodCrawler::markInvalidated(
561 const ObjCIvarDecl *Iv) {
562 IvarSet::iterator I = IVars.find(Iv);
563 if (I != IVars.end()) {
564 // If InvalidationMethod is present, we are processing the message send and
565 // should ensure we are invalidating with the appropriate method,
566 // otherwise, we are processing setting to 'nil'.
567 if (!InvalidationMethod || I->second.hasMethod(InvalidationMethod))
568 IVars.erase(I);
569 }
570}
571
572const Expr *IvarInvalidationCheckerImpl::MethodCrawler::peel(const Expr *E) const {
573 E = E->IgnoreParenCasts();
574 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
575 E = POE->getSyntacticForm()->IgnoreParenCasts();
576 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
577 E = OVE->getSourceExpr()->IgnoreParenCasts();
578 return E;
579}
580
581void IvarInvalidationCheckerImpl::MethodCrawler::checkObjCIvarRefExpr(
582 const ObjCIvarRefExpr *IvarRef) {
583 if (const Decl *D = IvarRef->getDecl())
584 markInvalidated(cast<ObjCIvarDecl>(D->getCanonicalDecl()));
585}
586
587void IvarInvalidationCheckerImpl::MethodCrawler::checkObjCMessageExpr(
588 const ObjCMessageExpr *ME) {
589 const ObjCMethodDecl *MD = ME->getMethodDecl();
590 if (MD) {
591 MD = MD->getCanonicalDecl();
592 MethToIvarMapTy::const_iterator IvI = PropertyGetterToIvarMap.find(MD);
593 if (IvI != PropertyGetterToIvarMap.end())
594 markInvalidated(IvI->second);
595 }
596}
597
598void IvarInvalidationCheckerImpl::MethodCrawler::checkObjCPropertyRefExpr(
599 const ObjCPropertyRefExpr *PA) {
600
601 if (PA->isExplicitProperty()) {
602 const ObjCPropertyDecl *PD = PA->getExplicitProperty();
603 if (PD) {
605 PropToIvarMapTy::const_iterator IvI = PropertyToIvarMap.find(PD);
606 if (IvI != PropertyToIvarMap.end())
607 markInvalidated(IvI->second);
608 return;
609 }
610 }
611
612 if (PA->isImplicitProperty()) {
613 const ObjCMethodDecl *MD = PA->getImplicitPropertySetter();
614 if (MD) {
615 MD = MD->getCanonicalDecl();
616 MethToIvarMapTy::const_iterator IvI =PropertyGetterToIvarMap.find(MD);
617 if (IvI != PropertyGetterToIvarMap.end())
618 markInvalidated(IvI->second);
619 return;
620 }
621 }
622}
623
624bool IvarInvalidationCheckerImpl::MethodCrawler::isZero(const Expr *E) const {
625 E = peel(E);
626
629}
630
631void IvarInvalidationCheckerImpl::MethodCrawler::check(const Expr *E) {
632 E = peel(E);
633
634 if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
635 checkObjCIvarRefExpr(IvarRef);
636 return;
637 }
638
639 if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E)) {
640 checkObjCPropertyRefExpr(PropRef);
641 return;
642 }
643
644 if (const ObjCMessageExpr *MsgExpr = dyn_cast<ObjCMessageExpr>(E)) {
645 checkObjCMessageExpr(MsgExpr);
646 return;
647 }
648}
649
650void IvarInvalidationCheckerImpl::MethodCrawler::VisitBinaryOperator(
651 const BinaryOperator *BO) {
652 VisitStmt(BO);
653
654 // Do we assign/compare against zero? If yes, check the variable we are
655 // assigning to.
657 if (Opcode != BO_Assign &&
658 Opcode != BO_EQ &&
659 Opcode != BO_NE)
660 return;
661
662 if (isZero(BO->getRHS())) {
663 check(BO->getLHS());
664 return;
665 }
666
667 if (Opcode != BO_Assign && isZero(BO->getLHS())) {
668 check(BO->getRHS());
669 return;
670 }
671}
672
673void IvarInvalidationCheckerImpl::MethodCrawler::VisitObjCMessageExpr(
674 const ObjCMessageExpr *ME) {
675 const ObjCMethodDecl *MD = ME->getMethodDecl();
676 const Expr *Receiver = ME->getInstanceReceiver();
677
678 // Stop if we are calling '[self invalidate]'.
679 if (Receiver && isInvalidationMethod(MD, /*LookForPartial*/ false))
680 if (Receiver->isObjCSelfExpr()) {
681 CalledAnotherInvalidationMethod = true;
682 return;
683 }
684
685 // Check if we call a setter and set the property to 'nil'.
686 if (MD && (ME->getNumArgs() == 1) && isZero(ME->getArg(0))) {
687 MD = MD->getCanonicalDecl();
688 MethToIvarMapTy::const_iterator IvI = PropertySetterToIvarMap.find(MD);
689 if (IvI != PropertySetterToIvarMap.end()) {
690 markInvalidated(IvI->second);
691 return;
692 }
693 }
694
695 // Check if we call the 'invalidation' routine on the ivar.
696 if (Receiver) {
697 InvalidationMethod = MD;
698 check(Receiver->IgnoreParenCasts());
699 InvalidationMethod = nullptr;
700 }
701
702 VisitStmt(ME);
703}
704} // end anonymous namespace
705
706// Register the checkers.
707namespace {
708class IvarInvalidationChecker :
709 public Checker<check::ASTDecl<ObjCImplementationDecl> > {
710public:
711 ChecksFilter Filter;
712public:
713 void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
714 BugReporter &BR) const {
715 IvarInvalidationCheckerImpl Walker(Mgr, BR, Filter);
716 Walker.visit(D);
717 }
718};
719} // end anonymous namespace
720
721void ento::registerIvarInvalidationModeling(CheckerManager &mgr) {
722 mgr.registerChecker<IvarInvalidationChecker>();
723}
724
725bool ento::shouldRegisterIvarInvalidationModeling(const CheckerManager &mgr) {
726 return true;
727}
728
729#define REGISTER_CHECKER(name) \
730 void ento::register##name(CheckerManager &mgr) { \
731 IvarInvalidationChecker *checker = \
732 mgr.getChecker<IvarInvalidationChecker>(); \
733 checker->Filter.check_##name = true; \
734 checker->Filter.checkName_##name = mgr.getCurrentCheckerName(); \
735 } \
736 \
737 bool ento::shouldRegister##name(const CheckerManager &mgr) { return true; }
738
739REGISTER_CHECKER(InstanceVariableInvalidation)
740REGISTER_CHECKER(MissingInvalidationMethod)
741
742#undef REGISTER_CHECKER
#define REGISTER_CHECKER(name)
Expr * getLHS() const
Definition Expr.h:4157
Expr * getRHS() const
Definition Expr.h:4159
Opcode getOpcode() const
Definition Expr.h:4152
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:569
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:997
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3135
bool isObjCSelfExpr() const
Check if this expression is the ObjC 'self' implicit parameter.
Definition Expr.cpp:4254
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:880
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:849
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4111
StringRef getName() const
Return the actual identifier string.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
ObjCContainerDecl - Represents a container for method declarations.
Definition DeclObjC.h:954
ObjCMethodDecl * getMethod(Selector Sel, bool isInstance, bool AllowHidden=false) const
Definition DeclObjC.cpp:90
method_range methods() const
Definition DeclObjC.h:1022
const ObjCInterfaceDecl * getClassInterface() const
Definition DeclObjC.h:2492
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
void collectPropertiesToImplement(PropertyMap &PM) const override
This routine collects list of properties to be implemented in the class.
Definition DeclObjC.cpp:411
bool getSynthesize() const
Definition DeclObjC.h:2013
ObjCInterfaceDecl * getContainingInterface()
Return the class interface that this ivar is logically contained in; this is either the interface whe...
ObjCIvarDecl * getNextIvar()
Definition DeclObjC.h:1993
ObjCIvarDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this field.
Definition DeclObjC.h:1997
ObjCIvarDecl * getDecl()
Definition ExprObjC.h:611
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition ExprObjC.h:1435
Expr * getInstanceReceiver()
Returns the object expression (receiver) for an instance message, or null for a message that is not a...
Definition ExprObjC.h:1300
const ObjCMethodDecl * getMethodDecl() const
Definition ExprObjC.h:1396
unsigned getNumArgs() const
Return the number of actual arguments in this message, not counting the receiver.
Definition ExprObjC.h:1422
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Stmt * getBody() const override
Retrieve the body of this method, if it has one.
Definition DeclObjC.cpp:936
ObjCMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Selector getSelector() const
Definition DeclObjC.h:330
bool isInstanceMethod() const
Definition DeclObjC.h:429
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8373
bool isClassProperty() const
Definition DeclObjC.h:861
ObjCMethodDecl * getGetterMethodDecl() const
Definition DeclObjC.h:907
ObjCMethodDecl * getSetterMethodDecl() const
Definition DeclObjC.h:910
ObjCIvarDecl * getPropertyIvarDecl() const
Definition DeclObjC.h:930
ObjCPropertyDecl * getExplicitProperty() const
Definition ExprObjC.h:738
bool isExplicitProperty() const
Definition ExprObjC.h:736
bool isImplicitProperty() const
Definition ExprObjC.h:735
ObjCMethodDecl * getImplicitPropertySetter() const
Definition ExprObjC.h:748
child_range children()
Definition Stmt.cpp:304
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1844
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9537
QualType getType() const
Definition Decl.h:725
AnalysisDeclContext * getAnalysisDeclContext(const Decl *D)
const SourceManager & getSourceManager()
ASTContext & getContext()
void EmitBasicReport(const Decl *DeclWithIssue, const CheckerFrontend *Checker, StringRef BugName, StringRef BugCategory, StringRef BugStr, PathDiagnosticLocation Loc, ArrayRef< SourceRange > Ranges={}, ArrayRef< FixItHint > Fixits={})
CHECKER * registerChecker(AT &&...Args)
Register a single-part checker (derived from Checker): construct its singleton instance,...
static PathDiagnosticLocation createEnd(const Stmt *S, const SourceManager &SM, const StackFrameOrAnalysisDeclContext SFAC)
Create a location for the end of the statement.
static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM)
Create a location for the beginning of the declaration.
bool isInvalidationMethod(const CXXMethodDecl &MD)
const char *const CoreFoundationObjectiveC
llvm::cl::opt< std::string > Filter
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
U cast(CodeGen::Address addr)
Definition Address.h:327
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30