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