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