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 (const auto *Ext : InterfD->visible_extensions())
266       containsInvalidationMethod(Ext, OutInfo, Partial);
267 
268     containsInvalidationMethod(InterfD->getSuperClass(), OutInfo, Partial);
269     return;
270   }
271 
272   // If protocol, check all parent protocols.
273   if (const ObjCProtocolDecl *ProtD = dyn_cast<ObjCProtocolDecl>(D)) {
274     for (ObjCProtocolDecl::protocol_iterator I = ProtD->protocol_begin(),
275                                              E = ProtD->protocol_end();
276          I != E; ++I) {
277       containsInvalidationMethod((*I)->getDefinition(), OutInfo, Partial);
278     }
279     return;
280   }
281 
282   return;
283 }
284 
285 bool IvarInvalidationCheckerImpl::trackIvar(const ObjCIvarDecl *Iv,
286                                         IvarSet &TrackedIvars,
287                                         const ObjCIvarDecl **FirstIvarDecl) {
288   QualType IvQTy = Iv->getType();
289   const ObjCObjectPointerType *IvTy = IvQTy->getAs<ObjCObjectPointerType>();
290   if (!IvTy)
291     return false;
292   const ObjCInterfaceDecl *IvInterf = IvTy->getInterfaceDecl();
293 
294   InvalidationInfo Info;
295   containsInvalidationMethod(IvInterf, Info, /*LookForPartial*/ false);
296   if (Info.needsInvalidation()) {
297     const ObjCIvarDecl *I = cast<ObjCIvarDecl>(Iv->getCanonicalDecl());
298     TrackedIvars[I] = Info;
299     if (!*FirstIvarDecl)
300       *FirstIvarDecl = I;
301     return true;
302   }
303   return false;
304 }
305 
306 const ObjCIvarDecl *IvarInvalidationCheckerImpl::findPropertyBackingIvar(
307                         const ObjCPropertyDecl *Prop,
308                         const ObjCInterfaceDecl *InterfaceD,
309                         IvarSet &TrackedIvars,
310                         const ObjCIvarDecl **FirstIvarDecl) {
311   const ObjCIvarDecl *IvarD = 0;
312 
313   // Lookup for the synthesized case.
314   IvarD = Prop->getPropertyIvarDecl();
315   // We only track the ivars/properties that are defined in the current
316   // class (not the parent).
317   if (IvarD && IvarD->getContainingInterface() == InterfaceD) {
318     if (TrackedIvars.count(IvarD)) {
319       return IvarD;
320     }
321     // If the ivar is synthesized we still want to track it.
322     if (trackIvar(IvarD, TrackedIvars, FirstIvarDecl))
323       return IvarD;
324   }
325 
326   // Lookup IVars named "_PropName"or "PropName" among the tracked Ivars.
327   StringRef PropName = Prop->getIdentifier()->getName();
328   for (IvarSet::const_iterator I = TrackedIvars.begin(),
329                                E = TrackedIvars.end(); I != E; ++I) {
330     const ObjCIvarDecl *Iv = I->first;
331     StringRef IvarName = Iv->getName();
332 
333     if (IvarName == PropName)
334       return Iv;
335 
336     SmallString<128> PropNameWithUnderscore;
337     {
338       llvm::raw_svector_ostream os(PropNameWithUnderscore);
339       os << '_' << PropName;
340     }
341     if (IvarName == PropNameWithUnderscore.str())
342       return Iv;
343   }
344 
345   // Note, this is a possible source of false positives. We could look at the
346   // getter implementation to find the ivar when its name is not derived from
347   // the property name.
348   return 0;
349 }
350 
351 void IvarInvalidationCheckerImpl::printIvar(llvm::raw_svector_ostream &os,
352                                       const ObjCIvarDecl *IvarDecl,
353                                       const IvarToPropMapTy &IvarToPopertyMap) {
354   if (IvarDecl->getSynthesize()) {
355     const ObjCPropertyDecl *PD = IvarToPopertyMap.lookup(IvarDecl);
356     assert(PD &&"Do we synthesize ivars for something other than properties?");
357     os << "Property "<< PD->getName() << " ";
358   } else {
359     os << "Instance variable "<< IvarDecl->getName() << " ";
360   }
361 }
362 
363 // Check that the invalidatable interfaces with ivars/properties implement the
364 // invalidation methods.
365 void IvarInvalidationCheckerImpl::
366 visit(const ObjCImplementationDecl *ImplD) const {
367   // Collect all ivars that need cleanup.
368   IvarSet Ivars;
369   // Record the first Ivar needing invalidation; used in reporting when only
370   // one ivar is sufficient. Cannot grab the first on the Ivars set to ensure
371   // deterministic output.
372   const ObjCIvarDecl *FirstIvarDecl = 0;
373   const ObjCInterfaceDecl *InterfaceD = ImplD->getClassInterface();
374 
375   // Collect ivars declared in this class, its extensions and its implementation
376   ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(InterfaceD);
377   for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
378        Iv= Iv->getNextIvar())
379     trackIvar(Iv, Ivars, &FirstIvarDecl);
380 
381   // Construct Property/Property Accessor to Ivar maps to assist checking if an
382   // ivar which is backing a property has been reset.
383   MethToIvarMapTy PropSetterToIvarMap;
384   MethToIvarMapTy PropGetterToIvarMap;
385   PropToIvarMapTy PropertyToIvarMap;
386   IvarToPropMapTy IvarToPopertyMap;
387 
388   ObjCInterfaceDecl::PropertyMap PropMap;
389   ObjCInterfaceDecl::PropertyDeclOrder PropOrder;
390   InterfaceD->collectPropertiesToImplement(PropMap, PropOrder);
391 
392   for (ObjCInterfaceDecl::PropertyMap::iterator
393       I = PropMap.begin(), E = PropMap.end(); I != E; ++I) {
394     const ObjCPropertyDecl *PD = I->second;
395 
396     const ObjCIvarDecl *ID = findPropertyBackingIvar(PD, InterfaceD, Ivars,
397                                                      &FirstIvarDecl);
398     if (!ID)
399       continue;
400 
401     // Store the mappings.
402     PD = cast<ObjCPropertyDecl>(PD->getCanonicalDecl());
403     PropertyToIvarMap[PD] = ID;
404     IvarToPopertyMap[ID] = PD;
405 
406     // Find the setter and the getter.
407     const ObjCMethodDecl *SetterD = PD->getSetterMethodDecl();
408     if (SetterD) {
409       SetterD = cast<ObjCMethodDecl>(SetterD->getCanonicalDecl());
410       PropSetterToIvarMap[SetterD] = ID;
411     }
412 
413     const ObjCMethodDecl *GetterD = PD->getGetterMethodDecl();
414     if (GetterD) {
415       GetterD = cast<ObjCMethodDecl>(GetterD->getCanonicalDecl());
416       PropGetterToIvarMap[GetterD] = ID;
417     }
418   }
419 
420   // If no ivars need invalidation, there is nothing to check here.
421   if (Ivars.empty())
422     return;
423 
424   // Find all partial invalidation methods.
425   InvalidationInfo PartialInfo;
426   containsInvalidationMethod(InterfaceD, PartialInfo, /*LookForPartial*/ true);
427 
428   // Remove ivars invalidated by the partial invalidation methods. They do not
429   // need to be invalidated in the regular invalidation methods.
430   bool AtImplementationContainsAtLeastOnePartialInvalidationMethod = false;
431   for (MethodSet::iterator
432       I = PartialInfo.InvalidationMethods.begin(),
433       E = PartialInfo.InvalidationMethods.end(); I != E; ++I) {
434     const ObjCMethodDecl *InterfD = *I;
435 
436     // Get the corresponding method in the @implementation.
437     const ObjCMethodDecl *D = ImplD->getMethod(InterfD->getSelector(),
438                                                InterfD->isInstanceMethod());
439     if (D && D->hasBody()) {
440       AtImplementationContainsAtLeastOnePartialInvalidationMethod = true;
441 
442       bool CalledAnotherInvalidationMethod = false;
443       // The MethodCrowler is going to remove the invalidated ivars.
444       MethodCrawler(Ivars,
445                     CalledAnotherInvalidationMethod,
446                     PropSetterToIvarMap,
447                     PropGetterToIvarMap,
448                     PropertyToIvarMap,
449                     BR.getContext()).VisitStmt(D->getBody());
450       // If another invalidation method was called, trust that full invalidation
451       // has occurred.
452       if (CalledAnotherInvalidationMethod)
453         Ivars.clear();
454     }
455   }
456 
457   // If all ivars have been invalidated by partial invalidators, there is
458   // nothing to check here.
459   if (Ivars.empty())
460     return;
461 
462   // Find all invalidation methods in this @interface declaration and parents.
463   InvalidationInfo Info;
464   containsInvalidationMethod(InterfaceD, Info, /*LookForPartial*/ false);
465 
466   // Report an error in case none of the invalidation methods are declared.
467   if (!Info.needsInvalidation() && !PartialInfo.needsInvalidation()) {
468     if (Filter.check_MissingInvalidationMethod)
469       reportNoInvalidationMethod(Filter.checkName_MissingInvalidationMethod,
470                                  FirstIvarDecl, IvarToPopertyMap, InterfaceD,
471                                  /*MissingDeclaration*/ true);
472     // If there are no invalidation methods, there is no ivar validation work
473     // to be done.
474     return;
475   }
476 
477   // Only check if Ivars are invalidated when InstanceVariableInvalidation
478   // has been requested.
479   if (!Filter.check_InstanceVariableInvalidation)
480     return;
481 
482   // Check that all ivars are invalidated by the invalidation methods.
483   bool AtImplementationContainsAtLeastOneInvalidationMethod = false;
484   for (MethodSet::iterator I = Info.InvalidationMethods.begin(),
485                            E = Info.InvalidationMethods.end(); I != E; ++I) {
486     const ObjCMethodDecl *InterfD = *I;
487 
488     // Get the corresponding method in the @implementation.
489     const ObjCMethodDecl *D = ImplD->getMethod(InterfD->getSelector(),
490                                                InterfD->isInstanceMethod());
491     if (D && D->hasBody()) {
492       AtImplementationContainsAtLeastOneInvalidationMethod = true;
493 
494       // Get a copy of ivars needing invalidation.
495       IvarSet IvarsI = Ivars;
496 
497       bool CalledAnotherInvalidationMethod = false;
498       MethodCrawler(IvarsI,
499                     CalledAnotherInvalidationMethod,
500                     PropSetterToIvarMap,
501                     PropGetterToIvarMap,
502                     PropertyToIvarMap,
503                     BR.getContext()).VisitStmt(D->getBody());
504       // If another invalidation method was called, trust that full invalidation
505       // has occurred.
506       if (CalledAnotherInvalidationMethod)
507         continue;
508 
509       // Warn on the ivars that were not invalidated by the method.
510       for (IvarSet::const_iterator
511           I = IvarsI.begin(), E = IvarsI.end(); I != E; ++I)
512         reportIvarNeedsInvalidation(I->first, IvarToPopertyMap, D);
513     }
514   }
515 
516   // Report an error in case none of the invalidation methods are implemented.
517   if (!AtImplementationContainsAtLeastOneInvalidationMethod) {
518     if (AtImplementationContainsAtLeastOnePartialInvalidationMethod) {
519       // Warn on the ivars that were not invalidated by the prrtial
520       // invalidation methods.
521       for (IvarSet::const_iterator
522            I = Ivars.begin(), E = Ivars.end(); I != E; ++I)
523         reportIvarNeedsInvalidation(I->first, IvarToPopertyMap, 0);
524     } else {
525       // Otherwise, no invalidation methods were implemented.
526       reportNoInvalidationMethod(Filter.checkName_InstanceVariableInvalidation,
527                                  FirstIvarDecl, IvarToPopertyMap, InterfaceD,
528                                  /*MissingDeclaration*/ false);
529     }
530   }
531 }
532 
533 void IvarInvalidationCheckerImpl::reportNoInvalidationMethod(
534     CheckName CheckName, const ObjCIvarDecl *FirstIvarDecl,
535     const IvarToPropMapTy &IvarToPopertyMap,
536     const ObjCInterfaceDecl *InterfaceD, bool MissingDeclaration) const {
537   SmallString<128> sbuf;
538   llvm::raw_svector_ostream os(sbuf);
539   assert(FirstIvarDecl);
540   printIvar(os, FirstIvarDecl, IvarToPopertyMap);
541   os << "needs to be invalidated; ";
542   if (MissingDeclaration)
543     os << "no invalidation method is declared for ";
544   else
545     os << "no invalidation method is defined in the @implementation for ";
546   os << InterfaceD->getName();
547 
548   PathDiagnosticLocation IvarDecLocation =
549     PathDiagnosticLocation::createBegin(FirstIvarDecl, BR.getSourceManager());
550 
551   BR.EmitBasicReport(FirstIvarDecl, CheckName, "Incomplete invalidation",
552                      categories::CoreFoundationObjectiveC, os.str(),
553                      IvarDecLocation);
554 }
555 
556 void IvarInvalidationCheckerImpl::
557 reportIvarNeedsInvalidation(const ObjCIvarDecl *IvarD,
558                             const IvarToPropMapTy &IvarToPopertyMap,
559                             const ObjCMethodDecl *MethodD) const {
560   SmallString<128> sbuf;
561   llvm::raw_svector_ostream os(sbuf);
562   printIvar(os, IvarD, IvarToPopertyMap);
563   os << "needs to be invalidated or set to nil";
564   if (MethodD) {
565     PathDiagnosticLocation MethodDecLocation =
566                            PathDiagnosticLocation::createEnd(MethodD->getBody(),
567                            BR.getSourceManager(),
568                            Mgr.getAnalysisDeclContext(MethodD));
569     BR.EmitBasicReport(MethodD, Filter.checkName_InstanceVariableInvalidation,
570                        "Incomplete invalidation",
571                        categories::CoreFoundationObjectiveC, os.str(),
572                        MethodDecLocation);
573   } else {
574     BR.EmitBasicReport(
575         IvarD, Filter.checkName_InstanceVariableInvalidation,
576         "Incomplete invalidation", categories::CoreFoundationObjectiveC,
577         os.str(),
578         PathDiagnosticLocation::createBegin(IvarD, BR.getSourceManager()));
579   }
580 }
581 
582 void IvarInvalidationCheckerImpl::MethodCrawler::markInvalidated(
583     const ObjCIvarDecl *Iv) {
584   IvarSet::iterator I = IVars.find(Iv);
585   if (I != IVars.end()) {
586     // If InvalidationMethod is present, we are processing the message send and
587     // should ensure we are invalidating with the appropriate method,
588     // otherwise, we are processing setting to 'nil'.
589     if (!InvalidationMethod ||
590         (InvalidationMethod && I->second.hasMethod(InvalidationMethod)))
591       IVars.erase(I);
592   }
593 }
594 
595 const Expr *IvarInvalidationCheckerImpl::MethodCrawler::peel(const Expr *E) const {
596   E = E->IgnoreParenCasts();
597   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
598     E = POE->getSyntacticForm()->IgnoreParenCasts();
599   if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
600     E = OVE->getSourceExpr()->IgnoreParenCasts();
601   return E;
602 }
603 
604 void IvarInvalidationCheckerImpl::MethodCrawler::checkObjCIvarRefExpr(
605     const ObjCIvarRefExpr *IvarRef) {
606   if (const Decl *D = IvarRef->getDecl())
607     markInvalidated(cast<ObjCIvarDecl>(D->getCanonicalDecl()));
608 }
609 
610 void IvarInvalidationCheckerImpl::MethodCrawler::checkObjCMessageExpr(
611     const ObjCMessageExpr *ME) {
612   const ObjCMethodDecl *MD = ME->getMethodDecl();
613   if (MD) {
614     MD = cast<ObjCMethodDecl>(MD->getCanonicalDecl());
615     MethToIvarMapTy::const_iterator IvI = PropertyGetterToIvarMap.find(MD);
616     if (IvI != PropertyGetterToIvarMap.end())
617       markInvalidated(IvI->second);
618   }
619 }
620 
621 void IvarInvalidationCheckerImpl::MethodCrawler::checkObjCPropertyRefExpr(
622     const ObjCPropertyRefExpr *PA) {
623 
624   if (PA->isExplicitProperty()) {
625     const ObjCPropertyDecl *PD = PA->getExplicitProperty();
626     if (PD) {
627       PD = cast<ObjCPropertyDecl>(PD->getCanonicalDecl());
628       PropToIvarMapTy::const_iterator IvI = PropertyToIvarMap.find(PD);
629       if (IvI != PropertyToIvarMap.end())
630         markInvalidated(IvI->second);
631       return;
632     }
633   }
634 
635   if (PA->isImplicitProperty()) {
636     const ObjCMethodDecl *MD = PA->getImplicitPropertySetter();
637     if (MD) {
638       MD = cast<ObjCMethodDecl>(MD->getCanonicalDecl());
639       MethToIvarMapTy::const_iterator IvI =PropertyGetterToIvarMap.find(MD);
640       if (IvI != PropertyGetterToIvarMap.end())
641         markInvalidated(IvI->second);
642       return;
643     }
644   }
645 }
646 
647 bool IvarInvalidationCheckerImpl::MethodCrawler::isZero(const Expr *E) const {
648   E = peel(E);
649 
650   return (E->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull)
651            != Expr::NPCK_NotNull);
652 }
653 
654 void IvarInvalidationCheckerImpl::MethodCrawler::check(const Expr *E) {
655   E = peel(E);
656 
657   if (const ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
658     checkObjCIvarRefExpr(IvarRef);
659     return;
660   }
661 
662   if (const ObjCPropertyRefExpr *PropRef = dyn_cast<ObjCPropertyRefExpr>(E)) {
663     checkObjCPropertyRefExpr(PropRef);
664     return;
665   }
666 
667   if (const ObjCMessageExpr *MsgExpr = dyn_cast<ObjCMessageExpr>(E)) {
668     checkObjCMessageExpr(MsgExpr);
669     return;
670   }
671 }
672 
673 void IvarInvalidationCheckerImpl::MethodCrawler::VisitBinaryOperator(
674     const BinaryOperator *BO) {
675   VisitStmt(BO);
676 
677   // Do we assign/compare against zero? If yes, check the variable we are
678   // assigning to.
679   BinaryOperatorKind Opcode = BO->getOpcode();
680   if (Opcode != BO_Assign &&
681       Opcode != BO_EQ &&
682       Opcode != BO_NE)
683     return;
684 
685   if (isZero(BO->getRHS())) {
686       check(BO->getLHS());
687       return;
688   }
689 
690   if (Opcode != BO_Assign && isZero(BO->getLHS())) {
691     check(BO->getRHS());
692     return;
693   }
694 }
695 
696 void IvarInvalidationCheckerImpl::MethodCrawler::VisitObjCMessageExpr(
697   const ObjCMessageExpr *ME) {
698   const ObjCMethodDecl *MD = ME->getMethodDecl();
699   const Expr *Receiver = ME->getInstanceReceiver();
700 
701   // Stop if we are calling '[self invalidate]'.
702   if (Receiver && isInvalidationMethod(MD, /*LookForPartial*/ false))
703     if (Receiver->isObjCSelfExpr()) {
704       CalledAnotherInvalidationMethod = true;
705       return;
706     }
707 
708   // Check if we call a setter and set the property to 'nil'.
709   if (MD && (ME->getNumArgs() == 1) && isZero(ME->getArg(0))) {
710     MD = cast<ObjCMethodDecl>(MD->getCanonicalDecl());
711     MethToIvarMapTy::const_iterator IvI = PropertySetterToIvarMap.find(MD);
712     if (IvI != PropertySetterToIvarMap.end()) {
713       markInvalidated(IvI->second);
714       return;
715     }
716   }
717 
718   // Check if we call the 'invalidation' routine on the ivar.
719   if (Receiver) {
720     InvalidationMethod = MD;
721     check(Receiver->IgnoreParenCasts());
722     InvalidationMethod = 0;
723   }
724 
725   VisitStmt(ME);
726 }
727 }
728 
729 // Register the checkers.
730 namespace {
731 
732 class IvarInvalidationChecker :
733   public Checker<check::ASTDecl<ObjCImplementationDecl> > {
734 public:
735   ChecksFilter Filter;
736 public:
737   void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& Mgr,
738                     BugReporter &BR) const {
739     IvarInvalidationCheckerImpl Walker(Mgr, BR, Filter);
740     Walker.visit(D);
741   }
742 };
743 }
744 
745 #define REGISTER_CHECKER(name)                                                 \
746   void ento::register##name(CheckerManager &mgr) {                             \
747     IvarInvalidationChecker *checker =                                         \
748         mgr.registerChecker<IvarInvalidationChecker>();                        \
749     checker->Filter.check_##name = true;                                       \
750     checker->Filter.checkName_##name = mgr.getCurrentCheckName();              \
751   }
752 
753 REGISTER_CHECKER(InstanceVariableInvalidation)
754 REGISTER_CHECKER(MissingInvalidationMethod)
755 
756