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