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