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