RetainCountChecker.cpp revision 166d502d5367ceacd1313a33cac43b1048b8524d
1//==-- RetainCountChecker.cpp - Checks for leaks and other issues -*- 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 file defines the methods for RetainCountChecker, which implements
11//  a reference count checker for Core Foundation and Cocoa on (Mac OS X).
12//
13//===----------------------------------------------------------------------===//
14
15#include "ClangSACheckers.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/Basic/LangOptions.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
21#include "clang/AST/ParentMap.h"
22#include "clang/StaticAnalyzer/Core/Checker.h"
23#include "clang/StaticAnalyzer/Core/CheckerManager.h"
24#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
25#include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
26#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
27#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
28#include "clang/StaticAnalyzer/Core/PathSensitive/ProgramStateTrait.h"
29#include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
30#include "llvm/ADT/DenseMap.h"
31#include "llvm/ADT/FoldingSet.h"
32#include "llvm/ADT/ImmutableList.h"
33#include "llvm/ADT/ImmutableMap.h"
34#include "llvm/ADT/SmallString.h"
35#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/StringExtras.h"
37#include <cstdarg>
38
39using namespace clang;
40using namespace ento;
41using llvm::StrInStrNoCase;
42
43//===----------------------------------------------------------------------===//
44// Primitives used for constructing summaries for function/method calls.
45//===----------------------------------------------------------------------===//
46
47/// ArgEffect is used to summarize a function/method call's effect on a
48/// particular argument.
49enum ArgEffect { DoNothing, Autorelease, Dealloc, DecRef, DecRefMsg,
50                 DecRefBridgedTransfered,
51                 IncRefMsg, IncRef, MakeCollectable, MayEscape,
52                 NewAutoreleasePool,
53
54                 // Stop tracking the argument - the effect of the call is
55                 // unknown.
56                 StopTracking,
57
58                 // In some cases, we obtain a better summary for this checker
59                 // by looking at the call site than by inlining the function.
60                 // Signifies that we should stop tracking the symbol even if
61                 // the function is inlined.
62                 StopTrackingHard,
63
64                 // The function decrements the reference count and the checker
65                 // should stop tracking the argument.
66                 DecRefAndStopTrackingHard, DecRefMsgAndStopTrackingHard
67               };
68
69namespace llvm {
70template <> struct FoldingSetTrait<ArgEffect> {
71static inline void Profile(const ArgEffect X, FoldingSetNodeID& ID) {
72  ID.AddInteger((unsigned) X);
73}
74};
75} // end llvm namespace
76
77/// ArgEffects summarizes the effects of a function/method call on all of
78/// its arguments.
79typedef llvm::ImmutableMap<unsigned,ArgEffect> ArgEffects;
80
81namespace {
82
83///  RetEffect is used to summarize a function/method call's behavior with
84///  respect to its return value.
85class RetEffect {
86public:
87  enum Kind { NoRet, OwnedSymbol, OwnedAllocatedSymbol,
88              NotOwnedSymbol, GCNotOwnedSymbol, ARCNotOwnedSymbol,
89              OwnedWhenTrackedReceiver,
90              // Treat this function as returning a non-tracked symbol even if
91              // the function has been inlined. This is used where the call
92              // site summary is more presise than the summary indirectly produced
93              // by inlining the function
94              NoRetHard
95            };
96
97  enum ObjKind { CF, ObjC, AnyObj };
98
99private:
100  Kind K;
101  ObjKind O;
102
103  RetEffect(Kind k, ObjKind o = AnyObj) : K(k), O(o) {}
104
105public:
106  Kind getKind() const { return K; }
107
108  ObjKind getObjKind() const { return O; }
109
110  bool isOwned() const {
111    return K == OwnedSymbol || K == OwnedAllocatedSymbol ||
112           K == OwnedWhenTrackedReceiver;
113  }
114
115  bool operator==(const RetEffect &Other) const {
116    return K == Other.K && O == Other.O;
117  }
118
119  static RetEffect MakeOwnedWhenTrackedReceiver() {
120    return RetEffect(OwnedWhenTrackedReceiver, ObjC);
121  }
122
123  static RetEffect MakeOwned(ObjKind o, bool isAllocated = false) {
124    return RetEffect(isAllocated ? OwnedAllocatedSymbol : OwnedSymbol, o);
125  }
126  static RetEffect MakeNotOwned(ObjKind o) {
127    return RetEffect(NotOwnedSymbol, o);
128  }
129  static RetEffect MakeGCNotOwned() {
130    return RetEffect(GCNotOwnedSymbol, ObjC);
131  }
132  static RetEffect MakeARCNotOwned() {
133    return RetEffect(ARCNotOwnedSymbol, ObjC);
134  }
135  static RetEffect MakeNoRet() {
136    return RetEffect(NoRet);
137  }
138  static RetEffect MakeNoRetHard() {
139    return RetEffect(NoRetHard);
140  }
141
142  void Profile(llvm::FoldingSetNodeID& ID) const {
143    ID.AddInteger((unsigned) K);
144    ID.AddInteger((unsigned) O);
145  }
146};
147
148//===----------------------------------------------------------------------===//
149// Reference-counting logic (typestate + counts).
150//===----------------------------------------------------------------------===//
151
152class RefVal {
153public:
154  enum Kind {
155    Owned = 0, // Owning reference.
156    NotOwned,  // Reference is not owned by still valid (not freed).
157    Released,  // Object has been released.
158    ReturnedOwned, // Returned object passes ownership to caller.
159    ReturnedNotOwned, // Return object does not pass ownership to caller.
160    ERROR_START,
161    ErrorDeallocNotOwned, // -dealloc called on non-owned object.
162    ErrorDeallocGC, // Calling -dealloc with GC enabled.
163    ErrorUseAfterRelease, // Object used after released.
164    ErrorReleaseNotOwned, // Release of an object that was not owned.
165    ERROR_LEAK_START,
166    ErrorLeak,  // A memory leak due to excessive reference counts.
167    ErrorLeakReturned, // A memory leak due to the returning method not having
168                       // the correct naming conventions.
169    ErrorGCLeakReturned,
170    ErrorOverAutorelease,
171    ErrorReturnedNotOwned
172  };
173
174private:
175  Kind kind;
176  RetEffect::ObjKind okind;
177  unsigned Cnt;
178  unsigned ACnt;
179  QualType T;
180
181  RefVal(Kind k, RetEffect::ObjKind o, unsigned cnt, unsigned acnt, QualType t)
182  : kind(k), okind(o), Cnt(cnt), ACnt(acnt), T(t) {}
183
184public:
185  Kind getKind() const { return kind; }
186
187  RetEffect::ObjKind getObjKind() const { return okind; }
188
189  unsigned getCount() const { return Cnt; }
190  unsigned getAutoreleaseCount() const { return ACnt; }
191  unsigned getCombinedCounts() const { return Cnt + ACnt; }
192  void clearCounts() { Cnt = 0; ACnt = 0; }
193  void setCount(unsigned i) { Cnt = i; }
194  void setAutoreleaseCount(unsigned i) { ACnt = i; }
195
196  QualType getType() const { return T; }
197
198  bool isOwned() const {
199    return getKind() == Owned;
200  }
201
202  bool isNotOwned() const {
203    return getKind() == NotOwned;
204  }
205
206  bool isReturnedOwned() const {
207    return getKind() == ReturnedOwned;
208  }
209
210  bool isReturnedNotOwned() const {
211    return getKind() == ReturnedNotOwned;
212  }
213
214  static RefVal makeOwned(RetEffect::ObjKind o, QualType t,
215                          unsigned Count = 1) {
216    return RefVal(Owned, o, Count, 0, t);
217  }
218
219  static RefVal makeNotOwned(RetEffect::ObjKind o, QualType t,
220                             unsigned Count = 0) {
221    return RefVal(NotOwned, o, Count, 0, t);
222  }
223
224  // Comparison, profiling, and pretty-printing.
225
226  bool operator==(const RefVal& X) const {
227    return kind == X.kind && Cnt == X.Cnt && T == X.T && ACnt == X.ACnt;
228  }
229
230  RefVal operator-(size_t i) const {
231    return RefVal(getKind(), getObjKind(), getCount() - i,
232                  getAutoreleaseCount(), getType());
233  }
234
235  RefVal operator+(size_t i) const {
236    return RefVal(getKind(), getObjKind(), getCount() + i,
237                  getAutoreleaseCount(), getType());
238  }
239
240  RefVal operator^(Kind k) const {
241    return RefVal(k, getObjKind(), getCount(), getAutoreleaseCount(),
242                  getType());
243  }
244
245  RefVal autorelease() const {
246    return RefVal(getKind(), getObjKind(), getCount(), getAutoreleaseCount()+1,
247                  getType());
248  }
249
250  void Profile(llvm::FoldingSetNodeID& ID) const {
251    ID.AddInteger((unsigned) kind);
252    ID.AddInteger(Cnt);
253    ID.AddInteger(ACnt);
254    ID.Add(T);
255  }
256
257  void print(raw_ostream &Out) const;
258};
259
260void RefVal::print(raw_ostream &Out) const {
261  if (!T.isNull())
262    Out << "Tracked " << T.getAsString() << '/';
263
264  switch (getKind()) {
265    default: llvm_unreachable("Invalid RefVal kind");
266    case Owned: {
267      Out << "Owned";
268      unsigned cnt = getCount();
269      if (cnt) Out << " (+ " << cnt << ")";
270      break;
271    }
272
273    case NotOwned: {
274      Out << "NotOwned";
275      unsigned cnt = getCount();
276      if (cnt) Out << " (+ " << cnt << ")";
277      break;
278    }
279
280    case ReturnedOwned: {
281      Out << "ReturnedOwned";
282      unsigned cnt = getCount();
283      if (cnt) Out << " (+ " << cnt << ")";
284      break;
285    }
286
287    case ReturnedNotOwned: {
288      Out << "ReturnedNotOwned";
289      unsigned cnt = getCount();
290      if (cnt) Out << " (+ " << cnt << ")";
291      break;
292    }
293
294    case Released:
295      Out << "Released";
296      break;
297
298    case ErrorDeallocGC:
299      Out << "-dealloc (GC)";
300      break;
301
302    case ErrorDeallocNotOwned:
303      Out << "-dealloc (not-owned)";
304      break;
305
306    case ErrorLeak:
307      Out << "Leaked";
308      break;
309
310    case ErrorLeakReturned:
311      Out << "Leaked (Bad naming)";
312      break;
313
314    case ErrorGCLeakReturned:
315      Out << "Leaked (GC-ed at return)";
316      break;
317
318    case ErrorUseAfterRelease:
319      Out << "Use-After-Release [ERROR]";
320      break;
321
322    case ErrorReleaseNotOwned:
323      Out << "Release of Not-Owned [ERROR]";
324      break;
325
326    case RefVal::ErrorOverAutorelease:
327      Out << "Over autoreleased";
328      break;
329
330    case RefVal::ErrorReturnedNotOwned:
331      Out << "Non-owned object returned instead of owned";
332      break;
333  }
334
335  if (ACnt) {
336    Out << " [ARC +" << ACnt << ']';
337  }
338}
339} //end anonymous namespace
340
341//===----------------------------------------------------------------------===//
342// RefBindings - State used to track object reference counts.
343//===----------------------------------------------------------------------===//
344
345REGISTER_MAP_WITH_PROGRAMSTATE(RefBindings, SymbolRef, RefVal)
346
347static inline const RefVal *getRefBinding(ProgramStateRef State,
348                                          SymbolRef Sym) {
349  return State->get<RefBindings>(Sym);
350}
351
352static inline ProgramStateRef setRefBinding(ProgramStateRef State,
353                                            SymbolRef Sym, RefVal Val) {
354  return State->set<RefBindings>(Sym, Val);
355}
356
357static ProgramStateRef removeRefBinding(ProgramStateRef State, SymbolRef Sym) {
358  return State->remove<RefBindings>(Sym);
359}
360
361//===----------------------------------------------------------------------===//
362// Function/Method behavior summaries.
363//===----------------------------------------------------------------------===//
364
365namespace {
366class RetainSummary {
367  /// Args - a map of (index, ArgEffect) pairs, where index
368  ///  specifies the argument (starting from 0).  This can be sparsely
369  ///  populated; arguments with no entry in Args use 'DefaultArgEffect'.
370  ArgEffects Args;
371
372  /// DefaultArgEffect - The default ArgEffect to apply to arguments that
373  ///  do not have an entry in Args.
374  ArgEffect DefaultArgEffect;
375
376  /// Receiver - If this summary applies to an Objective-C message expression,
377  ///  this is the effect applied to the state of the receiver.
378  ArgEffect Receiver;
379
380  /// Ret - The effect on the return value.  Used to indicate if the
381  ///  function/method call returns a new tracked symbol.
382  RetEffect Ret;
383
384public:
385  RetainSummary(ArgEffects A, RetEffect R, ArgEffect defaultEff,
386                ArgEffect ReceiverEff)
387    : Args(A), DefaultArgEffect(defaultEff), Receiver(ReceiverEff), Ret(R) {}
388
389  /// getArg - Return the argument effect on the argument specified by
390  ///  idx (starting from 0).
391  ArgEffect getArg(unsigned idx) const {
392    if (const ArgEffect *AE = Args.lookup(idx))
393      return *AE;
394
395    return DefaultArgEffect;
396  }
397
398  void addArg(ArgEffects::Factory &af, unsigned idx, ArgEffect e) {
399    Args = af.add(Args, idx, e);
400  }
401
402  /// setDefaultArgEffect - Set the default argument effect.
403  void setDefaultArgEffect(ArgEffect E) {
404    DefaultArgEffect = E;
405  }
406
407  /// getRetEffect - Returns the effect on the return value of the call.
408  RetEffect getRetEffect() const { return Ret; }
409
410  /// setRetEffect - Set the effect of the return value of the call.
411  void setRetEffect(RetEffect E) { Ret = E; }
412
413
414  /// Sets the effect on the receiver of the message.
415  void setReceiverEffect(ArgEffect e) { Receiver = e; }
416
417  /// getReceiverEffect - Returns the effect on the receiver of the call.
418  ///  This is only meaningful if the summary applies to an ObjCMessageExpr*.
419  ArgEffect getReceiverEffect() const { return Receiver; }
420
421  /// Test if two retain summaries are identical. Note that merely equivalent
422  /// summaries are not necessarily identical (for example, if an explicit
423  /// argument effect matches the default effect).
424  bool operator==(const RetainSummary &Other) const {
425    return Args == Other.Args && DefaultArgEffect == Other.DefaultArgEffect &&
426           Receiver == Other.Receiver && Ret == Other.Ret;
427  }
428
429  /// Profile this summary for inclusion in a FoldingSet.
430  void Profile(llvm::FoldingSetNodeID& ID) const {
431    ID.Add(Args);
432    ID.Add(DefaultArgEffect);
433    ID.Add(Receiver);
434    ID.Add(Ret);
435  }
436
437  /// A retain summary is simple if it has no ArgEffects other than the default.
438  bool isSimple() const {
439    return Args.isEmpty();
440  }
441
442private:
443  ArgEffects getArgEffects() const { return Args; }
444  ArgEffect getDefaultArgEffect() const { return DefaultArgEffect; }
445
446  friend class RetainSummaryManager;
447};
448} // end anonymous namespace
449
450//===----------------------------------------------------------------------===//
451// Data structures for constructing summaries.
452//===----------------------------------------------------------------------===//
453
454namespace {
455class ObjCSummaryKey {
456  IdentifierInfo* II;
457  Selector S;
458public:
459  ObjCSummaryKey(IdentifierInfo* ii, Selector s)
460    : II(ii), S(s) {}
461
462  ObjCSummaryKey(const ObjCInterfaceDecl *d, Selector s)
463    : II(d ? d->getIdentifier() : 0), S(s) {}
464
465  ObjCSummaryKey(Selector s)
466    : II(0), S(s) {}
467
468  IdentifierInfo *getIdentifier() const { return II; }
469  Selector getSelector() const { return S; }
470};
471}
472
473namespace llvm {
474template <> struct DenseMapInfo<ObjCSummaryKey> {
475  static inline ObjCSummaryKey getEmptyKey() {
476    return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getEmptyKey(),
477                          DenseMapInfo<Selector>::getEmptyKey());
478  }
479
480  static inline ObjCSummaryKey getTombstoneKey() {
481    return ObjCSummaryKey(DenseMapInfo<IdentifierInfo*>::getTombstoneKey(),
482                          DenseMapInfo<Selector>::getTombstoneKey());
483  }
484
485  static unsigned getHashValue(const ObjCSummaryKey &V) {
486    typedef std::pair<IdentifierInfo*, Selector> PairTy;
487    return DenseMapInfo<PairTy>::getHashValue(PairTy(V.getIdentifier(),
488                                                     V.getSelector()));
489  }
490
491  static bool isEqual(const ObjCSummaryKey& LHS, const ObjCSummaryKey& RHS) {
492    return LHS.getIdentifier() == RHS.getIdentifier() &&
493           LHS.getSelector() == RHS.getSelector();
494  }
495
496};
497template <>
498struct isPodLike<ObjCSummaryKey> { static const bool value = true; };
499} // end llvm namespace
500
501namespace {
502class ObjCSummaryCache {
503  typedef llvm::DenseMap<ObjCSummaryKey, const RetainSummary *> MapTy;
504  MapTy M;
505public:
506  ObjCSummaryCache() {}
507
508  const RetainSummary * find(const ObjCInterfaceDecl *D, Selector S) {
509    // Do a lookup with the (D,S) pair.  If we find a match return
510    // the iterator.
511    ObjCSummaryKey K(D, S);
512    MapTy::iterator I = M.find(K);
513
514    if (I != M.end())
515      return I->second;
516    if (!D)
517      return NULL;
518
519    // Walk the super chain.  If we find a hit with a parent, we'll end
520    // up returning that summary.  We actually allow that key (null,S), as
521    // we cache summaries for the null ObjCInterfaceDecl* to allow us to
522    // generate initial summaries without having to worry about NSObject
523    // being declared.
524    // FIXME: We may change this at some point.
525    for (ObjCInterfaceDecl *C=D->getSuperClass() ;; C=C->getSuperClass()) {
526      if ((I = M.find(ObjCSummaryKey(C, S))) != M.end())
527        break;
528
529      if (!C)
530        return NULL;
531    }
532
533    // Cache the summary with original key to make the next lookup faster
534    // and return the iterator.
535    const RetainSummary *Summ = I->second;
536    M[K] = Summ;
537    return Summ;
538  }
539
540  const RetainSummary *find(IdentifierInfo* II, Selector S) {
541    // FIXME: Class method lookup.  Right now we dont' have a good way
542    // of going between IdentifierInfo* and the class hierarchy.
543    MapTy::iterator I = M.find(ObjCSummaryKey(II, S));
544
545    if (I == M.end())
546      I = M.find(ObjCSummaryKey(S));
547
548    return I == M.end() ? NULL : I->second;
549  }
550
551  const RetainSummary *& operator[](ObjCSummaryKey K) {
552    return M[K];
553  }
554
555  const RetainSummary *& operator[](Selector S) {
556    return M[ ObjCSummaryKey(S) ];
557  }
558};
559} // end anonymous namespace
560
561//===----------------------------------------------------------------------===//
562// Data structures for managing collections of summaries.
563//===----------------------------------------------------------------------===//
564
565namespace {
566class RetainSummaryManager {
567
568  //==-----------------------------------------------------------------==//
569  //  Typedefs.
570  //==-----------------------------------------------------------------==//
571
572  typedef llvm::DenseMap<const FunctionDecl*, const RetainSummary *>
573          FuncSummariesTy;
574
575  typedef ObjCSummaryCache ObjCMethodSummariesTy;
576
577  typedef llvm::FoldingSetNodeWrapper<RetainSummary> CachedSummaryNode;
578
579  //==-----------------------------------------------------------------==//
580  //  Data.
581  //==-----------------------------------------------------------------==//
582
583  /// Ctx - The ASTContext object for the analyzed ASTs.
584  ASTContext &Ctx;
585
586  /// GCEnabled - Records whether or not the analyzed code runs in GC mode.
587  const bool GCEnabled;
588
589  /// Records whether or not the analyzed code runs in ARC mode.
590  const bool ARCEnabled;
591
592  /// FuncSummaries - A map from FunctionDecls to summaries.
593  FuncSummariesTy FuncSummaries;
594
595  /// ObjCClassMethodSummaries - A map from selectors (for instance methods)
596  ///  to summaries.
597  ObjCMethodSummariesTy ObjCClassMethodSummaries;
598
599  /// ObjCMethodSummaries - A map from selectors to summaries.
600  ObjCMethodSummariesTy ObjCMethodSummaries;
601
602  /// BPAlloc - A BumpPtrAllocator used for allocating summaries, ArgEffects,
603  ///  and all other data used by the checker.
604  llvm::BumpPtrAllocator BPAlloc;
605
606  /// AF - A factory for ArgEffects objects.
607  ArgEffects::Factory AF;
608
609  /// ScratchArgs - A holding buffer for construct ArgEffects.
610  ArgEffects ScratchArgs;
611
612  /// ObjCAllocRetE - Default return effect for methods returning Objective-C
613  ///  objects.
614  RetEffect ObjCAllocRetE;
615
616  /// ObjCInitRetE - Default return effect for init methods returning
617  ///   Objective-C objects.
618  RetEffect ObjCInitRetE;
619
620  /// SimpleSummaries - Used for uniquing summaries that don't have special
621  /// effects.
622  llvm::FoldingSet<CachedSummaryNode> SimpleSummaries;
623
624  //==-----------------------------------------------------------------==//
625  //  Methods.
626  //==-----------------------------------------------------------------==//
627
628  /// getArgEffects - Returns a persistent ArgEffects object based on the
629  ///  data in ScratchArgs.
630  ArgEffects getArgEffects();
631
632  enum UnaryFuncKind { cfretain, cfrelease, cfmakecollectable };
633
634  const RetainSummary *getUnarySummary(const FunctionType* FT,
635                                       UnaryFuncKind func);
636
637  const RetainSummary *getCFSummaryCreateRule(const FunctionDecl *FD);
638  const RetainSummary *getCFSummaryGetRule(const FunctionDecl *FD);
639  const RetainSummary *getCFCreateGetRuleSummary(const FunctionDecl *FD);
640
641  const RetainSummary *getPersistentSummary(const RetainSummary &OldSumm);
642
643  const RetainSummary *getPersistentSummary(RetEffect RetEff,
644                                            ArgEffect ReceiverEff = DoNothing,
645                                            ArgEffect DefaultEff = MayEscape) {
646    RetainSummary Summ(getArgEffects(), RetEff, DefaultEff, ReceiverEff);
647    return getPersistentSummary(Summ);
648  }
649
650  const RetainSummary *getDoNothingSummary() {
651    return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
652  }
653
654  const RetainSummary *getDefaultSummary() {
655    return getPersistentSummary(RetEffect::MakeNoRet(),
656                                DoNothing, MayEscape);
657  }
658
659  const RetainSummary *getPersistentStopSummary() {
660    return getPersistentSummary(RetEffect::MakeNoRet(),
661                                StopTracking, StopTracking);
662  }
663
664  void InitializeClassMethodSummaries();
665  void InitializeMethodSummaries();
666private:
667  void addNSObjectClsMethSummary(Selector S, const RetainSummary *Summ) {
668    ObjCClassMethodSummaries[S] = Summ;
669  }
670
671  void addNSObjectMethSummary(Selector S, const RetainSummary *Summ) {
672    ObjCMethodSummaries[S] = Summ;
673  }
674
675  void addClassMethSummary(const char* Cls, const char* name,
676                           const RetainSummary *Summ, bool isNullary = true) {
677    IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
678    Selector S = isNullary ? GetNullarySelector(name, Ctx)
679                           : GetUnarySelector(name, Ctx);
680    ObjCClassMethodSummaries[ObjCSummaryKey(ClsII, S)]  = Summ;
681  }
682
683  void addInstMethSummary(const char* Cls, const char* nullaryName,
684                          const RetainSummary *Summ) {
685    IdentifierInfo* ClsII = &Ctx.Idents.get(Cls);
686    Selector S = GetNullarySelector(nullaryName, Ctx);
687    ObjCMethodSummaries[ObjCSummaryKey(ClsII, S)]  = Summ;
688  }
689
690  Selector generateSelector(va_list argp) {
691    SmallVector<IdentifierInfo*, 10> II;
692
693    while (const char* s = va_arg(argp, const char*))
694      II.push_back(&Ctx.Idents.get(s));
695
696    return Ctx.Selectors.getSelector(II.size(), &II[0]);
697  }
698
699  void addMethodSummary(IdentifierInfo *ClsII, ObjCMethodSummariesTy& Summaries,
700                        const RetainSummary * Summ, va_list argp) {
701    Selector S = generateSelector(argp);
702    Summaries[ObjCSummaryKey(ClsII, S)] = Summ;
703  }
704
705  void addInstMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
706    va_list argp;
707    va_start(argp, Summ);
708    addMethodSummary(&Ctx.Idents.get(Cls), ObjCMethodSummaries, Summ, argp);
709    va_end(argp);
710  }
711
712  void addClsMethSummary(const char* Cls, const RetainSummary * Summ, ...) {
713    va_list argp;
714    va_start(argp, Summ);
715    addMethodSummary(&Ctx.Idents.get(Cls),ObjCClassMethodSummaries, Summ, argp);
716    va_end(argp);
717  }
718
719  void addClsMethSummary(IdentifierInfo *II, const RetainSummary * Summ, ...) {
720    va_list argp;
721    va_start(argp, Summ);
722    addMethodSummary(II, ObjCClassMethodSummaries, Summ, argp);
723    va_end(argp);
724  }
725
726public:
727
728  RetainSummaryManager(ASTContext &ctx, bool gcenabled, bool usesARC)
729   : Ctx(ctx),
730     GCEnabled(gcenabled),
731     ARCEnabled(usesARC),
732     AF(BPAlloc), ScratchArgs(AF.getEmptyMap()),
733     ObjCAllocRetE(gcenabled
734                    ? RetEffect::MakeGCNotOwned()
735                    : (usesARC ? RetEffect::MakeARCNotOwned()
736                               : RetEffect::MakeOwned(RetEffect::ObjC, true))),
737     ObjCInitRetE(gcenabled
738                    ? RetEffect::MakeGCNotOwned()
739                    : (usesARC ? RetEffect::MakeARCNotOwned()
740                               : RetEffect::MakeOwnedWhenTrackedReceiver())) {
741    InitializeClassMethodSummaries();
742    InitializeMethodSummaries();
743  }
744
745  const RetainSummary *getSummary(const CallEvent &Call,
746                                  ProgramStateRef State = 0);
747
748  const RetainSummary *getFunctionSummary(const FunctionDecl *FD);
749
750  const RetainSummary *getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
751                                        const ObjCMethodDecl *MD,
752                                        QualType RetTy,
753                                        ObjCMethodSummariesTy &CachedSummaries);
754
755  const RetainSummary *getInstanceMethodSummary(const ObjCMethodCall &M,
756                                                ProgramStateRef State);
757
758  const RetainSummary *getClassMethodSummary(const ObjCMethodCall &M) {
759    assert(!M.isInstanceMessage());
760    const ObjCInterfaceDecl *Class = M.getReceiverInterface();
761
762    return getMethodSummary(M.getSelector(), Class, M.getDecl(),
763                            M.getResultType(), ObjCClassMethodSummaries);
764  }
765
766  /// getMethodSummary - This version of getMethodSummary is used to query
767  ///  the summary for the current method being analyzed.
768  const RetainSummary *getMethodSummary(const ObjCMethodDecl *MD) {
769    const ObjCInterfaceDecl *ID = MD->getClassInterface();
770    Selector S = MD->getSelector();
771    QualType ResultTy = MD->getResultType();
772
773    ObjCMethodSummariesTy *CachedSummaries;
774    if (MD->isInstanceMethod())
775      CachedSummaries = &ObjCMethodSummaries;
776    else
777      CachedSummaries = &ObjCClassMethodSummaries;
778
779    return getMethodSummary(S, ID, MD, ResultTy, *CachedSummaries);
780  }
781
782  const RetainSummary *getStandardMethodSummary(const ObjCMethodDecl *MD,
783                                                Selector S, QualType RetTy);
784
785  void updateSummaryFromAnnotations(const RetainSummary *&Summ,
786                                    const ObjCMethodDecl *MD);
787
788  void updateSummaryFromAnnotations(const RetainSummary *&Summ,
789                                    const FunctionDecl *FD);
790
791  void updateSummaryForCall(const RetainSummary *&Summ,
792                            const CallEvent &Call);
793
794  bool isGCEnabled() const { return GCEnabled; }
795
796  bool isARCEnabled() const { return ARCEnabled; }
797
798  bool isARCorGCEnabled() const { return GCEnabled || ARCEnabled; }
799
800  RetEffect getObjAllocRetEffect() const { return ObjCAllocRetE; }
801
802  friend class RetainSummaryTemplate;
803};
804
805// Used to avoid allocating long-term (BPAlloc'd) memory for default retain
806// summaries. If a function or method looks like it has a default summary, but
807// it has annotations, the annotations are added to the stack-based template
808// and then copied into managed memory.
809class RetainSummaryTemplate {
810  RetainSummaryManager &Manager;
811  const RetainSummary *&RealSummary;
812  RetainSummary ScratchSummary;
813  bool Accessed;
814public:
815  RetainSummaryTemplate(const RetainSummary *&real, RetainSummaryManager &mgr)
816    : Manager(mgr), RealSummary(real), ScratchSummary(*real), Accessed(false) {}
817
818  ~RetainSummaryTemplate() {
819    if (Accessed)
820      RealSummary = Manager.getPersistentSummary(ScratchSummary);
821  }
822
823  RetainSummary &operator*() {
824    Accessed = true;
825    return ScratchSummary;
826  }
827
828  RetainSummary *operator->() {
829    Accessed = true;
830    return &ScratchSummary;
831  }
832};
833
834} // end anonymous namespace
835
836//===----------------------------------------------------------------------===//
837// Implementation of checker data structures.
838//===----------------------------------------------------------------------===//
839
840ArgEffects RetainSummaryManager::getArgEffects() {
841  ArgEffects AE = ScratchArgs;
842  ScratchArgs = AF.getEmptyMap();
843  return AE;
844}
845
846const RetainSummary *
847RetainSummaryManager::getPersistentSummary(const RetainSummary &OldSumm) {
848  // Unique "simple" summaries -- those without ArgEffects.
849  if (OldSumm.isSimple()) {
850    llvm::FoldingSetNodeID ID;
851    OldSumm.Profile(ID);
852
853    void *Pos;
854    CachedSummaryNode *N = SimpleSummaries.FindNodeOrInsertPos(ID, Pos);
855
856    if (!N) {
857      N = (CachedSummaryNode *) BPAlloc.Allocate<CachedSummaryNode>();
858      new (N) CachedSummaryNode(OldSumm);
859      SimpleSummaries.InsertNode(N, Pos);
860    }
861
862    return &N->getValue();
863  }
864
865  RetainSummary *Summ = (RetainSummary *) BPAlloc.Allocate<RetainSummary>();
866  new (Summ) RetainSummary(OldSumm);
867  return Summ;
868}
869
870//===----------------------------------------------------------------------===//
871// Summary creation for functions (largely uses of Core Foundation).
872//===----------------------------------------------------------------------===//
873
874static bool isRetain(const FunctionDecl *FD, StringRef FName) {
875  return FName.endswith("Retain");
876}
877
878static bool isRelease(const FunctionDecl *FD, StringRef FName) {
879  return FName.endswith("Release");
880}
881
882static bool isMakeCollectable(const FunctionDecl *FD, StringRef FName) {
883  // FIXME: Remove FunctionDecl parameter.
884  // FIXME: Is it really okay if MakeCollectable isn't a suffix?
885  return FName.find("MakeCollectable") != StringRef::npos;
886}
887
888static ArgEffect getStopTrackingHardEquivalent(ArgEffect E) {
889  switch (E) {
890  case DoNothing:
891  case Autorelease:
892  case DecRefBridgedTransfered:
893  case IncRef:
894  case IncRefMsg:
895  case MakeCollectable:
896  case MayEscape:
897  case NewAutoreleasePool:
898  case StopTracking:
899  case StopTrackingHard:
900    return StopTrackingHard;
901  case DecRef:
902  case DecRefAndStopTrackingHard:
903    return DecRefAndStopTrackingHard;
904  case DecRefMsg:
905  case DecRefMsgAndStopTrackingHard:
906    return DecRefMsgAndStopTrackingHard;
907  case Dealloc:
908    return Dealloc;
909  }
910
911  llvm_unreachable("Unknown ArgEffect kind");
912}
913
914void RetainSummaryManager::updateSummaryForCall(const RetainSummary *&S,
915                                                const CallEvent &Call) {
916  if (Call.hasNonZeroCallbackArg()) {
917    ArgEffect RecEffect =
918      getStopTrackingHardEquivalent(S->getReceiverEffect());
919    ArgEffect DefEffect =
920      getStopTrackingHardEquivalent(S->getDefaultArgEffect());
921
922    ArgEffects CustomArgEffects = S->getArgEffects();
923    for (ArgEffects::iterator I = CustomArgEffects.begin(),
924                              E = CustomArgEffects.end();
925         I != E; ++I) {
926      ArgEffect Translated = getStopTrackingHardEquivalent(I->second);
927      if (Translated != DefEffect)
928        ScratchArgs = AF.add(ScratchArgs, I->first, Translated);
929    }
930
931    RetEffect RE = RetEffect::MakeNoRetHard();
932
933    // Special cases where the callback argument CANNOT free the return value.
934    // This can generally only happen if we know that the callback will only be
935    // called when the return value is already being deallocated.
936    if (const FunctionCall *FC = dyn_cast<FunctionCall>(&Call)) {
937      if (IdentifierInfo *Name = FC->getDecl()->getIdentifier()) {
938        // When the CGBitmapContext is deallocated, the callback here will free
939        // the associated data buffer.
940        if (Name->isStr("CGBitmapContextCreateWithData"))
941          RE = S->getRetEffect();
942      }
943    }
944
945    S = getPersistentSummary(RE, RecEffect, DefEffect);
946  }
947
948  // Special case '[super init];' and '[self init];'
949  //
950  // Even though calling '[super init]' without assigning the result to self
951  // and checking if the parent returns 'nil' is a bad pattern, it is common.
952  // Additionally, our Self Init checker already warns about it. To avoid
953  // overwhelming the user with messages from both checkers, we model the case
954  // of '[super init]' in cases when it is not consumed by another expression
955  // as if the call preserves the value of 'self'; essentially, assuming it can
956  // never fail and return 'nil'.
957  // Note, we don't want to just stop tracking the value since we want the
958  // RetainCount checker to report leaks and use-after-free if SelfInit checker
959  // is turned off.
960  if (const ObjCMethodCall *MC = dyn_cast<ObjCMethodCall>(&Call)) {
961    if (MC->getMethodFamily() == OMF_init && MC->isReceiverSelfOrSuper()) {
962
963      // Check if the message is not consumed, we know it will not be used in
964      // an assignment, ex: "self = [super init]".
965      const Expr *ME = MC->getOriginExpr();
966      const LocationContext *LCtx = MC->getLocationContext();
967      ParentMap &PM = LCtx->getAnalysisDeclContext()->getParentMap();
968      if (!PM.isConsumedExpr(ME)) {
969        RetainSummaryTemplate ModifiableSummaryTemplate(S, *this);
970        ModifiableSummaryTemplate->setReceiverEffect(DoNothing);
971        ModifiableSummaryTemplate->setRetEffect(RetEffect::MakeNoRet());
972      }
973    }
974
975  }
976}
977
978const RetainSummary *
979RetainSummaryManager::getSummary(const CallEvent &Call,
980                                 ProgramStateRef State) {
981  const RetainSummary *Summ;
982  switch (Call.getKind()) {
983  case CE_Function:
984    Summ = getFunctionSummary(cast<FunctionCall>(Call).getDecl());
985    break;
986  case CE_CXXMember:
987  case CE_CXXMemberOperator:
988  case CE_Block:
989  case CE_CXXConstructor:
990  case CE_CXXDestructor:
991  case CE_CXXAllocator:
992    // FIXME: These calls are currently unsupported.
993    return getPersistentStopSummary();
994  case CE_ObjCMessage: {
995    const ObjCMethodCall &Msg = cast<ObjCMethodCall>(Call);
996    if (Msg.isInstanceMessage())
997      Summ = getInstanceMethodSummary(Msg, State);
998    else
999      Summ = getClassMethodSummary(Msg);
1000    break;
1001  }
1002  }
1003
1004  updateSummaryForCall(Summ, Call);
1005
1006  assert(Summ && "Unknown call type?");
1007  return Summ;
1008}
1009
1010const RetainSummary *
1011RetainSummaryManager::getFunctionSummary(const FunctionDecl *FD) {
1012  // If we don't know what function we're calling, use our default summary.
1013  if (!FD)
1014    return getDefaultSummary();
1015
1016  // Look up a summary in our cache of FunctionDecls -> Summaries.
1017  FuncSummariesTy::iterator I = FuncSummaries.find(FD);
1018  if (I != FuncSummaries.end())
1019    return I->second;
1020
1021  // No summary?  Generate one.
1022  const RetainSummary *S = 0;
1023  bool AllowAnnotations = true;
1024
1025  do {
1026    // We generate "stop" summaries for implicitly defined functions.
1027    if (FD->isImplicit()) {
1028      S = getPersistentStopSummary();
1029      break;
1030    }
1031
1032    // [PR 3337] Use 'getAs<FunctionType>' to strip away any typedefs on the
1033    // function's type.
1034    const FunctionType* FT = FD->getType()->getAs<FunctionType>();
1035    const IdentifierInfo *II = FD->getIdentifier();
1036    if (!II)
1037      break;
1038
1039    StringRef FName = II->getName();
1040
1041    // Strip away preceding '_'.  Doing this here will effect all the checks
1042    // down below.
1043    FName = FName.substr(FName.find_first_not_of('_'));
1044
1045    // Inspect the result type.
1046    QualType RetTy = FT->getResultType();
1047
1048    // FIXME: This should all be refactored into a chain of "summary lookup"
1049    //  filters.
1050    assert(ScratchArgs.isEmpty());
1051
1052    if (FName == "pthread_create" || FName == "pthread_setspecific") {
1053      // Part of: <rdar://problem/7299394> and <rdar://problem/11282706>.
1054      // This will be addressed better with IPA.
1055      S = getPersistentStopSummary();
1056    } else if (FName == "NSMakeCollectable") {
1057      // Handle: id NSMakeCollectable(CFTypeRef)
1058      S = (RetTy->isObjCIdType())
1059          ? getUnarySummary(FT, cfmakecollectable)
1060          : getPersistentStopSummary();
1061      // The headers on OS X 10.8 use cf_consumed/ns_returns_retained,
1062      // but we can fully model NSMakeCollectable ourselves.
1063      AllowAnnotations = false;
1064    } else if (FName == "CFPlugInInstanceCreate") {
1065      S = getPersistentSummary(RetEffect::MakeNoRet());
1066    } else if (FName == "IOBSDNameMatching" ||
1067               FName == "IOServiceMatching" ||
1068               FName == "IOServiceNameMatching" ||
1069               FName == "IORegistryEntrySearchCFProperty" ||
1070               FName == "IORegistryEntryIDMatching" ||
1071               FName == "IOOpenFirmwarePathMatching") {
1072      // Part of <rdar://problem/6961230>. (IOKit)
1073      // This should be addressed using a API table.
1074      S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1075                               DoNothing, DoNothing);
1076    } else if (FName == "IOServiceGetMatchingService" ||
1077               FName == "IOServiceGetMatchingServices") {
1078      // FIXES: <rdar://problem/6326900>
1079      // This should be addressed using a API table.  This strcmp is also
1080      // a little gross, but there is no need to super optimize here.
1081      ScratchArgs = AF.add(ScratchArgs, 1, DecRef);
1082      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1083    } else if (FName == "IOServiceAddNotification" ||
1084               FName == "IOServiceAddMatchingNotification") {
1085      // Part of <rdar://problem/6961230>. (IOKit)
1086      // This should be addressed using a API table.
1087      ScratchArgs = AF.add(ScratchArgs, 2, DecRef);
1088      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1089    } else if (FName == "CVPixelBufferCreateWithBytes") {
1090      // FIXES: <rdar://problem/7283567>
1091      // Eventually this can be improved by recognizing that the pixel
1092      // buffer passed to CVPixelBufferCreateWithBytes is released via
1093      // a callback and doing full IPA to make sure this is done correctly.
1094      // FIXME: This function has an out parameter that returns an
1095      // allocated object.
1096      ScratchArgs = AF.add(ScratchArgs, 7, StopTracking);
1097      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1098    } else if (FName == "CGBitmapContextCreateWithData") {
1099      // FIXES: <rdar://problem/7358899>
1100      // Eventually this can be improved by recognizing that 'releaseInfo'
1101      // passed to CGBitmapContextCreateWithData is released via
1102      // a callback and doing full IPA to make sure this is done correctly.
1103      ScratchArgs = AF.add(ScratchArgs, 8, StopTracking);
1104      S = getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true),
1105                               DoNothing, DoNothing);
1106    } else if (FName == "CVPixelBufferCreateWithPlanarBytes") {
1107      // FIXES: <rdar://problem/7283567>
1108      // Eventually this can be improved by recognizing that the pixel
1109      // buffer passed to CVPixelBufferCreateWithPlanarBytes is released
1110      // via a callback and doing full IPA to make sure this is done
1111      // correctly.
1112      ScratchArgs = AF.add(ScratchArgs, 12, StopTracking);
1113      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1114    } else if (FName == "dispatch_set_context") {
1115      // <rdar://problem/11059275> - The analyzer currently doesn't have
1116      // a good way to reason about the finalizer function for libdispatch.
1117      // If we pass a context object that is memory managed, stop tracking it.
1118      // FIXME: this hack should possibly go away once we can handle
1119      // libdispatch finalizers.
1120      ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1121      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1122    } else if (FName.startswith("NSLog")) {
1123      S = getDoNothingSummary();
1124    } else if (FName.startswith("NS") &&
1125                (FName.find("Insert") != StringRef::npos)) {
1126      // Whitelist NSXXInsertXX, for example NSMapInsertIfAbsent, since they can
1127      // be deallocated by NSMapRemove. (radar://11152419)
1128      ScratchArgs = AF.add(ScratchArgs, 1, StopTracking);
1129      ScratchArgs = AF.add(ScratchArgs, 2, StopTracking);
1130      S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1131    }
1132
1133    // Did we get a summary?
1134    if (S)
1135      break;
1136
1137    if (RetTy->isPointerType()) {
1138      if (FD->getAttr<CFAuditedTransferAttr>()) {
1139        S = getCFCreateGetRuleSummary(FD);
1140        break;
1141      }
1142
1143      // For CoreFoundation ('CF') types.
1144      if (cocoa::isRefType(RetTy, "CF", FName)) {
1145        if (isRetain(FD, FName))
1146          S = getUnarySummary(FT, cfretain);
1147        else if (isMakeCollectable(FD, FName))
1148          S = getUnarySummary(FT, cfmakecollectable);
1149        else
1150          S = getCFCreateGetRuleSummary(FD);
1151
1152        break;
1153      }
1154
1155      // For CoreGraphics ('CG') types.
1156      if (cocoa::isRefType(RetTy, "CG", FName)) {
1157        if (isRetain(FD, FName))
1158          S = getUnarySummary(FT, cfretain);
1159        else
1160          S = getCFCreateGetRuleSummary(FD);
1161
1162        break;
1163      }
1164
1165      // For the Disk Arbitration API (DiskArbitration/DADisk.h)
1166      if (cocoa::isRefType(RetTy, "DADisk") ||
1167          cocoa::isRefType(RetTy, "DADissenter") ||
1168          cocoa::isRefType(RetTy, "DASessionRef")) {
1169        S = getCFCreateGetRuleSummary(FD);
1170        break;
1171      }
1172
1173      break;
1174    }
1175
1176    // Check for release functions, the only kind of functions that we care
1177    // about that don't return a pointer type.
1178    if (FName[0] == 'C' && (FName[1] == 'F' || FName[1] == 'G')) {
1179      // Test for 'CGCF'.
1180      FName = FName.substr(FName.startswith("CGCF") ? 4 : 2);
1181
1182      if (isRelease(FD, FName))
1183        S = getUnarySummary(FT, cfrelease);
1184      else {
1185        assert (ScratchArgs.isEmpty());
1186        // Remaining CoreFoundation and CoreGraphics functions.
1187        // We use to assume that they all strictly followed the ownership idiom
1188        // and that ownership cannot be transferred.  While this is technically
1189        // correct, many methods allow a tracked object to escape.  For example:
1190        //
1191        //   CFMutableDictionaryRef x = CFDictionaryCreateMutable(...);
1192        //   CFDictionaryAddValue(y, key, x);
1193        //   CFRelease(x);
1194        //   ... it is okay to use 'x' since 'y' has a reference to it
1195        //
1196        // We handle this and similar cases with the follow heuristic.  If the
1197        // function name contains "InsertValue", "SetValue", "AddValue",
1198        // "AppendValue", or "SetAttribute", then we assume that arguments may
1199        // "escape."  This means that something else holds on to the object,
1200        // allowing it be used even after its local retain count drops to 0.
1201        ArgEffect E = (StrInStrNoCase(FName, "InsertValue") != StringRef::npos||
1202                       StrInStrNoCase(FName, "AddValue") != StringRef::npos ||
1203                       StrInStrNoCase(FName, "SetValue") != StringRef::npos ||
1204                       StrInStrNoCase(FName, "AppendValue") != StringRef::npos||
1205                       StrInStrNoCase(FName, "SetAttribute") != StringRef::npos)
1206                      ? MayEscape : DoNothing;
1207
1208        S = getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, E);
1209      }
1210    }
1211  }
1212  while (0);
1213
1214  // If we got all the way here without any luck, use a default summary.
1215  if (!S)
1216    S = getDefaultSummary();
1217
1218  // Annotations override defaults.
1219  if (AllowAnnotations)
1220    updateSummaryFromAnnotations(S, FD);
1221
1222  FuncSummaries[FD] = S;
1223  return S;
1224}
1225
1226const RetainSummary *
1227RetainSummaryManager::getCFCreateGetRuleSummary(const FunctionDecl *FD) {
1228  if (coreFoundation::followsCreateRule(FD))
1229    return getCFSummaryCreateRule(FD);
1230
1231  return getCFSummaryGetRule(FD);
1232}
1233
1234const RetainSummary *
1235RetainSummaryManager::getUnarySummary(const FunctionType* FT,
1236                                      UnaryFuncKind func) {
1237
1238  // Sanity check that this is *really* a unary function.  This can
1239  // happen if people do weird things.
1240  const FunctionProtoType* FTP = dyn_cast<FunctionProtoType>(FT);
1241  if (!FTP || FTP->getNumArgs() != 1)
1242    return getPersistentStopSummary();
1243
1244  assert (ScratchArgs.isEmpty());
1245
1246  ArgEffect Effect;
1247  switch (func) {
1248    case cfretain: Effect = IncRef; break;
1249    case cfrelease: Effect = DecRef; break;
1250    case cfmakecollectable: Effect = MakeCollectable; break;
1251  }
1252
1253  ScratchArgs = AF.add(ScratchArgs, 0, Effect);
1254  return getPersistentSummary(RetEffect::MakeNoRet(), DoNothing, DoNothing);
1255}
1256
1257const RetainSummary *
1258RetainSummaryManager::getCFSummaryCreateRule(const FunctionDecl *FD) {
1259  assert (ScratchArgs.isEmpty());
1260
1261  return getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
1262}
1263
1264const RetainSummary *
1265RetainSummaryManager::getCFSummaryGetRule(const FunctionDecl *FD) {
1266  assert (ScratchArgs.isEmpty());
1267  return getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::CF),
1268                              DoNothing, DoNothing);
1269}
1270
1271//===----------------------------------------------------------------------===//
1272// Summary creation for Selectors.
1273//===----------------------------------------------------------------------===//
1274
1275void
1276RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1277                                                   const FunctionDecl *FD) {
1278  if (!FD)
1279    return;
1280
1281  assert(Summ && "Must have a summary to add annotations to.");
1282  RetainSummaryTemplate Template(Summ, *this);
1283
1284  // Effects on the parameters.
1285  unsigned parm_idx = 0;
1286  for (FunctionDecl::param_const_iterator pi = FD->param_begin(),
1287         pe = FD->param_end(); pi != pe; ++pi, ++parm_idx) {
1288    const ParmVarDecl *pd = *pi;
1289    if (pd->getAttr<NSConsumedAttr>()) {
1290      if (!GCEnabled) {
1291        Template->addArg(AF, parm_idx, DecRef);
1292      }
1293    } else if (pd->getAttr<CFConsumedAttr>()) {
1294      Template->addArg(AF, parm_idx, DecRef);
1295    }
1296  }
1297
1298  QualType RetTy = FD->getResultType();
1299
1300  // Determine if there is a special return effect for this method.
1301  if (cocoa::isCocoaObjectRef(RetTy)) {
1302    if (FD->getAttr<NSReturnsRetainedAttr>()) {
1303      Template->setRetEffect(ObjCAllocRetE);
1304    }
1305    else if (FD->getAttr<CFReturnsRetainedAttr>()) {
1306      Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1307    }
1308    else if (FD->getAttr<NSReturnsNotRetainedAttr>()) {
1309      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
1310    }
1311    else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
1312      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
1313    }
1314  } else if (RetTy->getAs<PointerType>()) {
1315    if (FD->getAttr<CFReturnsRetainedAttr>()) {
1316      Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1317    }
1318    else if (FD->getAttr<CFReturnsNotRetainedAttr>()) {
1319      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
1320    }
1321  }
1322}
1323
1324void
1325RetainSummaryManager::updateSummaryFromAnnotations(const RetainSummary *&Summ,
1326                                                   const ObjCMethodDecl *MD) {
1327  if (!MD)
1328    return;
1329
1330  assert(Summ && "Must have a valid summary to add annotations to");
1331  RetainSummaryTemplate Template(Summ, *this);
1332  bool isTrackedLoc = false;
1333
1334  // Effects on the receiver.
1335  if (MD->getAttr<NSConsumesSelfAttr>()) {
1336    if (!GCEnabled)
1337      Template->setReceiverEffect(DecRefMsg);
1338  }
1339
1340  // Effects on the parameters.
1341  unsigned parm_idx = 0;
1342  for (ObjCMethodDecl::param_const_iterator
1343         pi=MD->param_begin(), pe=MD->param_end();
1344       pi != pe; ++pi, ++parm_idx) {
1345    const ParmVarDecl *pd = *pi;
1346    if (pd->getAttr<NSConsumedAttr>()) {
1347      if (!GCEnabled)
1348        Template->addArg(AF, parm_idx, DecRef);
1349    }
1350    else if(pd->getAttr<CFConsumedAttr>()) {
1351      Template->addArg(AF, parm_idx, DecRef);
1352    }
1353  }
1354
1355  // Determine if there is a special return effect for this method.
1356  if (cocoa::isCocoaObjectRef(MD->getResultType())) {
1357    if (MD->getAttr<NSReturnsRetainedAttr>()) {
1358      Template->setRetEffect(ObjCAllocRetE);
1359      return;
1360    }
1361    if (MD->getAttr<NSReturnsNotRetainedAttr>()) {
1362      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::ObjC));
1363      return;
1364    }
1365
1366    isTrackedLoc = true;
1367  } else {
1368    isTrackedLoc = MD->getResultType()->getAs<PointerType>() != NULL;
1369  }
1370
1371  if (isTrackedLoc) {
1372    if (MD->getAttr<CFReturnsRetainedAttr>())
1373      Template->setRetEffect(RetEffect::MakeOwned(RetEffect::CF, true));
1374    else if (MD->getAttr<CFReturnsNotRetainedAttr>())
1375      Template->setRetEffect(RetEffect::MakeNotOwned(RetEffect::CF));
1376  }
1377}
1378
1379const RetainSummary *
1380RetainSummaryManager::getStandardMethodSummary(const ObjCMethodDecl *MD,
1381                                               Selector S, QualType RetTy) {
1382  // Any special effects?
1383  ArgEffect ReceiverEff = DoNothing;
1384  RetEffect ResultEff = RetEffect::MakeNoRet();
1385
1386  // Check the method family, and apply any default annotations.
1387  switch (MD ? MD->getMethodFamily() : S.getMethodFamily()) {
1388    case OMF_None:
1389    case OMF_performSelector:
1390      // Assume all Objective-C methods follow Cocoa Memory Management rules.
1391      // FIXME: Does the non-threaded performSelector family really belong here?
1392      // The selector could be, say, @selector(copy).
1393      if (cocoa::isCocoaObjectRef(RetTy))
1394        ResultEff = RetEffect::MakeNotOwned(RetEffect::ObjC);
1395      else if (coreFoundation::isCFObjectRef(RetTy)) {
1396        // ObjCMethodDecl currently doesn't consider CF objects as valid return
1397        // values for alloc, new, copy, or mutableCopy, so we have to
1398        // double-check with the selector. This is ugly, but there aren't that
1399        // many Objective-C methods that return CF objects, right?
1400        if (MD) {
1401          switch (S.getMethodFamily()) {
1402          case OMF_alloc:
1403          case OMF_new:
1404          case OMF_copy:
1405          case OMF_mutableCopy:
1406            ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1407            break;
1408          default:
1409            ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1410            break;
1411          }
1412        } else {
1413          ResultEff = RetEffect::MakeNotOwned(RetEffect::CF);
1414        }
1415      }
1416      break;
1417    case OMF_init:
1418      ResultEff = ObjCInitRetE;
1419      ReceiverEff = DecRefMsg;
1420      break;
1421    case OMF_alloc:
1422    case OMF_new:
1423    case OMF_copy:
1424    case OMF_mutableCopy:
1425      if (cocoa::isCocoaObjectRef(RetTy))
1426        ResultEff = ObjCAllocRetE;
1427      else if (coreFoundation::isCFObjectRef(RetTy))
1428        ResultEff = RetEffect::MakeOwned(RetEffect::CF, true);
1429      break;
1430    case OMF_autorelease:
1431      ReceiverEff = Autorelease;
1432      break;
1433    case OMF_retain:
1434      ReceiverEff = IncRefMsg;
1435      break;
1436    case OMF_release:
1437      ReceiverEff = DecRefMsg;
1438      break;
1439    case OMF_dealloc:
1440      ReceiverEff = Dealloc;
1441      break;
1442    case OMF_self:
1443      // -self is handled specially by the ExprEngine to propagate the receiver.
1444      break;
1445    case OMF_retainCount:
1446    case OMF_finalize:
1447      // These methods don't return objects.
1448      break;
1449  }
1450
1451  // If one of the arguments in the selector has the keyword 'delegate' we
1452  // should stop tracking the reference count for the receiver.  This is
1453  // because the reference count is quite possibly handled by a delegate
1454  // method.
1455  if (S.isKeywordSelector()) {
1456    for (unsigned i = 0, e = S.getNumArgs(); i != e; ++i) {
1457      StringRef Slot = S.getNameForSlot(i);
1458      if (Slot.substr(Slot.size() - 8).equals_lower("delegate")) {
1459        if (ResultEff == ObjCInitRetE)
1460          ResultEff = RetEffect::MakeNoRetHard();
1461        else
1462          ReceiverEff = StopTrackingHard;
1463      }
1464    }
1465  }
1466
1467  if (ScratchArgs.isEmpty() && ReceiverEff == DoNothing &&
1468      ResultEff.getKind() == RetEffect::NoRet)
1469    return getDefaultSummary();
1470
1471  return getPersistentSummary(ResultEff, ReceiverEff, MayEscape);
1472}
1473
1474const RetainSummary *
1475RetainSummaryManager::getInstanceMethodSummary(const ObjCMethodCall &Msg,
1476                                               ProgramStateRef State) {
1477  const ObjCInterfaceDecl *ReceiverClass = 0;
1478
1479  // We do better tracking of the type of the object than the core ExprEngine.
1480  // See if we have its type in our private state.
1481  // FIXME: Eventually replace the use of state->get<RefBindings> with
1482  // a generic API for reasoning about the Objective-C types of symbolic
1483  // objects.
1484  SVal ReceiverV = Msg.getReceiverSVal();
1485  if (SymbolRef Sym = ReceiverV.getAsLocSymbol())
1486    if (const RefVal *T = getRefBinding(State, Sym))
1487      if (const ObjCObjectPointerType *PT =
1488            T->getType()->getAs<ObjCObjectPointerType>())
1489        ReceiverClass = PT->getInterfaceDecl();
1490
1491  // If we don't know what kind of object this is, fall back to its static type.
1492  if (!ReceiverClass)
1493    ReceiverClass = Msg.getReceiverInterface();
1494
1495  // FIXME: The receiver could be a reference to a class, meaning that
1496  //  we should use the class method.
1497  // id x = [NSObject class];
1498  // [x performSelector:... withObject:... afterDelay:...];
1499  Selector S = Msg.getSelector();
1500  const ObjCMethodDecl *Method = Msg.getDecl();
1501  if (!Method && ReceiverClass)
1502    Method = ReceiverClass->getInstanceMethod(S);
1503
1504  return getMethodSummary(S, ReceiverClass, Method, Msg.getResultType(),
1505                          ObjCMethodSummaries);
1506}
1507
1508const RetainSummary *
1509RetainSummaryManager::getMethodSummary(Selector S, const ObjCInterfaceDecl *ID,
1510                                       const ObjCMethodDecl *MD, QualType RetTy,
1511                                       ObjCMethodSummariesTy &CachedSummaries) {
1512
1513  // Look up a summary in our summary cache.
1514  const RetainSummary *Summ = CachedSummaries.find(ID, S);
1515
1516  if (!Summ) {
1517    Summ = getStandardMethodSummary(MD, S, RetTy);
1518
1519    // Annotations override defaults.
1520    updateSummaryFromAnnotations(Summ, MD);
1521
1522    // Memoize the summary.
1523    CachedSummaries[ObjCSummaryKey(ID, S)] = Summ;
1524  }
1525
1526  return Summ;
1527}
1528
1529void RetainSummaryManager::InitializeClassMethodSummaries() {
1530  assert(ScratchArgs.isEmpty());
1531  // Create the [NSAssertionHandler currentHander] summary.
1532  addClassMethSummary("NSAssertionHandler", "currentHandler",
1533                getPersistentSummary(RetEffect::MakeNotOwned(RetEffect::ObjC)));
1534
1535  // Create the [NSAutoreleasePool addObject:] summary.
1536  ScratchArgs = AF.add(ScratchArgs, 0, Autorelease);
1537  addClassMethSummary("NSAutoreleasePool", "addObject",
1538                      getPersistentSummary(RetEffect::MakeNoRet(),
1539                                           DoNothing, Autorelease));
1540}
1541
1542void RetainSummaryManager::InitializeMethodSummaries() {
1543
1544  assert (ScratchArgs.isEmpty());
1545
1546  // Create the "init" selector.  It just acts as a pass-through for the
1547  // receiver.
1548  const RetainSummary *InitSumm = getPersistentSummary(ObjCInitRetE, DecRefMsg);
1549  addNSObjectMethSummary(GetNullarySelector("init", Ctx), InitSumm);
1550
1551  // awakeAfterUsingCoder: behaves basically like an 'init' method.  It
1552  // claims the receiver and returns a retained object.
1553  addNSObjectMethSummary(GetUnarySelector("awakeAfterUsingCoder", Ctx),
1554                         InitSumm);
1555
1556  // The next methods are allocators.
1557  const RetainSummary *AllocSumm = getPersistentSummary(ObjCAllocRetE);
1558  const RetainSummary *CFAllocSumm =
1559    getPersistentSummary(RetEffect::MakeOwned(RetEffect::CF, true));
1560
1561  // Create the "retain" selector.
1562  RetEffect NoRet = RetEffect::MakeNoRet();
1563  const RetainSummary *Summ = getPersistentSummary(NoRet, IncRefMsg);
1564  addNSObjectMethSummary(GetNullarySelector("retain", Ctx), Summ);
1565
1566  // Create the "release" selector.
1567  Summ = getPersistentSummary(NoRet, DecRefMsg);
1568  addNSObjectMethSummary(GetNullarySelector("release", Ctx), Summ);
1569
1570  // Create the "drain" selector.
1571  Summ = getPersistentSummary(NoRet, isGCEnabled() ? DoNothing : DecRef);
1572  addNSObjectMethSummary(GetNullarySelector("drain", Ctx), Summ);
1573
1574  // Create the -dealloc summary.
1575  Summ = getPersistentSummary(NoRet, Dealloc);
1576  addNSObjectMethSummary(GetNullarySelector("dealloc", Ctx), Summ);
1577
1578  // Create the "autorelease" selector.
1579  Summ = getPersistentSummary(NoRet, Autorelease);
1580  addNSObjectMethSummary(GetNullarySelector("autorelease", Ctx), Summ);
1581
1582  // Specially handle NSAutoreleasePool.
1583  addInstMethSummary("NSAutoreleasePool", "init",
1584                     getPersistentSummary(NoRet, NewAutoreleasePool));
1585
1586  // For NSWindow, allocated objects are (initially) self-owned.
1587  // FIXME: For now we opt for false negatives with NSWindow, as these objects
1588  //  self-own themselves.  However, they only do this once they are displayed.
1589  //  Thus, we need to track an NSWindow's display status.
1590  //  This is tracked in <rdar://problem/6062711>.
1591  //  See also http://llvm.org/bugs/show_bug.cgi?id=3714.
1592  const RetainSummary *NoTrackYet = getPersistentSummary(RetEffect::MakeNoRet(),
1593                                                   StopTracking,
1594                                                   StopTracking);
1595
1596  addClassMethSummary("NSWindow", "alloc", NoTrackYet);
1597
1598  // For NSPanel (which subclasses NSWindow), allocated objects are not
1599  //  self-owned.
1600  // FIXME: For now we don't track NSPanels. object for the same reason
1601  //   as for NSWindow objects.
1602  addClassMethSummary("NSPanel", "alloc", NoTrackYet);
1603
1604  // Don't track allocated autorelease pools yet, as it is okay to prematurely
1605  // exit a method.
1606  addClassMethSummary("NSAutoreleasePool", "alloc", NoTrackYet);
1607  addClassMethSummary("NSAutoreleasePool", "allocWithZone", NoTrackYet, false);
1608
1609  // Create summaries QCRenderer/QCView -createSnapShotImageOfType:
1610  addInstMethSummary("QCRenderer", AllocSumm,
1611                     "createSnapshotImageOfType", NULL);
1612  addInstMethSummary("QCView", AllocSumm,
1613                     "createSnapshotImageOfType", NULL);
1614
1615  // Create summaries for CIContext, 'createCGImage' and
1616  // 'createCGLayerWithSize'.  These objects are CF objects, and are not
1617  // automatically garbage collected.
1618  addInstMethSummary("CIContext", CFAllocSumm,
1619                     "createCGImage", "fromRect", NULL);
1620  addInstMethSummary("CIContext", CFAllocSumm,
1621                     "createCGImage", "fromRect", "format", "colorSpace", NULL);
1622  addInstMethSummary("CIContext", CFAllocSumm, "createCGLayerWithSize",
1623           "info", NULL);
1624}
1625
1626//===----------------------------------------------------------------------===//
1627// Error reporting.
1628//===----------------------------------------------------------------------===//
1629namespace {
1630  typedef llvm::DenseMap<const ExplodedNode *, const RetainSummary *>
1631    SummaryLogTy;
1632
1633  //===-------------===//
1634  // Bug Descriptions. //
1635  //===-------------===//
1636
1637  class CFRefBug : public BugType {
1638  protected:
1639    CFRefBug(StringRef name)
1640    : BugType(name, categories::MemoryCoreFoundationObjectiveC) {}
1641  public:
1642
1643    // FIXME: Eventually remove.
1644    virtual const char *getDescription() const = 0;
1645
1646    virtual bool isLeak() const { return false; }
1647  };
1648
1649  class UseAfterRelease : public CFRefBug {
1650  public:
1651    UseAfterRelease() : CFRefBug("Use-after-release") {}
1652
1653    const char *getDescription() const {
1654      return "Reference-counted object is used after it is released";
1655    }
1656  };
1657
1658  class BadRelease : public CFRefBug {
1659  public:
1660    BadRelease() : CFRefBug("Bad release") {}
1661
1662    const char *getDescription() const {
1663      return "Incorrect decrement of the reference count of an object that is "
1664             "not owned at this point by the caller";
1665    }
1666  };
1667
1668  class DeallocGC : public CFRefBug {
1669  public:
1670    DeallocGC()
1671    : CFRefBug("-dealloc called while using garbage collection") {}
1672
1673    const char *getDescription() const {
1674      return "-dealloc called while using garbage collection";
1675    }
1676  };
1677
1678  class DeallocNotOwned : public CFRefBug {
1679  public:
1680    DeallocNotOwned()
1681    : CFRefBug("-dealloc sent to non-exclusively owned object") {}
1682
1683    const char *getDescription() const {
1684      return "-dealloc sent to object that may be referenced elsewhere";
1685    }
1686  };
1687
1688  class OverAutorelease : public CFRefBug {
1689  public:
1690    OverAutorelease()
1691    : CFRefBug("Object sent -autorelease too many times") {}
1692
1693    const char *getDescription() const {
1694      return "Object sent -autorelease too many times";
1695    }
1696  };
1697
1698  class ReturnedNotOwnedForOwned : public CFRefBug {
1699  public:
1700    ReturnedNotOwnedForOwned()
1701    : CFRefBug("Method should return an owned object") {}
1702
1703    const char *getDescription() const {
1704      return "Object with a +0 retain count returned to caller where a +1 "
1705             "(owning) retain count is expected";
1706    }
1707  };
1708
1709  class Leak : public CFRefBug {
1710  public:
1711    Leak(StringRef name)
1712    : CFRefBug(name) {
1713      // Leaks should not be reported if they are post-dominated by a sink.
1714      setSuppressOnSink(true);
1715    }
1716
1717    const char *getDescription() const { return ""; }
1718
1719    bool isLeak() const { return true; }
1720  };
1721
1722  //===---------===//
1723  // Bug Reports.  //
1724  //===---------===//
1725
1726  class CFRefReportVisitor : public BugReporterVisitorImpl<CFRefReportVisitor> {
1727  protected:
1728    SymbolRef Sym;
1729    const SummaryLogTy &SummaryLog;
1730    bool GCEnabled;
1731
1732  public:
1733    CFRefReportVisitor(SymbolRef sym, bool gcEnabled, const SummaryLogTy &log)
1734       : Sym(sym), SummaryLog(log), GCEnabled(gcEnabled) {}
1735
1736    virtual void Profile(llvm::FoldingSetNodeID &ID) const {
1737      static int x = 0;
1738      ID.AddPointer(&x);
1739      ID.AddPointer(Sym);
1740    }
1741
1742    virtual PathDiagnosticPiece *VisitNode(const ExplodedNode *N,
1743                                           const ExplodedNode *PrevN,
1744                                           BugReporterContext &BRC,
1745                                           BugReport &BR);
1746
1747    virtual PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1748                                            const ExplodedNode *N,
1749                                            BugReport &BR);
1750  };
1751
1752  class CFRefLeakReportVisitor : public CFRefReportVisitor {
1753  public:
1754    CFRefLeakReportVisitor(SymbolRef sym, bool GCEnabled,
1755                           const SummaryLogTy &log)
1756       : CFRefReportVisitor(sym, GCEnabled, log) {}
1757
1758    PathDiagnosticPiece *getEndPath(BugReporterContext &BRC,
1759                                    const ExplodedNode *N,
1760                                    BugReport &BR);
1761
1762    virtual BugReporterVisitor *clone() const {
1763      // The curiously-recurring template pattern only works for one level of
1764      // subclassing. Rather than make a new template base for
1765      // CFRefReportVisitor, we simply override clone() to do the right thing.
1766      // This could be trouble someday if BugReporterVisitorImpl is ever
1767      // used for something else besides a convenient implementation of clone().
1768      return new CFRefLeakReportVisitor(*this);
1769    }
1770  };
1771
1772  class CFRefReport : public BugReport {
1773    void addGCModeDescription(const LangOptions &LOpts, bool GCEnabled);
1774
1775  public:
1776    CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1777                const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1778                bool registerVisitor = true)
1779      : BugReport(D, D.getDescription(), n) {
1780      if (registerVisitor)
1781        addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1782      addGCModeDescription(LOpts, GCEnabled);
1783    }
1784
1785    CFRefReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1786                const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1787                StringRef endText)
1788      : BugReport(D, D.getDescription(), endText, n) {
1789      addVisitor(new CFRefReportVisitor(sym, GCEnabled, Log));
1790      addGCModeDescription(LOpts, GCEnabled);
1791    }
1792
1793    virtual std::pair<ranges_iterator, ranges_iterator> getRanges() {
1794      const CFRefBug& BugTy = static_cast<CFRefBug&>(getBugType());
1795      if (!BugTy.isLeak())
1796        return BugReport::getRanges();
1797      else
1798        return std::make_pair(ranges_iterator(), ranges_iterator());
1799    }
1800  };
1801
1802  class CFRefLeakReport : public CFRefReport {
1803    const MemRegion* AllocBinding;
1804
1805  public:
1806    CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts, bool GCEnabled,
1807                    const SummaryLogTy &Log, ExplodedNode *n, SymbolRef sym,
1808                    CheckerContext &Ctx);
1809
1810    PathDiagnosticLocation getLocation(const SourceManager &SM) const {
1811      assert(Location.isValid());
1812      return Location;
1813    }
1814  };
1815} // end anonymous namespace
1816
1817void CFRefReport::addGCModeDescription(const LangOptions &LOpts,
1818                                       bool GCEnabled) {
1819  const char *GCModeDescription = 0;
1820
1821  switch (LOpts.getGC()) {
1822  case LangOptions::GCOnly:
1823    assert(GCEnabled);
1824    GCModeDescription = "Code is compiled to only use garbage collection";
1825    break;
1826
1827  case LangOptions::NonGC:
1828    assert(!GCEnabled);
1829    GCModeDescription = "Code is compiled to use reference counts";
1830    break;
1831
1832  case LangOptions::HybridGC:
1833    if (GCEnabled) {
1834      GCModeDescription = "Code is compiled to use either garbage collection "
1835                          "(GC) or reference counts (non-GC).  The bug occurs "
1836                          "with GC enabled";
1837      break;
1838    } else {
1839      GCModeDescription = "Code is compiled to use either garbage collection "
1840                          "(GC) or reference counts (non-GC).  The bug occurs "
1841                          "in non-GC mode";
1842      break;
1843    }
1844  }
1845
1846  assert(GCModeDescription && "invalid/unknown GC mode");
1847  addExtraText(GCModeDescription);
1848}
1849
1850// FIXME: This should be a method on SmallVector.
1851static inline bool contains(const SmallVectorImpl<ArgEffect>& V,
1852                            ArgEffect X) {
1853  for (SmallVectorImpl<ArgEffect>::const_iterator I=V.begin(), E=V.end();
1854       I!=E; ++I)
1855    if (*I == X) return true;
1856
1857  return false;
1858}
1859
1860static bool isNumericLiteralExpression(const Expr *E) {
1861  // FIXME: This set of cases was copied from SemaExprObjC.
1862  return isa<IntegerLiteral>(E) ||
1863         isa<CharacterLiteral>(E) ||
1864         isa<FloatingLiteral>(E) ||
1865         isa<ObjCBoolLiteralExpr>(E) ||
1866         isa<CXXBoolLiteralExpr>(E);
1867}
1868
1869PathDiagnosticPiece *CFRefReportVisitor::VisitNode(const ExplodedNode *N,
1870                                                   const ExplodedNode *PrevN,
1871                                                   BugReporterContext &BRC,
1872                                                   BugReport &BR) {
1873  // FIXME: We will eventually need to handle non-statement-based events
1874  // (__attribute__((cleanup))).
1875  if (!isa<StmtPoint>(N->getLocation()))
1876    return NULL;
1877
1878  // Check if the type state has changed.
1879  ProgramStateRef PrevSt = PrevN->getState();
1880  ProgramStateRef CurrSt = N->getState();
1881  const LocationContext *LCtx = N->getLocationContext();
1882
1883  const RefVal* CurrT = getRefBinding(CurrSt, Sym);
1884  if (!CurrT) return NULL;
1885
1886  const RefVal &CurrV = *CurrT;
1887  const RefVal *PrevT = getRefBinding(PrevSt, Sym);
1888
1889  // Create a string buffer to constain all the useful things we want
1890  // to tell the user.
1891  std::string sbuf;
1892  llvm::raw_string_ostream os(sbuf);
1893
1894  // This is the allocation site since the previous node had no bindings
1895  // for this symbol.
1896  if (!PrevT) {
1897    const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
1898
1899    if (isa<ObjCArrayLiteral>(S)) {
1900      os << "NSArray literal is an object with a +0 retain count";
1901    }
1902    else if (isa<ObjCDictionaryLiteral>(S)) {
1903      os << "NSDictionary literal is an object with a +0 retain count";
1904    }
1905    else if (const ObjCBoxedExpr *BL = dyn_cast<ObjCBoxedExpr>(S)) {
1906      if (isNumericLiteralExpression(BL->getSubExpr()))
1907        os << "NSNumber literal is an object with a +0 retain count";
1908      else {
1909        const ObjCInterfaceDecl *BoxClass = 0;
1910        if (const ObjCMethodDecl *Method = BL->getBoxingMethod())
1911          BoxClass = Method->getClassInterface();
1912
1913        // We should always be able to find the boxing class interface,
1914        // but consider this future-proofing.
1915        if (BoxClass)
1916          os << *BoxClass << " b";
1917        else
1918          os << "B";
1919
1920        os << "oxed expression produces an object with a +0 retain count";
1921      }
1922    }
1923    else {
1924      if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1925        // Get the name of the callee (if it is available).
1926        SVal X = CurrSt->getSValAsScalarOrLoc(CE->getCallee(), LCtx);
1927        if (const FunctionDecl *FD = X.getAsFunctionDecl())
1928          os << "Call to function '" << *FD << '\'';
1929        else
1930          os << "function call";
1931      }
1932      else {
1933        assert(isa<ObjCMessageExpr>(S));
1934        CallEventManager &Mgr = CurrSt->getStateManager().getCallEventManager();
1935        CallEventRef<ObjCMethodCall> Call
1936          = Mgr.getObjCMethodCall(cast<ObjCMessageExpr>(S), CurrSt, LCtx);
1937
1938        switch (Call->getMessageKind()) {
1939        case OCM_Message:
1940          os << "Method";
1941          break;
1942        case OCM_PropertyAccess:
1943          os << "Property";
1944          break;
1945        case OCM_Subscript:
1946          os << "Subscript";
1947          break;
1948        }
1949      }
1950
1951      if (CurrV.getObjKind() == RetEffect::CF) {
1952        os << " returns a Core Foundation object with a ";
1953      }
1954      else {
1955        assert (CurrV.getObjKind() == RetEffect::ObjC);
1956        os << " returns an Objective-C object with a ";
1957      }
1958
1959      if (CurrV.isOwned()) {
1960        os << "+1 retain count";
1961
1962        if (GCEnabled) {
1963          assert(CurrV.getObjKind() == RetEffect::CF);
1964          os << ".  "
1965          "Core Foundation objects are not automatically garbage collected.";
1966        }
1967      }
1968      else {
1969        assert (CurrV.isNotOwned());
1970        os << "+0 retain count";
1971      }
1972    }
1973
1974    PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
1975                                  N->getLocationContext());
1976    return new PathDiagnosticEventPiece(Pos, os.str());
1977  }
1978
1979  // Gather up the effects that were performed on the object at this
1980  // program point
1981  SmallVector<ArgEffect, 2> AEffects;
1982
1983  const ExplodedNode *OrigNode = BRC.getNodeResolver().getOriginalNode(N);
1984  if (const RetainSummary *Summ = SummaryLog.lookup(OrigNode)) {
1985    // We only have summaries attached to nodes after evaluating CallExpr and
1986    // ObjCMessageExprs.
1987    const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
1988
1989    if (const CallExpr *CE = dyn_cast<CallExpr>(S)) {
1990      // Iterate through the parameter expressions and see if the symbol
1991      // was ever passed as an argument.
1992      unsigned i = 0;
1993
1994      for (CallExpr::const_arg_iterator AI=CE->arg_begin(), AE=CE->arg_end();
1995           AI!=AE; ++AI, ++i) {
1996
1997        // Retrieve the value of the argument.  Is it the symbol
1998        // we are interested in?
1999        if (CurrSt->getSValAsScalarOrLoc(*AI, LCtx).getAsLocSymbol() != Sym)
2000          continue;
2001
2002        // We have an argument.  Get the effect!
2003        AEffects.push_back(Summ->getArg(i));
2004      }
2005    }
2006    else if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(S)) {
2007      if (const Expr *receiver = ME->getInstanceReceiver())
2008        if (CurrSt->getSValAsScalarOrLoc(receiver, LCtx)
2009              .getAsLocSymbol() == Sym) {
2010          // The symbol we are tracking is the receiver.
2011          AEffects.push_back(Summ->getReceiverEffect());
2012        }
2013    }
2014  }
2015
2016  do {
2017    // Get the previous type state.
2018    RefVal PrevV = *PrevT;
2019
2020    // Specially handle -dealloc.
2021    if (!GCEnabled && contains(AEffects, Dealloc)) {
2022      // Determine if the object's reference count was pushed to zero.
2023      assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2024      // We may not have transitioned to 'release' if we hit an error.
2025      // This case is handled elsewhere.
2026      if (CurrV.getKind() == RefVal::Released) {
2027        assert(CurrV.getCombinedCounts() == 0);
2028        os << "Object released by directly sending the '-dealloc' message";
2029        break;
2030      }
2031    }
2032
2033    // Specially handle CFMakeCollectable and friends.
2034    if (contains(AEffects, MakeCollectable)) {
2035      // Get the name of the function.
2036      const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
2037      SVal X =
2038        CurrSt->getSValAsScalarOrLoc(cast<CallExpr>(S)->getCallee(), LCtx);
2039      const FunctionDecl *FD = X.getAsFunctionDecl();
2040
2041      if (GCEnabled) {
2042        // Determine if the object's reference count was pushed to zero.
2043        assert(!(PrevV == CurrV) && "The typestate *must* have changed.");
2044
2045        os << "In GC mode a call to '" << *FD
2046        <<  "' decrements an object's retain count and registers the "
2047        "object with the garbage collector. ";
2048
2049        if (CurrV.getKind() == RefVal::Released) {
2050          assert(CurrV.getCount() == 0);
2051          os << "Since it now has a 0 retain count the object can be "
2052          "automatically collected by the garbage collector.";
2053        }
2054        else
2055          os << "An object must have a 0 retain count to be garbage collected. "
2056          "After this call its retain count is +" << CurrV.getCount()
2057          << '.';
2058      }
2059      else
2060        os << "When GC is not enabled a call to '" << *FD
2061        << "' has no effect on its argument.";
2062
2063      // Nothing more to say.
2064      break;
2065    }
2066
2067    // Determine if the typestate has changed.
2068    if (!(PrevV == CurrV))
2069      switch (CurrV.getKind()) {
2070        case RefVal::Owned:
2071        case RefVal::NotOwned:
2072
2073          if (PrevV.getCount() == CurrV.getCount()) {
2074            // Did an autorelease message get sent?
2075            if (PrevV.getAutoreleaseCount() == CurrV.getAutoreleaseCount())
2076              return 0;
2077
2078            assert(PrevV.getAutoreleaseCount() < CurrV.getAutoreleaseCount());
2079            os << "Object sent -autorelease message";
2080            break;
2081          }
2082
2083          if (PrevV.getCount() > CurrV.getCount())
2084            os << "Reference count decremented.";
2085          else
2086            os << "Reference count incremented.";
2087
2088          if (unsigned Count = CurrV.getCount())
2089            os << " The object now has a +" << Count << " retain count.";
2090
2091          if (PrevV.getKind() == RefVal::Released) {
2092            assert(GCEnabled && CurrV.getCount() > 0);
2093            os << " The object is not eligible for garbage collection until "
2094                  "the retain count reaches 0 again.";
2095          }
2096
2097          break;
2098
2099        case RefVal::Released:
2100          os << "Object released.";
2101          break;
2102
2103        case RefVal::ReturnedOwned:
2104          // Autoreleases can be applied after marking a node ReturnedOwned.
2105          if (CurrV.getAutoreleaseCount())
2106            return NULL;
2107
2108          os << "Object returned to caller as an owning reference (single "
2109                "retain count transferred to caller)";
2110          break;
2111
2112        case RefVal::ReturnedNotOwned:
2113          os << "Object returned to caller with a +0 retain count";
2114          break;
2115
2116        default:
2117          return NULL;
2118      }
2119
2120    // Emit any remaining diagnostics for the argument effects (if any).
2121    for (SmallVectorImpl<ArgEffect>::iterator I=AEffects.begin(),
2122         E=AEffects.end(); I != E; ++I) {
2123
2124      // A bunch of things have alternate behavior under GC.
2125      if (GCEnabled)
2126        switch (*I) {
2127          default: break;
2128          case Autorelease:
2129            os << "In GC mode an 'autorelease' has no effect.";
2130            continue;
2131          case IncRefMsg:
2132            os << "In GC mode the 'retain' message has no effect.";
2133            continue;
2134          case DecRefMsg:
2135            os << "In GC mode the 'release' message has no effect.";
2136            continue;
2137        }
2138    }
2139  } while (0);
2140
2141  if (os.str().empty())
2142    return 0; // We have nothing to say!
2143
2144  const Stmt *S = cast<StmtPoint>(N->getLocation()).getStmt();
2145  PathDiagnosticLocation Pos(S, BRC.getSourceManager(),
2146                                N->getLocationContext());
2147  PathDiagnosticPiece *P = new PathDiagnosticEventPiece(Pos, os.str());
2148
2149  // Add the range by scanning the children of the statement for any bindings
2150  // to Sym.
2151  for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
2152       I!=E; ++I)
2153    if (const Expr *Exp = dyn_cast_or_null<Expr>(*I))
2154      if (CurrSt->getSValAsScalarOrLoc(Exp, LCtx).getAsLocSymbol() == Sym) {
2155        P->addRange(Exp->getSourceRange());
2156        break;
2157      }
2158
2159  return P;
2160}
2161
2162// Find the first node in the current function context that referred to the
2163// tracked symbol and the memory location that value was stored to. Note, the
2164// value is only reported if the allocation occurred in the same function as
2165// the leak.
2166static std::pair<const ExplodedNode*,const MemRegion*>
2167GetAllocationSite(ProgramStateManager& StateMgr, const ExplodedNode *N,
2168                  SymbolRef Sym) {
2169  const ExplodedNode *Last = N;
2170  const MemRegion* FirstBinding = 0;
2171  const LocationContext *LeakContext = N->getLocationContext();
2172
2173  while (N) {
2174    ProgramStateRef St = N->getState();
2175
2176    if (!getRefBinding(St, Sym))
2177      break;
2178
2179    StoreManager::FindUniqueBinding FB(Sym);
2180    StateMgr.iterBindings(St, FB);
2181    if (FB) FirstBinding = FB.getRegion();
2182
2183    // Allocation node, is the last node in the current context in which the
2184    // symbol was tracked.
2185    if (N->getLocationContext() == LeakContext)
2186      Last = N;
2187
2188    N = N->pred_empty() ? NULL : *(N->pred_begin());
2189  }
2190
2191  // If allocation happened in a function different from the leak node context,
2192  // do not report the binding.
2193  assert(N && "Could not find allocation node");
2194  if (N->getLocationContext() != LeakContext) {
2195    FirstBinding = 0;
2196  }
2197
2198  return std::make_pair(Last, FirstBinding);
2199}
2200
2201PathDiagnosticPiece*
2202CFRefReportVisitor::getEndPath(BugReporterContext &BRC,
2203                               const ExplodedNode *EndN,
2204                               BugReport &BR) {
2205  BR.markInteresting(Sym);
2206  return BugReporterVisitor::getDefaultEndPath(BRC, EndN, BR);
2207}
2208
2209PathDiagnosticPiece*
2210CFRefLeakReportVisitor::getEndPath(BugReporterContext &BRC,
2211                                   const ExplodedNode *EndN,
2212                                   BugReport &BR) {
2213
2214  // Tell the BugReporterContext to report cases when the tracked symbol is
2215  // assigned to different variables, etc.
2216  BR.markInteresting(Sym);
2217
2218  // We are reporting a leak.  Walk up the graph to get to the first node where
2219  // the symbol appeared, and also get the first VarDecl that tracked object
2220  // is stored to.
2221  const ExplodedNode *AllocNode = 0;
2222  const MemRegion* FirstBinding = 0;
2223
2224  llvm::tie(AllocNode, FirstBinding) =
2225    GetAllocationSite(BRC.getStateManager(), EndN, Sym);
2226
2227  SourceManager& SM = BRC.getSourceManager();
2228
2229  // Compute an actual location for the leak.  Sometimes a leak doesn't
2230  // occur at an actual statement (e.g., transition between blocks; end
2231  // of function) so we need to walk the graph and compute a real location.
2232  const ExplodedNode *LeakN = EndN;
2233  PathDiagnosticLocation L = PathDiagnosticLocation::createEndOfPath(LeakN, SM);
2234
2235  std::string sbuf;
2236  llvm::raw_string_ostream os(sbuf);
2237
2238  os << "Object leaked: ";
2239
2240  if (FirstBinding) {
2241    os << "object allocated and stored into '"
2242       << FirstBinding->getString() << '\'';
2243  }
2244  else
2245    os << "allocated object";
2246
2247  // Get the retain count.
2248  const RefVal* RV = getRefBinding(EndN->getState(), Sym);
2249  assert(RV);
2250
2251  if (RV->getKind() == RefVal::ErrorLeakReturned) {
2252    // FIXME: Per comments in rdar://6320065, "create" only applies to CF
2253    // objects.  Only "copy", "alloc", "retain" and "new" transfer ownership
2254    // to the caller for NS objects.
2255    const Decl *D = &EndN->getCodeDecl();
2256
2257    os << (isa<ObjCMethodDecl>(D) ? " is returned from a method "
2258                                  : " is returned from a function ");
2259
2260    if (D->getAttr<CFReturnsNotRetainedAttr>())
2261      os << "that is annotated as CF_RETURNS_NOT_RETAINED";
2262    else if (D->getAttr<NSReturnsNotRetainedAttr>())
2263      os << "that is annotated as NS_RETURNS_NOT_RETAINED";
2264    else {
2265      if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2266        os << "whose name ('" << MD->getSelector().getAsString()
2267           << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2268              "  This violates the naming convention rules"
2269              " given in the Memory Management Guide for Cocoa";
2270      }
2271      else {
2272        const FunctionDecl *FD = cast<FunctionDecl>(D);
2273        os << "whose name ('" << *FD
2274           << "') does not contain 'Copy' or 'Create'.  This violates the naming"
2275              " convention rules given in the Memory Management Guide for Core"
2276              " Foundation";
2277      }
2278    }
2279  }
2280  else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2281    ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
2282    os << " and returned from method '" << MD.getSelector().getAsString()
2283       << "' is potentially leaked when using garbage collection.  Callers "
2284          "of this method do not expect a returned object with a +1 retain "
2285          "count since they expect the object to be managed by the garbage "
2286          "collector";
2287  }
2288  else
2289    os << " is not referenced later in this execution path and has a retain "
2290          "count of +" << RV->getCount();
2291
2292  return new PathDiagnosticEventPiece(L, os.str());
2293}
2294
2295CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2296                                 bool GCEnabled, const SummaryLogTy &Log,
2297                                 ExplodedNode *n, SymbolRef sym,
2298                                 CheckerContext &Ctx)
2299: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
2300
2301  // Most bug reports are cached at the location where they occurred.
2302  // With leaks, we want to unique them by the location where they were
2303  // allocated, and only report a single path.  To do this, we need to find
2304  // the allocation site of a piece of tracked memory, which we do via a
2305  // call to GetAllocationSite.  This will walk the ExplodedGraph backwards.
2306  // Note that this is *not* the trimmed graph; we are guaranteed, however,
2307  // that all ancestor nodes that represent the allocation site have the
2308  // same SourceLocation.
2309  const ExplodedNode *AllocNode = 0;
2310
2311  const SourceManager& SMgr = Ctx.getSourceManager();
2312
2313  llvm::tie(AllocNode, AllocBinding) =  // Set AllocBinding.
2314    GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
2315
2316  // Get the SourceLocation for the allocation site.
2317  // FIXME: This will crash the analyzer if an allocation comes from an
2318  // implicit call. (Currently there are no such allocations in Cocoa, though.)
2319  const Stmt *AllocStmt;
2320  ProgramPoint P = AllocNode->getLocation();
2321  if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
2322    AllocStmt = Exit->getCalleeContext()->getCallSite();
2323  else
2324    AllocStmt = cast<PostStmt>(P).getStmt();
2325  assert(AllocStmt && "All allocations must come from explicit calls");
2326  Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2327                                                  n->getLocationContext());
2328  // Fill in the description of the bug.
2329  Description.clear();
2330  llvm::raw_string_ostream os(Description);
2331  os << "Potential leak ";
2332  if (GCEnabled)
2333    os << "(when using garbage collection) ";
2334  os << "of an object";
2335
2336  // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2337  if (AllocBinding)
2338    os << " stored into '" << AllocBinding->getString() << '\'';
2339
2340  addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
2341}
2342
2343//===----------------------------------------------------------------------===//
2344// Main checker logic.
2345//===----------------------------------------------------------------------===//
2346
2347namespace {
2348class RetainCountChecker
2349  : public Checker< check::Bind,
2350                    check::DeadSymbols,
2351                    check::EndAnalysis,
2352                    check::EndPath,
2353                    check::PostStmt<BlockExpr>,
2354                    check::PostStmt<CastExpr>,
2355                    check::PostStmt<ObjCArrayLiteral>,
2356                    check::PostStmt<ObjCDictionaryLiteral>,
2357                    check::PostStmt<ObjCBoxedExpr>,
2358                    check::PostCall,
2359                    check::PreStmt<ReturnStmt>,
2360                    check::RegionChanges,
2361                    eval::Assume,
2362                    eval::Call > {
2363  mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2364  mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2365  mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2366  mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2367  mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
2368
2369  typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2370
2371  // This map is only used to ensure proper deletion of any allocated tags.
2372  mutable SymbolTagMap DeadSymbolTags;
2373
2374  mutable OwningPtr<RetainSummaryManager> Summaries;
2375  mutable OwningPtr<RetainSummaryManager> SummariesGC;
2376  mutable SummaryLogTy SummaryLog;
2377  mutable bool ShouldResetSummaryLog;
2378
2379public:
2380  RetainCountChecker() : ShouldResetSummaryLog(false) {}
2381
2382  virtual ~RetainCountChecker() {
2383    DeleteContainerSeconds(DeadSymbolTags);
2384  }
2385
2386  void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2387                        ExprEngine &Eng) const {
2388    // FIXME: This is a hack to make sure the summary log gets cleared between
2389    // analyses of different code bodies.
2390    //
2391    // Why is this necessary? Because a checker's lifetime is tied to a
2392    // translation unit, but an ExplodedGraph's lifetime is just a code body.
2393    // Once in a blue moon, a new ExplodedNode will have the same address as an
2394    // old one with an associated summary, and the bug report visitor gets very
2395    // confused. (To make things worse, the summary lifetime is currently also
2396    // tied to a code body, so we get a crash instead of incorrect results.)
2397    //
2398    // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2399    // changes, things will start going wrong again. Really the lifetime of this
2400    // log needs to be tied to either the specific nodes in it or the entire
2401    // ExplodedGraph, not to a specific part of the code being analyzed.
2402    //
2403    // (Also, having stateful local data means that the same checker can't be
2404    // used from multiple threads, but a lot of checkers have incorrect
2405    // assumptions about that anyway. So that wasn't a priority at the time of
2406    // this fix.)
2407    //
2408    // This happens at the end of analysis, but bug reports are emitted /after/
2409    // this point. So we can't just clear the summary log now. Instead, we mark
2410    // that the next time we access the summary log, it should be cleared.
2411
2412    // If we never reset the summary log during /this/ code body analysis,
2413    // there were no new summaries. There might still have been summaries from
2414    // the /last/ analysis, so clear them out to make sure the bug report
2415    // visitors don't get confused.
2416    if (ShouldResetSummaryLog)
2417      SummaryLog.clear();
2418
2419    ShouldResetSummaryLog = !SummaryLog.empty();
2420  }
2421
2422  CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2423                                     bool GCEnabled) const {
2424    if (GCEnabled) {
2425      if (!leakWithinFunctionGC)
2426        leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2427                                             "garbage collection"));
2428      return leakWithinFunctionGC.get();
2429    } else {
2430      if (!leakWithinFunction) {
2431        if (LOpts.getGC() == LangOptions::HybridGC) {
2432          leakWithinFunction.reset(new Leak("Leak of object when not using "
2433                                            "garbage collection (GC) in "
2434                                            "dual GC/non-GC code"));
2435        } else {
2436          leakWithinFunction.reset(new Leak("Leak"));
2437        }
2438      }
2439      return leakWithinFunction.get();
2440    }
2441  }
2442
2443  CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2444    if (GCEnabled) {
2445      if (!leakAtReturnGC)
2446        leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2447                                      "garbage collection"));
2448      return leakAtReturnGC.get();
2449    } else {
2450      if (!leakAtReturn) {
2451        if (LOpts.getGC() == LangOptions::HybridGC) {
2452          leakAtReturn.reset(new Leak("Leak of returned object when not using "
2453                                      "garbage collection (GC) in dual "
2454                                      "GC/non-GC code"));
2455        } else {
2456          leakAtReturn.reset(new Leak("Leak of returned object"));
2457        }
2458      }
2459      return leakAtReturn.get();
2460    }
2461  }
2462
2463  RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2464                                          bool GCEnabled) const {
2465    // FIXME: We don't support ARC being turned on and off during one analysis.
2466    // (nor, for that matter, do we support changing ASTContexts)
2467    bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
2468    if (GCEnabled) {
2469      if (!SummariesGC)
2470        SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
2471      else
2472        assert(SummariesGC->isARCEnabled() == ARCEnabled);
2473      return *SummariesGC;
2474    } else {
2475      if (!Summaries)
2476        Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
2477      else
2478        assert(Summaries->isARCEnabled() == ARCEnabled);
2479      return *Summaries;
2480    }
2481  }
2482
2483  RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2484    return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2485  }
2486
2487  void printState(raw_ostream &Out, ProgramStateRef State,
2488                  const char *NL, const char *Sep) const;
2489
2490  void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
2491  void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2492  void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
2493
2494  void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2495  void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
2496  void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2497
2498  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
2499
2500  void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
2501                    CheckerContext &C) const;
2502
2503  void processSummaryOfInlined(const RetainSummary &Summ,
2504                               const CallEvent &Call,
2505                               CheckerContext &C) const;
2506
2507  bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2508
2509  ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
2510                                 bool Assumption) const;
2511
2512  ProgramStateRef
2513  checkRegionChanges(ProgramStateRef state,
2514                     const StoreManager::InvalidatedSymbols *invalidated,
2515                     ArrayRef<const MemRegion *> ExplicitRegions,
2516                     ArrayRef<const MemRegion *> Regions,
2517                     const CallEvent *Call) const;
2518
2519  bool wantsRegionChangeUpdate(ProgramStateRef state) const {
2520    return true;
2521  }
2522
2523  void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2524  void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2525                                ExplodedNode *Pred, RetEffect RE, RefVal X,
2526                                SymbolRef Sym, ProgramStateRef state) const;
2527
2528  void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
2529  void checkEndPath(CheckerContext &C) const;
2530
2531  ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
2532                               RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2533                               CheckerContext &C) const;
2534
2535  void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
2536                           RefVal::Kind ErrorKind, SymbolRef Sym,
2537                           CheckerContext &C) const;
2538
2539  void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
2540
2541  const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2542
2543  ProgramStateRef handleSymbolDeath(ProgramStateRef state,
2544                                    SymbolRef sid, RefVal V,
2545                                    SmallVectorImpl<SymbolRef> &Leaked) const;
2546
2547  std::pair<ExplodedNode *, ProgramStateRef >
2548  handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2549                          const ProgramPointTag *Tag, CheckerContext &Ctx,
2550                          SymbolRef Sym, RefVal V) const;
2551
2552  ExplodedNode *processLeaks(ProgramStateRef state,
2553                             SmallVectorImpl<SymbolRef> &Leaked,
2554                             CheckerContext &Ctx,
2555                             ExplodedNode *Pred = 0) const;
2556};
2557} // end anonymous namespace
2558
2559namespace {
2560class StopTrackingCallback : public SymbolVisitor {
2561  ProgramStateRef state;
2562public:
2563  StopTrackingCallback(ProgramStateRef st) : state(st) {}
2564  ProgramStateRef getState() const { return state; }
2565
2566  bool VisitSymbol(SymbolRef sym) {
2567    state = state->remove<RefBindings>(sym);
2568    return true;
2569  }
2570};
2571} // end anonymous namespace
2572
2573//===----------------------------------------------------------------------===//
2574// Handle statements that may have an effect on refcounts.
2575//===----------------------------------------------------------------------===//
2576
2577void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2578                                       CheckerContext &C) const {
2579
2580  // Scan the BlockDecRefExprs for any object the retain count checker
2581  // may be tracking.
2582  if (!BE->getBlockDecl()->hasCaptures())
2583    return;
2584
2585  ProgramStateRef state = C.getState();
2586  const BlockDataRegion *R =
2587    cast<BlockDataRegion>(state->getSVal(BE,
2588                                         C.getLocationContext()).getAsRegion());
2589
2590  BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2591                                            E = R->referenced_vars_end();
2592
2593  if (I == E)
2594    return;
2595
2596  // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2597  // via captured variables, even though captured variables result in a copy
2598  // and in implicit increment/decrement of a retain count.
2599  SmallVector<const MemRegion*, 10> Regions;
2600  const LocationContext *LC = C.getLocationContext();
2601  MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2602
2603  for ( ; I != E; ++I) {
2604    const VarRegion *VR = *I;
2605    if (VR->getSuperRegion() == R) {
2606      VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2607    }
2608    Regions.push_back(VR);
2609  }
2610
2611  state =
2612    state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2613                                    Regions.data() + Regions.size()).getState();
2614  C.addTransition(state);
2615}
2616
2617void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2618                                       CheckerContext &C) const {
2619  const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2620  if (!BE)
2621    return;
2622
2623  ArgEffect AE = IncRef;
2624
2625  switch (BE->getBridgeKind()) {
2626    case clang::OBC_Bridge:
2627      // Do nothing.
2628      return;
2629    case clang::OBC_BridgeRetained:
2630      AE = IncRef;
2631      break;
2632    case clang::OBC_BridgeTransfer:
2633      AE = DecRefBridgedTransfered;
2634      break;
2635  }
2636
2637  ProgramStateRef state = C.getState();
2638  SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
2639  if (!Sym)
2640    return;
2641  const RefVal* T = getRefBinding(state, Sym);
2642  if (!T)
2643    return;
2644
2645  RefVal::Kind hasErr = (RefVal::Kind) 0;
2646  state = updateSymbol(state, Sym, *T, AE, hasErr, C);
2647
2648  if (hasErr) {
2649    // FIXME: If we get an error during a bridge cast, should we report it?
2650    // Should we assert that there is no error?
2651    return;
2652  }
2653
2654  C.addTransition(state);
2655}
2656
2657void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2658                                             const Expr *Ex) const {
2659  ProgramStateRef state = C.getState();
2660  const ExplodedNode *pred = C.getPredecessor();
2661  for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2662       it != et ; ++it) {
2663    const Stmt *child = *it;
2664    SVal V = state->getSVal(child, pred->getLocationContext());
2665    if (SymbolRef sym = V.getAsSymbol())
2666      if (const RefVal* T = getRefBinding(state, sym)) {
2667        RefVal::Kind hasErr = (RefVal::Kind) 0;
2668        state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2669        if (hasErr) {
2670          processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2671          return;
2672        }
2673      }
2674  }
2675
2676  // Return the object as autoreleased.
2677  //  RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2678  if (SymbolRef sym =
2679        state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2680    QualType ResultTy = Ex->getType();
2681    state = setRefBinding(state, sym,
2682                          RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
2683  }
2684
2685  C.addTransition(state);
2686}
2687
2688void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2689                                       CheckerContext &C) const {
2690  // Apply the 'MayEscape' to all values.
2691  processObjCLiterals(C, AL);
2692}
2693
2694void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2695                                       CheckerContext &C) const {
2696  // Apply the 'MayEscape' to all keys and values.
2697  processObjCLiterals(C, DL);
2698}
2699
2700void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2701                                       CheckerContext &C) const {
2702  const ExplodedNode *Pred = C.getPredecessor();
2703  const LocationContext *LCtx = Pred->getLocationContext();
2704  ProgramStateRef State = Pred->getState();
2705
2706  if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2707    QualType ResultTy = Ex->getType();
2708    State = setRefBinding(State, Sym,
2709                          RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
2710  }
2711
2712  C.addTransition(State);
2713}
2714
2715void RetainCountChecker::checkPostCall(const CallEvent &Call,
2716                                       CheckerContext &C) const {
2717  RetainSummaryManager &Summaries = getSummaryManager(C);
2718  const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
2719
2720  if (C.wasInlined) {
2721    processSummaryOfInlined(*Summ, Call, C);
2722    return;
2723  }
2724  checkSummary(*Summ, Call, C);
2725}
2726
2727/// GetReturnType - Used to get the return type of a message expression or
2728///  function call with the intention of affixing that type to a tracked symbol.
2729///  While the return type can be queried directly from RetEx, when
2730///  invoking class methods we augment to the return type to be that of
2731///  a pointer to the class (as opposed it just being id).
2732// FIXME: We may be able to do this with related result types instead.
2733// This function is probably overestimating.
2734static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2735  QualType RetTy = RetE->getType();
2736  // If RetE is not a message expression just return its type.
2737  // If RetE is a message expression, return its types if it is something
2738  /// more specific than id.
2739  if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2740    if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2741      if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2742          PT->isObjCClassType()) {
2743        // At this point we know the return type of the message expression is
2744        // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2745        // is a call to a class method whose type we can resolve.  In such
2746        // cases, promote the return type to XXX* (where XXX is the class).
2747        const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2748        return !D ? RetTy :
2749                    Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2750      }
2751
2752  return RetTy;
2753}
2754
2755// We don't always get the exact modeling of the function with regards to the
2756// retain count checker even when the function is inlined. For example, we need
2757// to stop tracking the symbols which were marked with StopTrackingHard.
2758void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2759                                                 const CallEvent &CallOrMsg,
2760                                                 CheckerContext &C) const {
2761  ProgramStateRef state = C.getState();
2762
2763  // Evaluate the effect of the arguments.
2764  for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2765    if (Summ.getArg(idx) == StopTrackingHard) {
2766      SVal V = CallOrMsg.getArgSVal(idx);
2767      if (SymbolRef Sym = V.getAsLocSymbol()) {
2768        state = removeRefBinding(state, Sym);
2769      }
2770    }
2771  }
2772
2773  // Evaluate the effect on the message receiver.
2774  const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2775  if (MsgInvocation) {
2776    if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2777      if (Summ.getReceiverEffect() == StopTrackingHard) {
2778        state = removeRefBinding(state, Sym);
2779      }
2780    }
2781  }
2782
2783  // Consult the summary for the return value.
2784  RetEffect RE = Summ.getRetEffect();
2785  if (RE.getKind() == RetEffect::NoRetHard) {
2786    SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(),
2787        C.getLocationContext()).getAsSymbol();
2788    if (Sym)
2789      state = removeRefBinding(state, Sym);
2790  }
2791
2792  C.addTransition(state);
2793}
2794
2795void RetainCountChecker::checkSummary(const RetainSummary &Summ,
2796                                      const CallEvent &CallOrMsg,
2797                                      CheckerContext &C) const {
2798  ProgramStateRef state = C.getState();
2799
2800  // Evaluate the effect of the arguments.
2801  RefVal::Kind hasErr = (RefVal::Kind) 0;
2802  SourceRange ErrorRange;
2803  SymbolRef ErrorSym = 0;
2804
2805  for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2806    SVal V = CallOrMsg.getArgSVal(idx);
2807
2808    if (SymbolRef Sym = V.getAsLocSymbol()) {
2809      if (const RefVal *T = getRefBinding(state, Sym)) {
2810        state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
2811        if (hasErr) {
2812          ErrorRange = CallOrMsg.getArgSourceRange(idx);
2813          ErrorSym = Sym;
2814          break;
2815        }
2816      }
2817    }
2818  }
2819
2820  // Evaluate the effect on the message receiver.
2821  bool ReceiverIsTracked = false;
2822  if (!hasErr) {
2823    const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2824    if (MsgInvocation) {
2825      if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2826        if (const RefVal *T = getRefBinding(state, Sym)) {
2827          ReceiverIsTracked = true;
2828          state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
2829                                 hasErr, C);
2830          if (hasErr) {
2831            ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
2832            ErrorSym = Sym;
2833          }
2834        }
2835      }
2836    }
2837  }
2838
2839  // Process any errors.
2840  if (hasErr) {
2841    processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2842    return;
2843  }
2844
2845  // Consult the summary for the return value.
2846  RetEffect RE = Summ.getRetEffect();
2847
2848  if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2849    if (ReceiverIsTracked)
2850      RE = getSummaryManager(C).getObjAllocRetEffect();
2851    else
2852      RE = RetEffect::MakeNoRet();
2853  }
2854
2855  switch (RE.getKind()) {
2856    default:
2857      llvm_unreachable("Unhandled RetEffect.");
2858
2859    case RetEffect::NoRet:
2860    case RetEffect::NoRetHard:
2861      // No work necessary.
2862      break;
2863
2864    case RetEffect::OwnedAllocatedSymbol:
2865    case RetEffect::OwnedSymbol: {
2866      SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(),
2867                                     C.getLocationContext()).getAsSymbol();
2868      if (!Sym)
2869        break;
2870
2871      // Use the result type from the CallEvent as it automatically adjusts
2872      // for methods/functions that return references.
2873      QualType ResultTy = CallOrMsg.getResultType();
2874      state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2875                                                          ResultTy));
2876
2877      // FIXME: Add a flag to the checker where allocations are assumed to
2878      // *not* fail.
2879      break;
2880    }
2881
2882    case RetEffect::GCNotOwnedSymbol:
2883    case RetEffect::ARCNotOwnedSymbol:
2884    case RetEffect::NotOwnedSymbol: {
2885      const Expr *Ex = CallOrMsg.getOriginExpr();
2886      SymbolRef Sym = state->getSVal(Ex, C.getLocationContext()).getAsSymbol();
2887      if (!Sym)
2888        break;
2889      assert(Ex);
2890      // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2891      QualType ResultTy = GetReturnType(Ex, C.getASTContext());
2892      state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2893                                                             ResultTy));
2894      break;
2895    }
2896  }
2897
2898  // This check is actually necessary; otherwise the statement builder thinks
2899  // we've hit a previously-found path.
2900  // Normally addTransition takes care of this, but we want the node pointer.
2901  ExplodedNode *NewNode;
2902  if (state == C.getState()) {
2903    NewNode = C.getPredecessor();
2904  } else {
2905    NewNode = C.addTransition(state);
2906  }
2907
2908  // Annotate the node with summary we used.
2909  if (NewNode) {
2910    // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2911    if (ShouldResetSummaryLog) {
2912      SummaryLog.clear();
2913      ShouldResetSummaryLog = false;
2914    }
2915    SummaryLog[NewNode] = &Summ;
2916  }
2917}
2918
2919
2920ProgramStateRef
2921RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
2922                                 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2923                                 CheckerContext &C) const {
2924  // In GC mode [... release] and [... retain] do nothing.
2925  // In ARC mode they shouldn't exist at all, but we just ignore them.
2926  bool IgnoreRetainMsg = C.isObjCGCEnabled();
2927  if (!IgnoreRetainMsg)
2928    IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
2929
2930  switch (E) {
2931  default:
2932    break;
2933  case IncRefMsg:
2934    E = IgnoreRetainMsg ? DoNothing : IncRef;
2935    break;
2936  case DecRefMsg:
2937    E = IgnoreRetainMsg ? DoNothing : DecRef;
2938    break;
2939  case DecRefMsgAndStopTrackingHard:
2940    E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
2941    break;
2942  case MakeCollectable:
2943    E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2944    break;
2945  case NewAutoreleasePool:
2946    E = C.isObjCGCEnabled() ? DoNothing : NewAutoreleasePool;
2947    break;
2948  }
2949
2950  // Handle all use-after-releases.
2951  if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
2952    V = V ^ RefVal::ErrorUseAfterRelease;
2953    hasErr = V.getKind();
2954    return setRefBinding(state, sym, V);
2955  }
2956
2957  switch (E) {
2958    case DecRefMsg:
2959    case IncRefMsg:
2960    case MakeCollectable:
2961    case DecRefMsgAndStopTrackingHard:
2962      llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
2963
2964    case Dealloc:
2965      // Any use of -dealloc in GC is *bad*.
2966      if (C.isObjCGCEnabled()) {
2967        V = V ^ RefVal::ErrorDeallocGC;
2968        hasErr = V.getKind();
2969        break;
2970      }
2971
2972      switch (V.getKind()) {
2973        default:
2974          llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
2975        case RefVal::Owned:
2976          // The object immediately transitions to the released state.
2977          V = V ^ RefVal::Released;
2978          V.clearCounts();
2979          return setRefBinding(state, sym, V);
2980        case RefVal::NotOwned:
2981          V = V ^ RefVal::ErrorDeallocNotOwned;
2982          hasErr = V.getKind();
2983          break;
2984      }
2985      break;
2986
2987    case NewAutoreleasePool:
2988      assert(!C.isObjCGCEnabled());
2989      return state;
2990
2991    case MayEscape:
2992      if (V.getKind() == RefVal::Owned) {
2993        V = V ^ RefVal::NotOwned;
2994        break;
2995      }
2996
2997      // Fall-through.
2998
2999    case DoNothing:
3000      return state;
3001
3002    case Autorelease:
3003      if (C.isObjCGCEnabled())
3004        return state;
3005      // Update the autorelease counts.
3006      V = V.autorelease();
3007      break;
3008
3009    case StopTracking:
3010    case StopTrackingHard:
3011      return removeRefBinding(state, sym);
3012
3013    case IncRef:
3014      switch (V.getKind()) {
3015        default:
3016          llvm_unreachable("Invalid RefVal state for a retain.");
3017        case RefVal::Owned:
3018        case RefVal::NotOwned:
3019          V = V + 1;
3020          break;
3021        case RefVal::Released:
3022          // Non-GC cases are handled above.
3023          assert(C.isObjCGCEnabled());
3024          V = (V ^ RefVal::Owned) + 1;
3025          break;
3026      }
3027      break;
3028
3029    case DecRef:
3030    case DecRefBridgedTransfered:
3031    case DecRefAndStopTrackingHard:
3032      switch (V.getKind()) {
3033        default:
3034          // case 'RefVal::Released' handled above.
3035          llvm_unreachable("Invalid RefVal state for a release.");
3036
3037        case RefVal::Owned:
3038          assert(V.getCount() > 0);
3039          if (V.getCount() == 1)
3040            V = V ^ (E == DecRefBridgedTransfered ?
3041                      RefVal::NotOwned : RefVal::Released);
3042          else if (E == DecRefAndStopTrackingHard)
3043            return removeRefBinding(state, sym);
3044
3045          V = V - 1;
3046          break;
3047
3048        case RefVal::NotOwned:
3049          if (V.getCount() > 0) {
3050            if (E == DecRefAndStopTrackingHard)
3051              return removeRefBinding(state, sym);
3052            V = V - 1;
3053          } else {
3054            V = V ^ RefVal::ErrorReleaseNotOwned;
3055            hasErr = V.getKind();
3056          }
3057          break;
3058
3059        case RefVal::Released:
3060          // Non-GC cases are handled above.
3061          assert(C.isObjCGCEnabled());
3062          V = V ^ RefVal::ErrorUseAfterRelease;
3063          hasErr = V.getKind();
3064          break;
3065      }
3066      break;
3067  }
3068  return setRefBinding(state, sym, V);
3069}
3070
3071void RetainCountChecker::processNonLeakError(ProgramStateRef St,
3072                                             SourceRange ErrorRange,
3073                                             RefVal::Kind ErrorKind,
3074                                             SymbolRef Sym,
3075                                             CheckerContext &C) const {
3076  ExplodedNode *N = C.generateSink(St);
3077  if (!N)
3078    return;
3079
3080  CFRefBug *BT;
3081  switch (ErrorKind) {
3082    default:
3083      llvm_unreachable("Unhandled error.");
3084    case RefVal::ErrorUseAfterRelease:
3085      if (!useAfterRelease)
3086        useAfterRelease.reset(new UseAfterRelease());
3087      BT = &*useAfterRelease;
3088      break;
3089    case RefVal::ErrorReleaseNotOwned:
3090      if (!releaseNotOwned)
3091        releaseNotOwned.reset(new BadRelease());
3092      BT = &*releaseNotOwned;
3093      break;
3094    case RefVal::ErrorDeallocGC:
3095      if (!deallocGC)
3096        deallocGC.reset(new DeallocGC());
3097      BT = &*deallocGC;
3098      break;
3099    case RefVal::ErrorDeallocNotOwned:
3100      if (!deallocNotOwned)
3101        deallocNotOwned.reset(new DeallocNotOwned());
3102      BT = &*deallocNotOwned;
3103      break;
3104  }
3105
3106  assert(BT);
3107  CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
3108                                        C.isObjCGCEnabled(), SummaryLog,
3109                                        N, Sym);
3110  report->addRange(ErrorRange);
3111  C.emitReport(report);
3112}
3113
3114//===----------------------------------------------------------------------===//
3115// Handle the return values of retain-count-related functions.
3116//===----------------------------------------------------------------------===//
3117
3118bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
3119  // Get the callee. We're only interested in simple C functions.
3120  ProgramStateRef state = C.getState();
3121  const FunctionDecl *FD = C.getCalleeDecl(CE);
3122  if (!FD)
3123    return false;
3124
3125  IdentifierInfo *II = FD->getIdentifier();
3126  if (!II)
3127    return false;
3128
3129  // For now, we're only handling the functions that return aliases of their
3130  // arguments: CFRetain and CFMakeCollectable (and their families).
3131  // Eventually we should add other functions we can model entirely,
3132  // such as CFRelease, which don't invalidate their arguments or globals.
3133  if (CE->getNumArgs() != 1)
3134    return false;
3135
3136  // Get the name of the function.
3137  StringRef FName = II->getName();
3138  FName = FName.substr(FName.find_first_not_of('_'));
3139
3140  // See if it's one of the specific functions we know how to eval.
3141  bool canEval = false;
3142
3143  QualType ResultTy = CE->getCallReturnType();
3144  if (ResultTy->isObjCIdType()) {
3145    // Handle: id NSMakeCollectable(CFTypeRef)
3146    canEval = II->isStr("NSMakeCollectable");
3147  } else if (ResultTy->isPointerType()) {
3148    // Handle: (CF|CG)Retain
3149    //         CFMakeCollectable
3150    // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3151    if (cocoa::isRefType(ResultTy, "CF", FName) ||
3152        cocoa::isRefType(ResultTy, "CG", FName)) {
3153      canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3154    }
3155  }
3156
3157  if (!canEval)
3158    return false;
3159
3160  // Bind the return value.
3161  const LocationContext *LCtx = C.getLocationContext();
3162  SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
3163  if (RetVal.isUnknown()) {
3164    // If the receiver is unknown, conjure a return value.
3165    SValBuilder &SVB = C.getSValBuilder();
3166    RetVal = SVB.conjureSymbolVal(0, CE, LCtx, ResultTy, C.blockCount());
3167  }
3168  state = state->BindExpr(CE, LCtx, RetVal, false);
3169
3170  // FIXME: This should not be necessary, but otherwise the argument seems to be
3171  // considered alive during the next statement.
3172  if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3173    // Save the refcount status of the argument.
3174    SymbolRef Sym = RetVal.getAsLocSymbol();
3175    const RefVal *Binding = 0;
3176    if (Sym)
3177      Binding = getRefBinding(state, Sym);
3178
3179    // Invalidate the argument region.
3180    state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx);
3181
3182    // Restore the refcount status of the argument.
3183    if (Binding)
3184      state = setRefBinding(state, Sym, *Binding);
3185  }
3186
3187  C.addTransition(state);
3188  return true;
3189}
3190
3191//===----------------------------------------------------------------------===//
3192// Handle return statements.
3193//===----------------------------------------------------------------------===//
3194
3195// Return true if the current LocationContext has no caller context.
3196static bool inTopFrame(CheckerContext &C) {
3197  const LocationContext *LC = C.getLocationContext();
3198  return LC->getParent() == 0;
3199}
3200
3201void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3202                                      CheckerContext &C) const {
3203
3204  // Only adjust the reference count if this is the top-level call frame,
3205  // and not the result of inlining.  In the future, we should do
3206  // better checking even for inlined calls, and see if they match
3207  // with their expected semantics (e.g., the method should return a retained
3208  // object, etc.).
3209  if (!inTopFrame(C))
3210    return;
3211
3212  const Expr *RetE = S->getRetValue();
3213  if (!RetE)
3214    return;
3215
3216  ProgramStateRef state = C.getState();
3217  SymbolRef Sym =
3218    state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
3219  if (!Sym)
3220    return;
3221
3222  // Get the reference count binding (if any).
3223  const RefVal *T = getRefBinding(state, Sym);
3224  if (!T)
3225    return;
3226
3227  // Change the reference count.
3228  RefVal X = *T;
3229
3230  switch (X.getKind()) {
3231    case RefVal::Owned: {
3232      unsigned cnt = X.getCount();
3233      assert(cnt > 0);
3234      X.setCount(cnt - 1);
3235      X = X ^ RefVal::ReturnedOwned;
3236      break;
3237    }
3238
3239    case RefVal::NotOwned: {
3240      unsigned cnt = X.getCount();
3241      if (cnt) {
3242        X.setCount(cnt - 1);
3243        X = X ^ RefVal::ReturnedOwned;
3244      }
3245      else {
3246        X = X ^ RefVal::ReturnedNotOwned;
3247      }
3248      break;
3249    }
3250
3251    default:
3252      return;
3253  }
3254
3255  // Update the binding.
3256  state = setRefBinding(state, Sym, X);
3257  ExplodedNode *Pred = C.addTransition(state);
3258
3259  // At this point we have updated the state properly.
3260  // Everything after this is merely checking to see if the return value has
3261  // been over- or under-retained.
3262
3263  // Did we cache out?
3264  if (!Pred)
3265    return;
3266
3267  // Update the autorelease counts.
3268  static SimpleProgramPointTag
3269         AutoreleaseTag("RetainCountChecker : Autorelease");
3270  llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag,
3271                                                   C, Sym, X);
3272
3273  // Did we cache out?
3274  if (!Pred)
3275    return;
3276
3277  // Get the updated binding.
3278  T = getRefBinding(state, Sym);
3279  assert(T);
3280  X = *T;
3281
3282  // Consult the summary of the enclosing method.
3283  RetainSummaryManager &Summaries = getSummaryManager(C);
3284  const Decl *CD = &Pred->getCodeDecl();
3285  RetEffect RE = RetEffect::MakeNoRet();
3286
3287  // FIXME: What is the convention for blocks? Is there one?
3288  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
3289    const RetainSummary *Summ = Summaries.getMethodSummary(MD);
3290    RE = Summ->getRetEffect();
3291  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3292    if (!isa<CXXMethodDecl>(FD)) {
3293      const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3294      RE = Summ->getRetEffect();
3295    }
3296  }
3297
3298  checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
3299}
3300
3301void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3302                                                  CheckerContext &C,
3303                                                  ExplodedNode *Pred,
3304                                                  RetEffect RE, RefVal X,
3305                                                  SymbolRef Sym,
3306                                              ProgramStateRef state) const {
3307  // Any leaks or other errors?
3308  if (X.isReturnedOwned() && X.getCount() == 0) {
3309    if (RE.getKind() != RetEffect::NoRet) {
3310      bool hasError = false;
3311      if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3312        // Things are more complicated with garbage collection.  If the
3313        // returned object is suppose to be an Objective-C object, we have
3314        // a leak (as the caller expects a GC'ed object) because no
3315        // method should return ownership unless it returns a CF object.
3316        hasError = true;
3317        X = X ^ RefVal::ErrorGCLeakReturned;
3318      }
3319      else if (!RE.isOwned()) {
3320        // Either we are using GC and the returned object is a CF type
3321        // or we aren't using GC.  In either case, we expect that the
3322        // enclosing method is expected to return ownership.
3323        hasError = true;
3324        X = X ^ RefVal::ErrorLeakReturned;
3325      }
3326
3327      if (hasError) {
3328        // Generate an error node.
3329        state = setRefBinding(state, Sym, X);
3330
3331        static SimpleProgramPointTag
3332               ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
3333        ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
3334        if (N) {
3335          const LangOptions &LOpts = C.getASTContext().getLangOpts();
3336          bool GCEnabled = C.isObjCGCEnabled();
3337          CFRefReport *report =
3338            new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3339                                LOpts, GCEnabled, SummaryLog,
3340                                N, Sym, C);
3341          C.emitReport(report);
3342        }
3343      }
3344    }
3345  } else if (X.isReturnedNotOwned()) {
3346    if (RE.isOwned()) {
3347      // Trying to return a not owned object to a caller expecting an
3348      // owned object.
3349      state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
3350
3351      static SimpleProgramPointTag
3352             ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
3353      ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
3354      if (N) {
3355        if (!returnNotOwnedForOwned)
3356          returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3357
3358        CFRefReport *report =
3359            new CFRefReport(*returnNotOwnedForOwned,
3360                            C.getASTContext().getLangOpts(),
3361                            C.isObjCGCEnabled(), SummaryLog, N, Sym);
3362        C.emitReport(report);
3363      }
3364    }
3365  }
3366}
3367
3368//===----------------------------------------------------------------------===//
3369// Check various ways a symbol can be invalidated.
3370//===----------------------------------------------------------------------===//
3371
3372void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
3373                                   CheckerContext &C) const {
3374  // Are we storing to something that causes the value to "escape"?
3375  bool escapes = true;
3376
3377  // A value escapes in three possible cases (this may change):
3378  //
3379  // (1) we are binding to something that is not a memory region.
3380  // (2) we are binding to a memregion that does not have stack storage
3381  // (3) we are binding to a memregion with stack storage that the store
3382  //     does not understand.
3383  ProgramStateRef state = C.getState();
3384
3385  if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
3386    escapes = !regionLoc->getRegion()->hasStackStorage();
3387
3388    if (!escapes) {
3389      // To test (3), generate a new state with the binding added.  If it is
3390      // the same state, then it escapes (since the store cannot represent
3391      // the binding).
3392      // Do this only if we know that the store is not supposed to generate the
3393      // same state.
3394      SVal StoredVal = state->getSVal(regionLoc->getRegion());
3395      if (StoredVal != val)
3396        escapes = (state == (state->bindLoc(*regionLoc, val)));
3397    }
3398    if (!escapes) {
3399      // Case 4: We do not currently model what happens when a symbol is
3400      // assigned to a struct field, so be conservative here and let the symbol
3401      // go. TODO: This could definitely be improved upon.
3402      escapes = !isa<VarRegion>(regionLoc->getRegion());
3403    }
3404  }
3405
3406  // If our store can represent the binding and we aren't storing to something
3407  // that doesn't have local storage then just return and have the simulation
3408  // state continue as is.
3409  if (!escapes)
3410      return;
3411
3412  // Otherwise, find all symbols referenced by 'val' that we are tracking
3413  // and stop tracking them.
3414  state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
3415  C.addTransition(state);
3416}
3417
3418ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
3419                                                   SVal Cond,
3420                                                   bool Assumption) const {
3421
3422  // FIXME: We may add to the interface of evalAssume the list of symbols
3423  //  whose assumptions have changed.  For now we just iterate through the
3424  //  bindings and check if any of the tracked symbols are NULL.  This isn't
3425  //  too bad since the number of symbols we will track in practice are
3426  //  probably small and evalAssume is only called at branches and a few
3427  //  other places.
3428  RefBindingsTy B = state->get<RefBindings>();
3429
3430  if (B.isEmpty())
3431    return state;
3432
3433  bool changed = false;
3434  RefBindingsTy::Factory &RefBFactory = state->get_context<RefBindings>();
3435
3436  for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3437    // Check if the symbol is null stop tracking the symbol.
3438    ConstraintManager &CMgr = state->getConstraintManager();
3439    ConditionTruthVal AllocFailed = CMgr.isNull(state, I.getKey());
3440    if (AllocFailed.isConstrainedTrue()) {
3441      changed = true;
3442      B = RefBFactory.remove(B, I.getKey());
3443    }
3444  }
3445
3446  if (changed)
3447    state = state->set<RefBindings>(B);
3448
3449  return state;
3450}
3451
3452ProgramStateRef
3453RetainCountChecker::checkRegionChanges(ProgramStateRef state,
3454                            const StoreManager::InvalidatedSymbols *invalidated,
3455                                    ArrayRef<const MemRegion *> ExplicitRegions,
3456                                    ArrayRef<const MemRegion *> Regions,
3457                                    const CallEvent *Call) const {
3458  if (!invalidated)
3459    return state;
3460
3461  llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3462  for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3463       E = ExplicitRegions.end(); I != E; ++I) {
3464    if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3465      WhitelistedSymbols.insert(SR->getSymbol());
3466  }
3467
3468  for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
3469       E = invalidated->end(); I!=E; ++I) {
3470    SymbolRef sym = *I;
3471    if (WhitelistedSymbols.count(sym))
3472      continue;
3473    // Remove any existing reference-count binding.
3474    state = removeRefBinding(state, sym);
3475  }
3476  return state;
3477}
3478
3479//===----------------------------------------------------------------------===//
3480// Handle dead symbols and end-of-path.
3481//===----------------------------------------------------------------------===//
3482
3483std::pair<ExplodedNode *, ProgramStateRef >
3484RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
3485                                            ExplodedNode *Pred,
3486                                            const ProgramPointTag *Tag,
3487                                            CheckerContext &Ctx,
3488                                            SymbolRef Sym, RefVal V) const {
3489  unsigned ACnt = V.getAutoreleaseCount();
3490
3491  // No autorelease counts?  Nothing to be done.
3492  if (!ACnt)
3493    return std::make_pair(Pred, state);
3494
3495  assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
3496  unsigned Cnt = V.getCount();
3497
3498  // FIXME: Handle sending 'autorelease' to already released object.
3499
3500  if (V.getKind() == RefVal::ReturnedOwned)
3501    ++Cnt;
3502
3503  if (ACnt <= Cnt) {
3504    if (ACnt == Cnt) {
3505      V.clearCounts();
3506      if (V.getKind() == RefVal::ReturnedOwned)
3507        V = V ^ RefVal::ReturnedNotOwned;
3508      else
3509        V = V ^ RefVal::NotOwned;
3510    } else {
3511      V.setCount(Cnt - ACnt);
3512      V.setAutoreleaseCount(0);
3513    }
3514    state = setRefBinding(state, Sym, V);
3515    ExplodedNode *N = Ctx.addTransition(state, Pred, Tag);
3516    if (N == 0)
3517      state = 0;
3518    return std::make_pair(N, state);
3519  }
3520
3521  // Woah!  More autorelease counts then retain counts left.
3522  // Emit hard error.
3523  V = V ^ RefVal::ErrorOverAutorelease;
3524  state = setRefBinding(state, Sym, V);
3525
3526  ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
3527  if (N) {
3528    SmallString<128> sbuf;
3529    llvm::raw_svector_ostream os(sbuf);
3530    os << "Object over-autoreleased: object was sent -autorelease ";
3531    if (V.getAutoreleaseCount() > 1)
3532      os << V.getAutoreleaseCount() << " times ";
3533    os << "but the object has a +" << V.getCount() << " retain count";
3534
3535    if (!overAutorelease)
3536      overAutorelease.reset(new OverAutorelease());
3537
3538    const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3539    CFRefReport *report =
3540      new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3541                      SummaryLog, N, Sym, os.str());
3542    Ctx.emitReport(report);
3543  }
3544
3545  return std::make_pair((ExplodedNode *)0, (ProgramStateRef )0);
3546}
3547
3548ProgramStateRef
3549RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
3550                                      SymbolRef sid, RefVal V,
3551                                    SmallVectorImpl<SymbolRef> &Leaked) const {
3552  bool hasLeak = false;
3553  if (V.isOwned())
3554    hasLeak = true;
3555  else if (V.isNotOwned() || V.isReturnedOwned())
3556    hasLeak = (V.getCount() > 0);
3557
3558  if (!hasLeak)
3559    return removeRefBinding(state, sid);
3560
3561  Leaked.push_back(sid);
3562  return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
3563}
3564
3565ExplodedNode *
3566RetainCountChecker::processLeaks(ProgramStateRef state,
3567                                 SmallVectorImpl<SymbolRef> &Leaked,
3568                                 CheckerContext &Ctx,
3569                                 ExplodedNode *Pred) const {
3570  if (Leaked.empty())
3571    return Pred;
3572
3573  // Generate an intermediate node representing the leak point.
3574  ExplodedNode *N = Ctx.addTransition(state, Pred);
3575
3576  if (N) {
3577    for (SmallVectorImpl<SymbolRef>::iterator
3578         I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3579
3580      const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3581      bool GCEnabled = Ctx.isObjCGCEnabled();
3582      CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3583                          : getLeakAtReturnBug(LOpts, GCEnabled);
3584      assert(BT && "BugType not initialized.");
3585
3586      CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
3587                                                    SummaryLog, N, *I, Ctx);
3588      Ctx.emitReport(report);
3589    }
3590  }
3591
3592  return N;
3593}
3594
3595void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const {
3596  ProgramStateRef state = Ctx.getState();
3597  RefBindingsTy B = state->get<RefBindings>();
3598  ExplodedNode *Pred = Ctx.getPredecessor();
3599
3600  for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3601    llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Pred, /*Tag=*/0,
3602                                                     Ctx, I->first, I->second);
3603    if (!state)
3604      return;
3605  }
3606
3607  // If the current LocationContext has a parent, don't check for leaks.
3608  // We will do that later.
3609  // FIXME: we should instead check for imbalances of the retain/releases,
3610  // and suggest annotations.
3611  if (Ctx.getLocationContext()->getParent())
3612    return;
3613
3614  B = state->get<RefBindings>();
3615  SmallVector<SymbolRef, 10> Leaked;
3616
3617  for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I)
3618    state = handleSymbolDeath(state, I->first, I->second, Leaked);
3619
3620  processLeaks(state, Leaked, Ctx, Pred);
3621}
3622
3623const ProgramPointTag *
3624RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
3625  const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3626  if (!tag) {
3627    SmallString<64> buf;
3628    llvm::raw_svector_ostream out(buf);
3629    out << "RetainCountChecker : Dead Symbol : ";
3630    sym->dumpToStream(out);
3631    tag = new SimpleProgramPointTag(out.str());
3632  }
3633  return tag;
3634}
3635
3636void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3637                                          CheckerContext &C) const {
3638  ExplodedNode *Pred = C.getPredecessor();
3639
3640  ProgramStateRef state = C.getState();
3641  RefBindingsTy B = state->get<RefBindings>();
3642
3643  // Update counts from autorelease pools
3644  for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3645       E = SymReaper.dead_end(); I != E; ++I) {
3646    SymbolRef Sym = *I;
3647    if (const RefVal *T = B.lookup(Sym)){
3648      // Use the symbol as the tag.
3649      // FIXME: This might not be as unique as we would like.
3650      const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
3651      llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Pred, Tag, C,
3652                                                       Sym, *T);
3653      if (!state)
3654        return;
3655    }
3656  }
3657
3658  B = state->get<RefBindings>();
3659  SmallVector<SymbolRef, 10> Leaked;
3660
3661  for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3662       E = SymReaper.dead_end(); I != E; ++I) {
3663    if (const RefVal *T = B.lookup(*I))
3664      state = handleSymbolDeath(state, *I, *T, Leaked);
3665  }
3666
3667  Pred = processLeaks(state, Leaked, C, Pred);
3668
3669  // Did we cache out?
3670  if (!Pred)
3671    return;
3672
3673  // Now generate a new node that nukes the old bindings.
3674  RefBindingsTy::Factory &F = state->get_context<RefBindings>();
3675
3676  for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3677       E = SymReaper.dead_end(); I != E; ++I)
3678    B = F.remove(B, *I);
3679
3680  state = state->set<RefBindings>(B);
3681  C.addTransition(state, Pred);
3682}
3683
3684void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
3685                                    const char *NL, const char *Sep) const {
3686
3687  RefBindingsTy B = State->get<RefBindings>();
3688
3689  if (!B.isEmpty())
3690    Out << Sep << NL;
3691
3692  for (RefBindingsTy::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3693    Out << I->first << " : ";
3694    I->second.print(Out);
3695    Out << NL;
3696  }
3697}
3698
3699//===----------------------------------------------------------------------===//
3700// Checker registration.
3701//===----------------------------------------------------------------------===//
3702
3703void ento::registerRetainCountChecker(CheckerManager &Mgr) {
3704  Mgr.registerChecker<RetainCountChecker>();
3705}
3706
3707