RetainCountChecker.cpp revision a89f719ad3a7134e3eec7c9e03aa0e22031c0de9
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      IdentifierInfo *Name = FC->getDecl()->getIdentifier();
951
952      // This callback frees the associated buffer.
953      if (Name)
954        if (Name->isStr("CGBitmapContextCreateWithData"))
955          RE = S->getRetEffect();
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    if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2266      os << " is returned from a method whose name ('"
2267         << MD->getSelector().getAsString()
2268         << "') does not start with 'copy', 'mutableCopy', 'alloc' or 'new'."
2269            "  This violates the naming convention rules"
2270            " given in the Memory Management Guide for Cocoa";
2271    }
2272    else {
2273      const FunctionDecl *FD = cast<FunctionDecl>(D);
2274      os << " is returned from a function whose name ('"
2275         << *FD
2276         << "') does not contain 'Copy' or 'Create'.  This violates the naming"
2277            " convention rules given in the Memory Management Guide for Core"
2278            " Foundation";
2279    }
2280  }
2281  else if (RV->getKind() == RefVal::ErrorGCLeakReturned) {
2282    ObjCMethodDecl &MD = cast<ObjCMethodDecl>(EndN->getCodeDecl());
2283    os << " and returned from method '" << MD.getSelector().getAsString()
2284       << "' is potentially leaked when using garbage collection.  Callers "
2285          "of this method do not expect a returned object with a +1 retain "
2286          "count since they expect the object to be managed by the garbage "
2287          "collector";
2288  }
2289  else
2290    os << " is not referenced later in this execution path and has a retain "
2291          "count of +" << RV->getCount();
2292
2293  return new PathDiagnosticEventPiece(L, os.str());
2294}
2295
2296CFRefLeakReport::CFRefLeakReport(CFRefBug &D, const LangOptions &LOpts,
2297                                 bool GCEnabled, const SummaryLogTy &Log,
2298                                 ExplodedNode *n, SymbolRef sym,
2299                                 CheckerContext &Ctx)
2300: CFRefReport(D, LOpts, GCEnabled, Log, n, sym, false) {
2301
2302  // Most bug reports are cached at the location where they occurred.
2303  // With leaks, we want to unique them by the location where they were
2304  // allocated, and only report a single path.  To do this, we need to find
2305  // the allocation site of a piece of tracked memory, which we do via a
2306  // call to GetAllocationSite.  This will walk the ExplodedGraph backwards.
2307  // Note that this is *not* the trimmed graph; we are guaranteed, however,
2308  // that all ancestor nodes that represent the allocation site have the
2309  // same SourceLocation.
2310  const ExplodedNode *AllocNode = 0;
2311
2312  const SourceManager& SMgr = Ctx.getSourceManager();
2313
2314  llvm::tie(AllocNode, AllocBinding) =  // Set AllocBinding.
2315    GetAllocationSite(Ctx.getStateManager(), getErrorNode(), sym);
2316
2317  // Get the SourceLocation for the allocation site.
2318  // FIXME: This will crash the analyzer if an allocation comes from an
2319  // implicit call. (Currently there are no such allocations in Cocoa, though.)
2320  const Stmt *AllocStmt;
2321  ProgramPoint P = AllocNode->getLocation();
2322  if (CallExitEnd *Exit = dyn_cast<CallExitEnd>(&P))
2323    AllocStmt = Exit->getCalleeContext()->getCallSite();
2324  else
2325    AllocStmt = cast<PostStmt>(P).getStmt();
2326  assert(AllocStmt && "All allocations must come from explicit calls");
2327  Location = PathDiagnosticLocation::createBegin(AllocStmt, SMgr,
2328                                                  n->getLocationContext());
2329  // Fill in the description of the bug.
2330  Description.clear();
2331  llvm::raw_string_ostream os(Description);
2332  os << "Potential leak ";
2333  if (GCEnabled)
2334    os << "(when using garbage collection) ";
2335  os << "of an object";
2336
2337  // FIXME: AllocBinding doesn't get populated for RegionStore yet.
2338  if (AllocBinding)
2339    os << " stored into '" << AllocBinding->getString() << '\'';
2340
2341  addVisitor(new CFRefLeakReportVisitor(sym, GCEnabled, Log));
2342}
2343
2344//===----------------------------------------------------------------------===//
2345// Main checker logic.
2346//===----------------------------------------------------------------------===//
2347
2348namespace {
2349class RetainCountChecker
2350  : public Checker< check::Bind,
2351                    check::DeadSymbols,
2352                    check::EndAnalysis,
2353                    check::EndPath,
2354                    check::PostStmt<BlockExpr>,
2355                    check::PostStmt<CastExpr>,
2356                    check::PostStmt<ObjCArrayLiteral>,
2357                    check::PostStmt<ObjCDictionaryLiteral>,
2358                    check::PostStmt<ObjCBoxedExpr>,
2359                    check::PostCall,
2360                    check::PreStmt<ReturnStmt>,
2361                    check::RegionChanges,
2362                    eval::Assume,
2363                    eval::Call > {
2364  mutable OwningPtr<CFRefBug> useAfterRelease, releaseNotOwned;
2365  mutable OwningPtr<CFRefBug> deallocGC, deallocNotOwned;
2366  mutable OwningPtr<CFRefBug> overAutorelease, returnNotOwnedForOwned;
2367  mutable OwningPtr<CFRefBug> leakWithinFunction, leakAtReturn;
2368  mutable OwningPtr<CFRefBug> leakWithinFunctionGC, leakAtReturnGC;
2369
2370  typedef llvm::DenseMap<SymbolRef, const SimpleProgramPointTag *> SymbolTagMap;
2371
2372  // This map is only used to ensure proper deletion of any allocated tags.
2373  mutable SymbolTagMap DeadSymbolTags;
2374
2375  mutable OwningPtr<RetainSummaryManager> Summaries;
2376  mutable OwningPtr<RetainSummaryManager> SummariesGC;
2377  mutable SummaryLogTy SummaryLog;
2378  mutable bool ShouldResetSummaryLog;
2379
2380public:
2381  RetainCountChecker() : ShouldResetSummaryLog(false) {}
2382
2383  virtual ~RetainCountChecker() {
2384    DeleteContainerSeconds(DeadSymbolTags);
2385  }
2386
2387  void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
2388                        ExprEngine &Eng) const {
2389    // FIXME: This is a hack to make sure the summary log gets cleared between
2390    // analyses of different code bodies.
2391    //
2392    // Why is this necessary? Because a checker's lifetime is tied to a
2393    // translation unit, but an ExplodedGraph's lifetime is just a code body.
2394    // Once in a blue moon, a new ExplodedNode will have the same address as an
2395    // old one with an associated summary, and the bug report visitor gets very
2396    // confused. (To make things worse, the summary lifetime is currently also
2397    // tied to a code body, so we get a crash instead of incorrect results.)
2398    //
2399    // Why is this a bad solution? Because if the lifetime of the ExplodedGraph
2400    // changes, things will start going wrong again. Really the lifetime of this
2401    // log needs to be tied to either the specific nodes in it or the entire
2402    // ExplodedGraph, not to a specific part of the code being analyzed.
2403    //
2404    // (Also, having stateful local data means that the same checker can't be
2405    // used from multiple threads, but a lot of checkers have incorrect
2406    // assumptions about that anyway. So that wasn't a priority at the time of
2407    // this fix.)
2408    //
2409    // This happens at the end of analysis, but bug reports are emitted /after/
2410    // this point. So we can't just clear the summary log now. Instead, we mark
2411    // that the next time we access the summary log, it should be cleared.
2412
2413    // If we never reset the summary log during /this/ code body analysis,
2414    // there were no new summaries. There might still have been summaries from
2415    // the /last/ analysis, so clear them out to make sure the bug report
2416    // visitors don't get confused.
2417    if (ShouldResetSummaryLog)
2418      SummaryLog.clear();
2419
2420    ShouldResetSummaryLog = !SummaryLog.empty();
2421  }
2422
2423  CFRefBug *getLeakWithinFunctionBug(const LangOptions &LOpts,
2424                                     bool GCEnabled) const {
2425    if (GCEnabled) {
2426      if (!leakWithinFunctionGC)
2427        leakWithinFunctionGC.reset(new Leak("Leak of object when using "
2428                                             "garbage collection"));
2429      return leakWithinFunctionGC.get();
2430    } else {
2431      if (!leakWithinFunction) {
2432        if (LOpts.getGC() == LangOptions::HybridGC) {
2433          leakWithinFunction.reset(new Leak("Leak of object when not using "
2434                                            "garbage collection (GC) in "
2435                                            "dual GC/non-GC code"));
2436        } else {
2437          leakWithinFunction.reset(new Leak("Leak"));
2438        }
2439      }
2440      return leakWithinFunction.get();
2441    }
2442  }
2443
2444  CFRefBug *getLeakAtReturnBug(const LangOptions &LOpts, bool GCEnabled) const {
2445    if (GCEnabled) {
2446      if (!leakAtReturnGC)
2447        leakAtReturnGC.reset(new Leak("Leak of returned object when using "
2448                                      "garbage collection"));
2449      return leakAtReturnGC.get();
2450    } else {
2451      if (!leakAtReturn) {
2452        if (LOpts.getGC() == LangOptions::HybridGC) {
2453          leakAtReturn.reset(new Leak("Leak of returned object when not using "
2454                                      "garbage collection (GC) in dual "
2455                                      "GC/non-GC code"));
2456        } else {
2457          leakAtReturn.reset(new Leak("Leak of returned object"));
2458        }
2459      }
2460      return leakAtReturn.get();
2461    }
2462  }
2463
2464  RetainSummaryManager &getSummaryManager(ASTContext &Ctx,
2465                                          bool GCEnabled) const {
2466    // FIXME: We don't support ARC being turned on and off during one analysis.
2467    // (nor, for that matter, do we support changing ASTContexts)
2468    bool ARCEnabled = (bool)Ctx.getLangOpts().ObjCAutoRefCount;
2469    if (GCEnabled) {
2470      if (!SummariesGC)
2471        SummariesGC.reset(new RetainSummaryManager(Ctx, true, ARCEnabled));
2472      else
2473        assert(SummariesGC->isARCEnabled() == ARCEnabled);
2474      return *SummariesGC;
2475    } else {
2476      if (!Summaries)
2477        Summaries.reset(new RetainSummaryManager(Ctx, false, ARCEnabled));
2478      else
2479        assert(Summaries->isARCEnabled() == ARCEnabled);
2480      return *Summaries;
2481    }
2482  }
2483
2484  RetainSummaryManager &getSummaryManager(CheckerContext &C) const {
2485    return getSummaryManager(C.getASTContext(), C.isObjCGCEnabled());
2486  }
2487
2488  void printState(raw_ostream &Out, ProgramStateRef State,
2489                  const char *NL, const char *Sep) const;
2490
2491  void checkBind(SVal loc, SVal val, const Stmt *S, CheckerContext &C) const;
2492  void checkPostStmt(const BlockExpr *BE, CheckerContext &C) const;
2493  void checkPostStmt(const CastExpr *CE, CheckerContext &C) const;
2494
2495  void checkPostStmt(const ObjCArrayLiteral *AL, CheckerContext &C) const;
2496  void checkPostStmt(const ObjCDictionaryLiteral *DL, CheckerContext &C) const;
2497  void checkPostStmt(const ObjCBoxedExpr *BE, CheckerContext &C) const;
2498
2499  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
2500
2501  void checkSummary(const RetainSummary &Summ, const CallEvent &Call,
2502                    CheckerContext &C) const;
2503
2504  void processSummaryOfInlined(const RetainSummary &Summ,
2505                               const CallEvent &Call,
2506                               CheckerContext &C) const;
2507
2508  bool evalCall(const CallExpr *CE, CheckerContext &C) const;
2509
2510  ProgramStateRef evalAssume(ProgramStateRef state, SVal Cond,
2511                                 bool Assumption) const;
2512
2513  ProgramStateRef
2514  checkRegionChanges(ProgramStateRef state,
2515                     const StoreManager::InvalidatedSymbols *invalidated,
2516                     ArrayRef<const MemRegion *> ExplicitRegions,
2517                     ArrayRef<const MemRegion *> Regions,
2518                     const CallEvent *Call) const;
2519
2520  bool wantsRegionChangeUpdate(ProgramStateRef state) const {
2521    return true;
2522  }
2523
2524  void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
2525  void checkReturnWithRetEffect(const ReturnStmt *S, CheckerContext &C,
2526                                ExplodedNode *Pred, RetEffect RE, RefVal X,
2527                                SymbolRef Sym, ProgramStateRef state) const;
2528
2529  void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
2530  void checkEndPath(CheckerContext &C) const;
2531
2532  ProgramStateRef updateSymbol(ProgramStateRef state, SymbolRef sym,
2533                               RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2534                               CheckerContext &C) const;
2535
2536  void processNonLeakError(ProgramStateRef St, SourceRange ErrorRange,
2537                           RefVal::Kind ErrorKind, SymbolRef Sym,
2538                           CheckerContext &C) const;
2539
2540  void processObjCLiterals(CheckerContext &C, const Expr *Ex) const;
2541
2542  const ProgramPointTag *getDeadSymbolTag(SymbolRef sym) const;
2543
2544  ProgramStateRef handleSymbolDeath(ProgramStateRef state,
2545                                    SymbolRef sid, RefVal V,
2546                                    SmallVectorImpl<SymbolRef> &Leaked) const;
2547
2548  std::pair<ExplodedNode *, ProgramStateRef >
2549  handleAutoreleaseCounts(ProgramStateRef state, ExplodedNode *Pred,
2550                          const ProgramPointTag *Tag, CheckerContext &Ctx,
2551                          SymbolRef Sym, RefVal V) const;
2552
2553  ExplodedNode *processLeaks(ProgramStateRef state,
2554                             SmallVectorImpl<SymbolRef> &Leaked,
2555                             CheckerContext &Ctx,
2556                             ExplodedNode *Pred = 0) const;
2557};
2558} // end anonymous namespace
2559
2560namespace {
2561class StopTrackingCallback : public SymbolVisitor {
2562  ProgramStateRef state;
2563public:
2564  StopTrackingCallback(ProgramStateRef st) : state(st) {}
2565  ProgramStateRef getState() const { return state; }
2566
2567  bool VisitSymbol(SymbolRef sym) {
2568    state = state->remove<RefBindings>(sym);
2569    return true;
2570  }
2571};
2572} // end anonymous namespace
2573
2574//===----------------------------------------------------------------------===//
2575// Handle statements that may have an effect on refcounts.
2576//===----------------------------------------------------------------------===//
2577
2578void RetainCountChecker::checkPostStmt(const BlockExpr *BE,
2579                                       CheckerContext &C) const {
2580
2581  // Scan the BlockDecRefExprs for any object the retain count checker
2582  // may be tracking.
2583  if (!BE->getBlockDecl()->hasCaptures())
2584    return;
2585
2586  ProgramStateRef state = C.getState();
2587  const BlockDataRegion *R =
2588    cast<BlockDataRegion>(state->getSVal(BE,
2589                                         C.getLocationContext()).getAsRegion());
2590
2591  BlockDataRegion::referenced_vars_iterator I = R->referenced_vars_begin(),
2592                                            E = R->referenced_vars_end();
2593
2594  if (I == E)
2595    return;
2596
2597  // FIXME: For now we invalidate the tracking of all symbols passed to blocks
2598  // via captured variables, even though captured variables result in a copy
2599  // and in implicit increment/decrement of a retain count.
2600  SmallVector<const MemRegion*, 10> Regions;
2601  const LocationContext *LC = C.getLocationContext();
2602  MemRegionManager &MemMgr = C.getSValBuilder().getRegionManager();
2603
2604  for ( ; I != E; ++I) {
2605    const VarRegion *VR = *I;
2606    if (VR->getSuperRegion() == R) {
2607      VR = MemMgr.getVarRegion(VR->getDecl(), LC);
2608    }
2609    Regions.push_back(VR);
2610  }
2611
2612  state =
2613    state->scanReachableSymbols<StopTrackingCallback>(Regions.data(),
2614                                    Regions.data() + Regions.size()).getState();
2615  C.addTransition(state);
2616}
2617
2618void RetainCountChecker::checkPostStmt(const CastExpr *CE,
2619                                       CheckerContext &C) const {
2620  const ObjCBridgedCastExpr *BE = dyn_cast<ObjCBridgedCastExpr>(CE);
2621  if (!BE)
2622    return;
2623
2624  ArgEffect AE = IncRef;
2625
2626  switch (BE->getBridgeKind()) {
2627    case clang::OBC_Bridge:
2628      // Do nothing.
2629      return;
2630    case clang::OBC_BridgeRetained:
2631      AE = IncRef;
2632      break;
2633    case clang::OBC_BridgeTransfer:
2634      AE = DecRefBridgedTransfered;
2635      break;
2636  }
2637
2638  ProgramStateRef state = C.getState();
2639  SymbolRef Sym = state->getSVal(CE, C.getLocationContext()).getAsLocSymbol();
2640  if (!Sym)
2641    return;
2642  const RefVal* T = getRefBinding(state, Sym);
2643  if (!T)
2644    return;
2645
2646  RefVal::Kind hasErr = (RefVal::Kind) 0;
2647  state = updateSymbol(state, Sym, *T, AE, hasErr, C);
2648
2649  if (hasErr) {
2650    // FIXME: If we get an error during a bridge cast, should we report it?
2651    // Should we assert that there is no error?
2652    return;
2653  }
2654
2655  C.addTransition(state);
2656}
2657
2658void RetainCountChecker::processObjCLiterals(CheckerContext &C,
2659                                             const Expr *Ex) const {
2660  ProgramStateRef state = C.getState();
2661  const ExplodedNode *pred = C.getPredecessor();
2662  for (Stmt::const_child_iterator it = Ex->child_begin(), et = Ex->child_end() ;
2663       it != et ; ++it) {
2664    const Stmt *child = *it;
2665    SVal V = state->getSVal(child, pred->getLocationContext());
2666    if (SymbolRef sym = V.getAsSymbol())
2667      if (const RefVal* T = getRefBinding(state, sym)) {
2668        RefVal::Kind hasErr = (RefVal::Kind) 0;
2669        state = updateSymbol(state, sym, *T, MayEscape, hasErr, C);
2670        if (hasErr) {
2671          processNonLeakError(state, child->getSourceRange(), hasErr, sym, C);
2672          return;
2673        }
2674      }
2675  }
2676
2677  // Return the object as autoreleased.
2678  //  RetEffect RE = RetEffect::MakeNotOwned(RetEffect::ObjC);
2679  if (SymbolRef sym =
2680        state->getSVal(Ex, pred->getLocationContext()).getAsSymbol()) {
2681    QualType ResultTy = Ex->getType();
2682    state = setRefBinding(state, sym,
2683                          RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
2684  }
2685
2686  C.addTransition(state);
2687}
2688
2689void RetainCountChecker::checkPostStmt(const ObjCArrayLiteral *AL,
2690                                       CheckerContext &C) const {
2691  // Apply the 'MayEscape' to all values.
2692  processObjCLiterals(C, AL);
2693}
2694
2695void RetainCountChecker::checkPostStmt(const ObjCDictionaryLiteral *DL,
2696                                       CheckerContext &C) const {
2697  // Apply the 'MayEscape' to all keys and values.
2698  processObjCLiterals(C, DL);
2699}
2700
2701void RetainCountChecker::checkPostStmt(const ObjCBoxedExpr *Ex,
2702                                       CheckerContext &C) const {
2703  const ExplodedNode *Pred = C.getPredecessor();
2704  const LocationContext *LCtx = Pred->getLocationContext();
2705  ProgramStateRef State = Pred->getState();
2706
2707  if (SymbolRef Sym = State->getSVal(Ex, LCtx).getAsSymbol()) {
2708    QualType ResultTy = Ex->getType();
2709    State = setRefBinding(State, Sym,
2710                          RefVal::makeNotOwned(RetEffect::ObjC, ResultTy));
2711  }
2712
2713  C.addTransition(State);
2714}
2715
2716void RetainCountChecker::checkPostCall(const CallEvent &Call,
2717                                       CheckerContext &C) const {
2718  RetainSummaryManager &Summaries = getSummaryManager(C);
2719  const RetainSummary *Summ = Summaries.getSummary(Call, C.getState());
2720
2721  if (C.wasInlined) {
2722    processSummaryOfInlined(*Summ, Call, C);
2723    return;
2724  }
2725  checkSummary(*Summ, Call, C);
2726}
2727
2728/// GetReturnType - Used to get the return type of a message expression or
2729///  function call with the intention of affixing that type to a tracked symbol.
2730///  While the return type can be queried directly from RetEx, when
2731///  invoking class methods we augment to the return type to be that of
2732///  a pointer to the class (as opposed it just being id).
2733// FIXME: We may be able to do this with related result types instead.
2734// This function is probably overestimating.
2735static QualType GetReturnType(const Expr *RetE, ASTContext &Ctx) {
2736  QualType RetTy = RetE->getType();
2737  // If RetE is not a message expression just return its type.
2738  // If RetE is a message expression, return its types if it is something
2739  /// more specific than id.
2740  if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RetE))
2741    if (const ObjCObjectPointerType *PT = RetTy->getAs<ObjCObjectPointerType>())
2742      if (PT->isObjCQualifiedIdType() || PT->isObjCIdType() ||
2743          PT->isObjCClassType()) {
2744        // At this point we know the return type of the message expression is
2745        // id, id<...>, or Class. If we have an ObjCInterfaceDecl, we know this
2746        // is a call to a class method whose type we can resolve.  In such
2747        // cases, promote the return type to XXX* (where XXX is the class).
2748        const ObjCInterfaceDecl *D = ME->getReceiverInterface();
2749        return !D ? RetTy :
2750                    Ctx.getObjCObjectPointerType(Ctx.getObjCInterfaceType(D));
2751      }
2752
2753  return RetTy;
2754}
2755
2756// We don't always get the exact modeling of the function with regards to the
2757// retain count checker even when the function is inlined. For example, we need
2758// to stop tracking the symbols which were marked with StopTrackingHard.
2759void RetainCountChecker::processSummaryOfInlined(const RetainSummary &Summ,
2760                                                 const CallEvent &CallOrMsg,
2761                                                 CheckerContext &C) const {
2762  ProgramStateRef state = C.getState();
2763
2764  // Evaluate the effect of the arguments.
2765  for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2766    if (Summ.getArg(idx) == StopTrackingHard) {
2767      SVal V = CallOrMsg.getArgSVal(idx);
2768      if (SymbolRef Sym = V.getAsLocSymbol()) {
2769        state = removeRefBinding(state, Sym);
2770      }
2771    }
2772  }
2773
2774  // Evaluate the effect on the message receiver.
2775  const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2776  if (MsgInvocation) {
2777    if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2778      if (Summ.getReceiverEffect() == StopTrackingHard) {
2779        state = removeRefBinding(state, Sym);
2780      }
2781    }
2782  }
2783
2784  // Consult the summary for the return value.
2785  RetEffect RE = Summ.getRetEffect();
2786  if (RE.getKind() == RetEffect::NoRetHard) {
2787    SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(),
2788        C.getLocationContext()).getAsSymbol();
2789    if (Sym)
2790      state = removeRefBinding(state, Sym);
2791  }
2792
2793  C.addTransition(state);
2794}
2795
2796void RetainCountChecker::checkSummary(const RetainSummary &Summ,
2797                                      const CallEvent &CallOrMsg,
2798                                      CheckerContext &C) const {
2799  ProgramStateRef state = C.getState();
2800
2801  // Evaluate the effect of the arguments.
2802  RefVal::Kind hasErr = (RefVal::Kind) 0;
2803  SourceRange ErrorRange;
2804  SymbolRef ErrorSym = 0;
2805
2806  for (unsigned idx = 0, e = CallOrMsg.getNumArgs(); idx != e; ++idx) {
2807    SVal V = CallOrMsg.getArgSVal(idx);
2808
2809    if (SymbolRef Sym = V.getAsLocSymbol()) {
2810      if (const RefVal *T = getRefBinding(state, Sym)) {
2811        state = updateSymbol(state, Sym, *T, Summ.getArg(idx), hasErr, C);
2812        if (hasErr) {
2813          ErrorRange = CallOrMsg.getArgSourceRange(idx);
2814          ErrorSym = Sym;
2815          break;
2816        }
2817      }
2818    }
2819  }
2820
2821  // Evaluate the effect on the message receiver.
2822  bool ReceiverIsTracked = false;
2823  if (!hasErr) {
2824    const ObjCMethodCall *MsgInvocation = dyn_cast<ObjCMethodCall>(&CallOrMsg);
2825    if (MsgInvocation) {
2826      if (SymbolRef Sym = MsgInvocation->getReceiverSVal().getAsLocSymbol()) {
2827        if (const RefVal *T = getRefBinding(state, Sym)) {
2828          ReceiverIsTracked = true;
2829          state = updateSymbol(state, Sym, *T, Summ.getReceiverEffect(),
2830                                 hasErr, C);
2831          if (hasErr) {
2832            ErrorRange = MsgInvocation->getOriginExpr()->getReceiverRange();
2833            ErrorSym = Sym;
2834          }
2835        }
2836      }
2837    }
2838  }
2839
2840  // Process any errors.
2841  if (hasErr) {
2842    processNonLeakError(state, ErrorRange, hasErr, ErrorSym, C);
2843    return;
2844  }
2845
2846  // Consult the summary for the return value.
2847  RetEffect RE = Summ.getRetEffect();
2848
2849  if (RE.getKind() == RetEffect::OwnedWhenTrackedReceiver) {
2850    if (ReceiverIsTracked)
2851      RE = getSummaryManager(C).getObjAllocRetEffect();
2852    else
2853      RE = RetEffect::MakeNoRet();
2854  }
2855
2856  switch (RE.getKind()) {
2857    default:
2858      llvm_unreachable("Unhandled RetEffect.");
2859
2860    case RetEffect::NoRet:
2861    case RetEffect::NoRetHard:
2862      // No work necessary.
2863      break;
2864
2865    case RetEffect::OwnedAllocatedSymbol:
2866    case RetEffect::OwnedSymbol: {
2867      SymbolRef Sym = state->getSVal(CallOrMsg.getOriginExpr(),
2868                                     C.getLocationContext()).getAsSymbol();
2869      if (!Sym)
2870        break;
2871
2872      // Use the result type from the CallEvent as it automatically adjusts
2873      // for methods/functions that return references.
2874      QualType ResultTy = CallOrMsg.getResultType();
2875      state = setRefBinding(state, Sym, RefVal::makeOwned(RE.getObjKind(),
2876                                                          ResultTy));
2877
2878      // FIXME: Add a flag to the checker where allocations are assumed to
2879      // *not* fail.
2880      break;
2881    }
2882
2883    case RetEffect::GCNotOwnedSymbol:
2884    case RetEffect::ARCNotOwnedSymbol:
2885    case RetEffect::NotOwnedSymbol: {
2886      const Expr *Ex = CallOrMsg.getOriginExpr();
2887      SymbolRef Sym = state->getSVal(Ex, C.getLocationContext()).getAsSymbol();
2888      if (!Sym)
2889        break;
2890
2891      // Use GetReturnType in order to give [NSFoo alloc] the type NSFoo *.
2892      QualType ResultTy = GetReturnType(Ex, C.getASTContext());
2893      state = setRefBinding(state, Sym, RefVal::makeNotOwned(RE.getObjKind(),
2894                                                             ResultTy));
2895      break;
2896    }
2897  }
2898
2899  // This check is actually necessary; otherwise the statement builder thinks
2900  // we've hit a previously-found path.
2901  // Normally addTransition takes care of this, but we want the node pointer.
2902  ExplodedNode *NewNode;
2903  if (state == C.getState()) {
2904    NewNode = C.getPredecessor();
2905  } else {
2906    NewNode = C.addTransition(state);
2907  }
2908
2909  // Annotate the node with summary we used.
2910  if (NewNode) {
2911    // FIXME: This is ugly. See checkEndAnalysis for why it's necessary.
2912    if (ShouldResetSummaryLog) {
2913      SummaryLog.clear();
2914      ShouldResetSummaryLog = false;
2915    }
2916    SummaryLog[NewNode] = &Summ;
2917  }
2918}
2919
2920
2921ProgramStateRef
2922RetainCountChecker::updateSymbol(ProgramStateRef state, SymbolRef sym,
2923                                 RefVal V, ArgEffect E, RefVal::Kind &hasErr,
2924                                 CheckerContext &C) const {
2925  // In GC mode [... release] and [... retain] do nothing.
2926  // In ARC mode they shouldn't exist at all, but we just ignore them.
2927  bool IgnoreRetainMsg = C.isObjCGCEnabled();
2928  if (!IgnoreRetainMsg)
2929    IgnoreRetainMsg = (bool)C.getASTContext().getLangOpts().ObjCAutoRefCount;
2930
2931  switch (E) {
2932  default:
2933    break;
2934  case IncRefMsg:
2935    E = IgnoreRetainMsg ? DoNothing : IncRef;
2936    break;
2937  case DecRefMsg:
2938    E = IgnoreRetainMsg ? DoNothing : DecRef;
2939    break;
2940  case DecRefMsgAndStopTrackingHard:
2941    E = IgnoreRetainMsg ? StopTracking : DecRefAndStopTrackingHard;
2942    break;
2943  case MakeCollectable:
2944    E = C.isObjCGCEnabled() ? DecRef : DoNothing;
2945    break;
2946  case NewAutoreleasePool:
2947    E = C.isObjCGCEnabled() ? DoNothing : NewAutoreleasePool;
2948    break;
2949  }
2950
2951  // Handle all use-after-releases.
2952  if (!C.isObjCGCEnabled() && V.getKind() == RefVal::Released) {
2953    V = V ^ RefVal::ErrorUseAfterRelease;
2954    hasErr = V.getKind();
2955    return setRefBinding(state, sym, V);
2956  }
2957
2958  switch (E) {
2959    case DecRefMsg:
2960    case IncRefMsg:
2961    case MakeCollectable:
2962    case DecRefMsgAndStopTrackingHard:
2963      llvm_unreachable("DecRefMsg/IncRefMsg/MakeCollectable already converted");
2964
2965    case Dealloc:
2966      // Any use of -dealloc in GC is *bad*.
2967      if (C.isObjCGCEnabled()) {
2968        V = V ^ RefVal::ErrorDeallocGC;
2969        hasErr = V.getKind();
2970        break;
2971      }
2972
2973      switch (V.getKind()) {
2974        default:
2975          llvm_unreachable("Invalid RefVal state for an explicit dealloc.");
2976        case RefVal::Owned:
2977          // The object immediately transitions to the released state.
2978          V = V ^ RefVal::Released;
2979          V.clearCounts();
2980          return setRefBinding(state, sym, V);
2981        case RefVal::NotOwned:
2982          V = V ^ RefVal::ErrorDeallocNotOwned;
2983          hasErr = V.getKind();
2984          break;
2985      }
2986      break;
2987
2988    case NewAutoreleasePool:
2989      assert(!C.isObjCGCEnabled());
2990      return state;
2991
2992    case MayEscape:
2993      if (V.getKind() == RefVal::Owned) {
2994        V = V ^ RefVal::NotOwned;
2995        break;
2996      }
2997
2998      // Fall-through.
2999
3000    case DoNothing:
3001      return state;
3002
3003    case Autorelease:
3004      if (C.isObjCGCEnabled())
3005        return state;
3006      // Update the autorelease counts.
3007      V = V.autorelease();
3008      break;
3009
3010    case StopTracking:
3011    case StopTrackingHard:
3012      return removeRefBinding(state, sym);
3013
3014    case IncRef:
3015      switch (V.getKind()) {
3016        default:
3017          llvm_unreachable("Invalid RefVal state for a retain.");
3018        case RefVal::Owned:
3019        case RefVal::NotOwned:
3020          V = V + 1;
3021          break;
3022        case RefVal::Released:
3023          // Non-GC cases are handled above.
3024          assert(C.isObjCGCEnabled());
3025          V = (V ^ RefVal::Owned) + 1;
3026          break;
3027      }
3028      break;
3029
3030    case DecRef:
3031    case DecRefBridgedTransfered:
3032    case DecRefAndStopTrackingHard:
3033      switch (V.getKind()) {
3034        default:
3035          // case 'RefVal::Released' handled above.
3036          llvm_unreachable("Invalid RefVal state for a release.");
3037
3038        case RefVal::Owned:
3039          assert(V.getCount() > 0);
3040          if (V.getCount() == 1)
3041            V = V ^ (E == DecRefBridgedTransfered ?
3042                      RefVal::NotOwned : RefVal::Released);
3043          else if (E == DecRefAndStopTrackingHard)
3044            return removeRefBinding(state, sym);
3045
3046          V = V - 1;
3047          break;
3048
3049        case RefVal::NotOwned:
3050          if (V.getCount() > 0) {
3051            if (E == DecRefAndStopTrackingHard)
3052              return removeRefBinding(state, sym);
3053            V = V - 1;
3054          } else {
3055            V = V ^ RefVal::ErrorReleaseNotOwned;
3056            hasErr = V.getKind();
3057          }
3058          break;
3059
3060        case RefVal::Released:
3061          // Non-GC cases are handled above.
3062          assert(C.isObjCGCEnabled());
3063          V = V ^ RefVal::ErrorUseAfterRelease;
3064          hasErr = V.getKind();
3065          break;
3066      }
3067      break;
3068  }
3069  return setRefBinding(state, sym, V);
3070}
3071
3072void RetainCountChecker::processNonLeakError(ProgramStateRef St,
3073                                             SourceRange ErrorRange,
3074                                             RefVal::Kind ErrorKind,
3075                                             SymbolRef Sym,
3076                                             CheckerContext &C) const {
3077  ExplodedNode *N = C.generateSink(St);
3078  if (!N)
3079    return;
3080
3081  CFRefBug *BT;
3082  switch (ErrorKind) {
3083    default:
3084      llvm_unreachable("Unhandled error.");
3085    case RefVal::ErrorUseAfterRelease:
3086      if (!useAfterRelease)
3087        useAfterRelease.reset(new UseAfterRelease());
3088      BT = &*useAfterRelease;
3089      break;
3090    case RefVal::ErrorReleaseNotOwned:
3091      if (!releaseNotOwned)
3092        releaseNotOwned.reset(new BadRelease());
3093      BT = &*releaseNotOwned;
3094      break;
3095    case RefVal::ErrorDeallocGC:
3096      if (!deallocGC)
3097        deallocGC.reset(new DeallocGC());
3098      BT = &*deallocGC;
3099      break;
3100    case RefVal::ErrorDeallocNotOwned:
3101      if (!deallocNotOwned)
3102        deallocNotOwned.reset(new DeallocNotOwned());
3103      BT = &*deallocNotOwned;
3104      break;
3105  }
3106
3107  assert(BT);
3108  CFRefReport *report = new CFRefReport(*BT, C.getASTContext().getLangOpts(),
3109                                        C.isObjCGCEnabled(), SummaryLog,
3110                                        N, Sym);
3111  report->addRange(ErrorRange);
3112  C.EmitReport(report);
3113}
3114
3115//===----------------------------------------------------------------------===//
3116// Handle the return values of retain-count-related functions.
3117//===----------------------------------------------------------------------===//
3118
3119bool RetainCountChecker::evalCall(const CallExpr *CE, CheckerContext &C) const {
3120  // Get the callee. We're only interested in simple C functions.
3121  ProgramStateRef state = C.getState();
3122  const FunctionDecl *FD = C.getCalleeDecl(CE);
3123  if (!FD)
3124    return false;
3125
3126  IdentifierInfo *II = FD->getIdentifier();
3127  if (!II)
3128    return false;
3129
3130  // For now, we're only handling the functions that return aliases of their
3131  // arguments: CFRetain and CFMakeCollectable (and their families).
3132  // Eventually we should add other functions we can model entirely,
3133  // such as CFRelease, which don't invalidate their arguments or globals.
3134  if (CE->getNumArgs() != 1)
3135    return false;
3136
3137  // Get the name of the function.
3138  StringRef FName = II->getName();
3139  FName = FName.substr(FName.find_first_not_of('_'));
3140
3141  // See if it's one of the specific functions we know how to eval.
3142  bool canEval = false;
3143
3144  QualType ResultTy = CE->getCallReturnType();
3145  if (ResultTy->isObjCIdType()) {
3146    // Handle: id NSMakeCollectable(CFTypeRef)
3147    canEval = II->isStr("NSMakeCollectable");
3148  } else if (ResultTy->isPointerType()) {
3149    // Handle: (CF|CG)Retain
3150    //         CFMakeCollectable
3151    // It's okay to be a little sloppy here (CGMakeCollectable doesn't exist).
3152    if (cocoa::isRefType(ResultTy, "CF", FName) ||
3153        cocoa::isRefType(ResultTy, "CG", FName)) {
3154      canEval = isRetain(FD, FName) || isMakeCollectable(FD, FName);
3155    }
3156  }
3157
3158  if (!canEval)
3159    return false;
3160
3161  // Bind the return value.
3162  const LocationContext *LCtx = C.getLocationContext();
3163  SVal RetVal = state->getSVal(CE->getArg(0), LCtx);
3164  if (RetVal.isUnknown()) {
3165    // If the receiver is unknown, conjure a return value.
3166    SValBuilder &SVB = C.getSValBuilder();
3167    RetVal = SVB.conjureSymbolVal(0, CE, LCtx, ResultTy, C.blockCount());
3168  }
3169  state = state->BindExpr(CE, LCtx, RetVal, false);
3170
3171  // FIXME: This should not be necessary, but otherwise the argument seems to be
3172  // considered alive during the next statement.
3173  if (const MemRegion *ArgRegion = RetVal.getAsRegion()) {
3174    // Save the refcount status of the argument.
3175    SymbolRef Sym = RetVal.getAsLocSymbol();
3176    const RefVal *Binding = 0;
3177    if (Sym)
3178      Binding = getRefBinding(state, Sym);
3179
3180    // Invalidate the argument region.
3181    state = state->invalidateRegions(ArgRegion, CE, C.blockCount(), LCtx);
3182
3183    // Restore the refcount status of the argument.
3184    if (Binding)
3185      state = setRefBinding(state, Sym, *Binding);
3186  }
3187
3188  C.addTransition(state);
3189  return true;
3190}
3191
3192//===----------------------------------------------------------------------===//
3193// Handle return statements.
3194//===----------------------------------------------------------------------===//
3195
3196// Return true if the current LocationContext has no caller context.
3197static bool inTopFrame(CheckerContext &C) {
3198  const LocationContext *LC = C.getLocationContext();
3199  return LC->getParent() == 0;
3200}
3201
3202void RetainCountChecker::checkPreStmt(const ReturnStmt *S,
3203                                      CheckerContext &C) const {
3204
3205  // Only adjust the reference count if this is the top-level call frame,
3206  // and not the result of inlining.  In the future, we should do
3207  // better checking even for inlined calls, and see if they match
3208  // with their expected semantics (e.g., the method should return a retained
3209  // object, etc.).
3210  if (!inTopFrame(C))
3211    return;
3212
3213  const Expr *RetE = S->getRetValue();
3214  if (!RetE)
3215    return;
3216
3217  ProgramStateRef state = C.getState();
3218  SymbolRef Sym =
3219    state->getSValAsScalarOrLoc(RetE, C.getLocationContext()).getAsLocSymbol();
3220  if (!Sym)
3221    return;
3222
3223  // Get the reference count binding (if any).
3224  const RefVal *T = getRefBinding(state, Sym);
3225  if (!T)
3226    return;
3227
3228  // Change the reference count.
3229  RefVal X = *T;
3230
3231  switch (X.getKind()) {
3232    case RefVal::Owned: {
3233      unsigned cnt = X.getCount();
3234      assert(cnt > 0);
3235      X.setCount(cnt - 1);
3236      X = X ^ RefVal::ReturnedOwned;
3237      break;
3238    }
3239
3240    case RefVal::NotOwned: {
3241      unsigned cnt = X.getCount();
3242      if (cnt) {
3243        X.setCount(cnt - 1);
3244        X = X ^ RefVal::ReturnedOwned;
3245      }
3246      else {
3247        X = X ^ RefVal::ReturnedNotOwned;
3248      }
3249      break;
3250    }
3251
3252    default:
3253      return;
3254  }
3255
3256  // Update the binding.
3257  state = setRefBinding(state, Sym, X);
3258  ExplodedNode *Pred = C.addTransition(state);
3259
3260  // At this point we have updated the state properly.
3261  // Everything after this is merely checking to see if the return value has
3262  // been over- or under-retained.
3263
3264  // Did we cache out?
3265  if (!Pred)
3266    return;
3267
3268  // Update the autorelease counts.
3269  static SimpleProgramPointTag
3270         AutoreleaseTag("RetainCountChecker : Autorelease");
3271  llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Pred, &AutoreleaseTag,
3272                                                   C, Sym, X);
3273
3274  // Did we cache out?
3275  if (!Pred)
3276    return;
3277
3278  // Get the updated binding.
3279  T = getRefBinding(state, Sym);
3280  assert(T);
3281  X = *T;
3282
3283  // Consult the summary of the enclosing method.
3284  RetainSummaryManager &Summaries = getSummaryManager(C);
3285  const Decl *CD = &Pred->getCodeDecl();
3286  RetEffect RE = RetEffect::MakeNoRet();
3287
3288  // FIXME: What is the convention for blocks? Is there one?
3289  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CD)) {
3290    const RetainSummary *Summ = Summaries.getMethodSummary(MD);
3291    RE = Summ->getRetEffect();
3292  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CD)) {
3293    if (!isa<CXXMethodDecl>(FD)) {
3294      const RetainSummary *Summ = Summaries.getFunctionSummary(FD);
3295      RE = Summ->getRetEffect();
3296    }
3297  }
3298
3299  checkReturnWithRetEffect(S, C, Pred, RE, X, Sym, state);
3300}
3301
3302void RetainCountChecker::checkReturnWithRetEffect(const ReturnStmt *S,
3303                                                  CheckerContext &C,
3304                                                  ExplodedNode *Pred,
3305                                                  RetEffect RE, RefVal X,
3306                                                  SymbolRef Sym,
3307                                              ProgramStateRef state) const {
3308  // Any leaks or other errors?
3309  if (X.isReturnedOwned() && X.getCount() == 0) {
3310    if (RE.getKind() != RetEffect::NoRet) {
3311      bool hasError = false;
3312      if (C.isObjCGCEnabled() && RE.getObjKind() == RetEffect::ObjC) {
3313        // Things are more complicated with garbage collection.  If the
3314        // returned object is suppose to be an Objective-C object, we have
3315        // a leak (as the caller expects a GC'ed object) because no
3316        // method should return ownership unless it returns a CF object.
3317        hasError = true;
3318        X = X ^ RefVal::ErrorGCLeakReturned;
3319      }
3320      else if (!RE.isOwned()) {
3321        // Either we are using GC and the returned object is a CF type
3322        // or we aren't using GC.  In either case, we expect that the
3323        // enclosing method is expected to return ownership.
3324        hasError = true;
3325        X = X ^ RefVal::ErrorLeakReturned;
3326      }
3327
3328      if (hasError) {
3329        // Generate an error node.
3330        state = setRefBinding(state, Sym, X);
3331
3332        static SimpleProgramPointTag
3333               ReturnOwnLeakTag("RetainCountChecker : ReturnsOwnLeak");
3334        ExplodedNode *N = C.addTransition(state, Pred, &ReturnOwnLeakTag);
3335        if (N) {
3336          const LangOptions &LOpts = C.getASTContext().getLangOpts();
3337          bool GCEnabled = C.isObjCGCEnabled();
3338          CFRefReport *report =
3339            new CFRefLeakReport(*getLeakAtReturnBug(LOpts, GCEnabled),
3340                                LOpts, GCEnabled, SummaryLog,
3341                                N, Sym, C);
3342          C.EmitReport(report);
3343        }
3344      }
3345    }
3346  } else if (X.isReturnedNotOwned()) {
3347    if (RE.isOwned()) {
3348      // Trying to return a not owned object to a caller expecting an
3349      // owned object.
3350      state = setRefBinding(state, Sym, X ^ RefVal::ErrorReturnedNotOwned);
3351
3352      static SimpleProgramPointTag
3353             ReturnNotOwnedTag("RetainCountChecker : ReturnNotOwnedForOwned");
3354      ExplodedNode *N = C.addTransition(state, Pred, &ReturnNotOwnedTag);
3355      if (N) {
3356        if (!returnNotOwnedForOwned)
3357          returnNotOwnedForOwned.reset(new ReturnedNotOwnedForOwned());
3358
3359        CFRefReport *report =
3360            new CFRefReport(*returnNotOwnedForOwned,
3361                            C.getASTContext().getLangOpts(),
3362                            C.isObjCGCEnabled(), SummaryLog, N, Sym);
3363        C.EmitReport(report);
3364      }
3365    }
3366  }
3367}
3368
3369//===----------------------------------------------------------------------===//
3370// Check various ways a symbol can be invalidated.
3371//===----------------------------------------------------------------------===//
3372
3373void RetainCountChecker::checkBind(SVal loc, SVal val, const Stmt *S,
3374                                   CheckerContext &C) const {
3375  // Are we storing to something that causes the value to "escape"?
3376  bool escapes = true;
3377
3378  // A value escapes in three possible cases (this may change):
3379  //
3380  // (1) we are binding to something that is not a memory region.
3381  // (2) we are binding to a memregion that does not have stack storage
3382  // (3) we are binding to a memregion with stack storage that the store
3383  //     does not understand.
3384  ProgramStateRef state = C.getState();
3385
3386  if (loc::MemRegionVal *regionLoc = dyn_cast<loc::MemRegionVal>(&loc)) {
3387    escapes = !regionLoc->getRegion()->hasStackStorage();
3388
3389    if (!escapes) {
3390      // To test (3), generate a new state with the binding added.  If it is
3391      // the same state, then it escapes (since the store cannot represent
3392      // the binding).
3393      // Do this only if we know that the store is not supposed to generate the
3394      // same state.
3395      SVal StoredVal = state->getSVal(regionLoc->getRegion());
3396      if (StoredVal != val)
3397        escapes = (state == (state->bindLoc(*regionLoc, val)));
3398    }
3399    if (!escapes) {
3400      // Case 4: We do not currently model what happens when a symbol is
3401      // assigned to a struct field, so be conservative here and let the symbol
3402      // go. TODO: This could definitely be improved upon.
3403      escapes = !isa<VarRegion>(regionLoc->getRegion());
3404    }
3405  }
3406
3407  // If our store can represent the binding and we aren't storing to something
3408  // that doesn't have local storage then just return and have the simulation
3409  // state continue as is.
3410  if (!escapes)
3411      return;
3412
3413  // Otherwise, find all symbols referenced by 'val' that we are tracking
3414  // and stop tracking them.
3415  state = state->scanReachableSymbols<StopTrackingCallback>(val).getState();
3416  C.addTransition(state);
3417}
3418
3419ProgramStateRef RetainCountChecker::evalAssume(ProgramStateRef state,
3420                                                   SVal Cond,
3421                                                   bool Assumption) const {
3422
3423  // FIXME: We may add to the interface of evalAssume the list of symbols
3424  //  whose assumptions have changed.  For now we just iterate through the
3425  //  bindings and check if any of the tracked symbols are NULL.  This isn't
3426  //  too bad since the number of symbols we will track in practice are
3427  //  probably small and evalAssume is only called at branches and a few
3428  //  other places.
3429  RefBindings B = state->get<RefBindings>();
3430
3431  if (B.isEmpty())
3432    return state;
3433
3434  bool changed = false;
3435  RefBindings::Factory &RefBFactory = state->get_context<RefBindings>();
3436
3437  for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3438    // Check if the symbol is null (or equal to any constant).
3439    // If this is the case, stop tracking the symbol.
3440    if (state->getSymVal(I.getKey())) {
3441      changed = true;
3442      B = RefBFactory.remove(B, I.getKey());
3443    }
3444  }
3445
3446  if (changed)
3447    state = state->set<RefBindings>(B);
3448
3449  return state;
3450}
3451
3452ProgramStateRef
3453RetainCountChecker::checkRegionChanges(ProgramStateRef state,
3454                            const StoreManager::InvalidatedSymbols *invalidated,
3455                                    ArrayRef<const MemRegion *> ExplicitRegions,
3456                                    ArrayRef<const MemRegion *> Regions,
3457                                    const CallEvent *Call) const {
3458  if (!invalidated)
3459    return state;
3460
3461  llvm::SmallPtrSet<SymbolRef, 8> WhitelistedSymbols;
3462  for (ArrayRef<const MemRegion *>::iterator I = ExplicitRegions.begin(),
3463       E = ExplicitRegions.end(); I != E; ++I) {
3464    if (const SymbolicRegion *SR = (*I)->StripCasts()->getAs<SymbolicRegion>())
3465      WhitelistedSymbols.insert(SR->getSymbol());
3466  }
3467
3468  for (StoreManager::InvalidatedSymbols::const_iterator I=invalidated->begin(),
3469       E = invalidated->end(); I!=E; ++I) {
3470    SymbolRef sym = *I;
3471    if (WhitelistedSymbols.count(sym))
3472      continue;
3473    // Remove any existing reference-count binding.
3474    state = removeRefBinding(state, sym);
3475  }
3476  return state;
3477}
3478
3479//===----------------------------------------------------------------------===//
3480// Handle dead symbols and end-of-path.
3481//===----------------------------------------------------------------------===//
3482
3483std::pair<ExplodedNode *, ProgramStateRef >
3484RetainCountChecker::handleAutoreleaseCounts(ProgramStateRef state,
3485                                            ExplodedNode *Pred,
3486                                            const ProgramPointTag *Tag,
3487                                            CheckerContext &Ctx,
3488                                            SymbolRef Sym, RefVal V) const {
3489  unsigned ACnt = V.getAutoreleaseCount();
3490
3491  // No autorelease counts?  Nothing to be done.
3492  if (!ACnt)
3493    return std::make_pair(Pred, state);
3494
3495  assert(!Ctx.isObjCGCEnabled() && "Autorelease counts in GC mode?");
3496  unsigned Cnt = V.getCount();
3497
3498  // FIXME: Handle sending 'autorelease' to already released object.
3499
3500  if (V.getKind() == RefVal::ReturnedOwned)
3501    ++Cnt;
3502
3503  if (ACnt <= Cnt) {
3504    if (ACnt == Cnt) {
3505      V.clearCounts();
3506      if (V.getKind() == RefVal::ReturnedOwned)
3507        V = V ^ RefVal::ReturnedNotOwned;
3508      else
3509        V = V ^ RefVal::NotOwned;
3510    } else {
3511      V.setCount(Cnt - ACnt);
3512      V.setAutoreleaseCount(0);
3513    }
3514    state = setRefBinding(state, Sym, V);
3515    ExplodedNode *N = Ctx.addTransition(state, Pred, Tag);
3516    if (N == 0)
3517      state = 0;
3518    return std::make_pair(N, state);
3519  }
3520
3521  // Woah!  More autorelease counts then retain counts left.
3522  // Emit hard error.
3523  V = V ^ RefVal::ErrorOverAutorelease;
3524  state = setRefBinding(state, Sym, V);
3525
3526  ExplodedNode *N = Ctx.generateSink(state, Pred, Tag);
3527  if (N) {
3528    SmallString<128> sbuf;
3529    llvm::raw_svector_ostream os(sbuf);
3530    os << "Object over-autoreleased: object was sent -autorelease ";
3531    if (V.getAutoreleaseCount() > 1)
3532      os << V.getAutoreleaseCount() << " times ";
3533    os << "but the object has a +" << V.getCount() << " retain count";
3534
3535    if (!overAutorelease)
3536      overAutorelease.reset(new OverAutorelease());
3537
3538    const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3539    CFRefReport *report =
3540      new CFRefReport(*overAutorelease, LOpts, /* GCEnabled = */ false,
3541                      SummaryLog, N, Sym, os.str());
3542    Ctx.EmitReport(report);
3543  }
3544
3545  return std::make_pair((ExplodedNode *)0, (ProgramStateRef )0);
3546}
3547
3548ProgramStateRef
3549RetainCountChecker::handleSymbolDeath(ProgramStateRef state,
3550                                      SymbolRef sid, RefVal V,
3551                                    SmallVectorImpl<SymbolRef> &Leaked) const {
3552  bool hasLeak = false;
3553  if (V.isOwned())
3554    hasLeak = true;
3555  else if (V.isNotOwned() || V.isReturnedOwned())
3556    hasLeak = (V.getCount() > 0);
3557
3558  if (!hasLeak)
3559    return removeRefBinding(state, sid);
3560
3561  Leaked.push_back(sid);
3562  return setRefBinding(state, sid, V ^ RefVal::ErrorLeak);
3563}
3564
3565ExplodedNode *
3566RetainCountChecker::processLeaks(ProgramStateRef state,
3567                                 SmallVectorImpl<SymbolRef> &Leaked,
3568                                 CheckerContext &Ctx,
3569                                 ExplodedNode *Pred) const {
3570  if (Leaked.empty())
3571    return Pred;
3572
3573  // Generate an intermediate node representing the leak point.
3574  ExplodedNode *N = Ctx.addTransition(state, Pred);
3575
3576  if (N) {
3577    for (SmallVectorImpl<SymbolRef>::iterator
3578         I = Leaked.begin(), E = Leaked.end(); I != E; ++I) {
3579
3580      const LangOptions &LOpts = Ctx.getASTContext().getLangOpts();
3581      bool GCEnabled = Ctx.isObjCGCEnabled();
3582      CFRefBug *BT = Pred ? getLeakWithinFunctionBug(LOpts, GCEnabled)
3583                          : getLeakAtReturnBug(LOpts, GCEnabled);
3584      assert(BT && "BugType not initialized.");
3585
3586      CFRefLeakReport *report = new CFRefLeakReport(*BT, LOpts, GCEnabled,
3587                                                    SummaryLog, N, *I, Ctx);
3588      Ctx.EmitReport(report);
3589    }
3590  }
3591
3592  return N;
3593}
3594
3595void RetainCountChecker::checkEndPath(CheckerContext &Ctx) const {
3596  ProgramStateRef state = Ctx.getState();
3597  RefBindings B = state->get<RefBindings>();
3598  ExplodedNode *Pred = Ctx.getPredecessor();
3599
3600  for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3601    llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Pred, /*Tag=*/0,
3602                                                     Ctx, I->first, I->second);
3603    if (!state)
3604      return;
3605  }
3606
3607  // If the current LocationContext has a parent, don't check for leaks.
3608  // We will do that later.
3609  // FIXME: we should instead check for imbalances of the retain/releases,
3610  // and suggest annotations.
3611  if (Ctx.getLocationContext()->getParent())
3612    return;
3613
3614  B = state->get<RefBindings>();
3615  SmallVector<SymbolRef, 10> Leaked;
3616
3617  for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I)
3618    state = handleSymbolDeath(state, I->first, I->second, Leaked);
3619
3620  processLeaks(state, Leaked, Ctx, Pred);
3621}
3622
3623const ProgramPointTag *
3624RetainCountChecker::getDeadSymbolTag(SymbolRef sym) const {
3625  const SimpleProgramPointTag *&tag = DeadSymbolTags[sym];
3626  if (!tag) {
3627    SmallString<64> buf;
3628    llvm::raw_svector_ostream out(buf);
3629    out << "RetainCountChecker : Dead Symbol : ";
3630    sym->dumpToStream(out);
3631    tag = new SimpleProgramPointTag(out.str());
3632  }
3633  return tag;
3634}
3635
3636void RetainCountChecker::checkDeadSymbols(SymbolReaper &SymReaper,
3637                                          CheckerContext &C) const {
3638  ExplodedNode *Pred = C.getPredecessor();
3639
3640  ProgramStateRef state = C.getState();
3641  RefBindings B = state->get<RefBindings>();
3642
3643  // Update counts from autorelease pools
3644  for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3645       E = SymReaper.dead_end(); I != E; ++I) {
3646    SymbolRef Sym = *I;
3647    if (const RefVal *T = B.lookup(Sym)){
3648      // Use the symbol as the tag.
3649      // FIXME: This might not be as unique as we would like.
3650      const ProgramPointTag *Tag = getDeadSymbolTag(Sym);
3651      llvm::tie(Pred, state) = handleAutoreleaseCounts(state, Pred, Tag, C,
3652                                                       Sym, *T);
3653      if (!state)
3654        return;
3655    }
3656  }
3657
3658  B = state->get<RefBindings>();
3659  SmallVector<SymbolRef, 10> Leaked;
3660
3661  for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3662       E = SymReaper.dead_end(); I != E; ++I) {
3663    if (const RefVal *T = B.lookup(*I))
3664      state = handleSymbolDeath(state, *I, *T, Leaked);
3665  }
3666
3667  Pred = processLeaks(state, Leaked, C, Pred);
3668
3669  // Did we cache out?
3670  if (!Pred)
3671    return;
3672
3673  // Now generate a new node that nukes the old bindings.
3674  RefBindings::Factory &F = state->get_context<RefBindings>();
3675
3676  for (SymbolReaper::dead_iterator I = SymReaper.dead_begin(),
3677       E = SymReaper.dead_end(); I != E; ++I)
3678    B = F.remove(B, *I);
3679
3680  state = state->set<RefBindings>(B);
3681  C.addTransition(state, Pred);
3682}
3683
3684void RetainCountChecker::printState(raw_ostream &Out, ProgramStateRef State,
3685                                    const char *NL, const char *Sep) const {
3686
3687  RefBindings B = State->get<RefBindings>();
3688
3689  if (!B.isEmpty())
3690    Out << Sep << NL;
3691
3692  for (RefBindings::iterator I = B.begin(), E = B.end(); I != E; ++I) {
3693    Out << I->first << " : ";
3694    I->second.print(Out);
3695    Out << NL;
3696  }
3697}
3698
3699//===----------------------------------------------------------------------===//
3700// Checker registration.
3701//===----------------------------------------------------------------------===//
3702
3703void ento::registerRetainCountChecker(CheckerManager &Mgr) {
3704  Mgr.registerChecker<RetainCountChecker>();
3705}
3706
3707