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