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