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