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