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