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