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