2ce7dfd86f6560e54ea8eb7c0d5a2971c2d4fa3d
[oota-llvm.git] / lib / Transforms / ObjCARC / ObjCARCOpts.cpp
1 //===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===//
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 /// \file
10 /// This file defines ObjC ARC optimizations. ARC stands for Automatic
11 /// Reference Counting and is a system for managing reference counts for objects
12 /// in Objective C.
13 ///
14 /// The optimizations performed include elimination of redundant, partially
15 /// redundant, and inconsequential reference count operations, elimination of
16 /// redundant weak pointer operations, and numerous minor simplifications.
17 ///
18 /// WARNING: This file knows about certain library functions. It recognizes them
19 /// by name, and hardwires knowledge of their semantics.
20 ///
21 /// WARNING: This file knows about how certain Objective-C library functions are
22 /// used. Naive LLVM IR transformations which would otherwise be
23 /// behavior-preserving may break these assumptions.
24 ///
25 //===----------------------------------------------------------------------===//
26
27 #include "ObjCARC.h"
28 #include "ARCRuntimeEntryPoints.h"
29 #include "DependencyAnalysis.h"
30 #include "ObjCARCAliasAnalysis.h"
31 #include "ProvenanceAnalysis.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/DenseSet.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/IR/CFG.h"
38 #include "llvm/IR/IRBuilder.h"
39 #include "llvm/IR/LLVMContext.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
42
43 using namespace llvm;
44 using namespace llvm::objcarc;
45
46 #define DEBUG_TYPE "objc-arc-opts"
47
48 /// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
49 /// @{
50
51 namespace {
52   /// \brief An associative container with fast insertion-order (deterministic)
53   /// iteration over its elements. Plus the special blot operation.
54   template<class KeyT, class ValueT>
55   class MapVector {
56     /// Map keys to indices in Vector.
57     typedef DenseMap<KeyT, size_t> MapTy;
58     MapTy Map;
59
60     typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
61     /// Keys and values.
62     VectorTy Vector;
63
64   public:
65     typedef typename VectorTy::iterator iterator;
66     typedef typename VectorTy::const_iterator const_iterator;
67     iterator begin() { return Vector.begin(); }
68     iterator end() { return Vector.end(); }
69     const_iterator begin() const { return Vector.begin(); }
70     const_iterator end() const { return Vector.end(); }
71
72 #ifdef XDEBUG
73     ~MapVector() {
74       assert(Vector.size() >= Map.size()); // May differ due to blotting.
75       for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
76            I != E; ++I) {
77         assert(I->second < Vector.size());
78         assert(Vector[I->second].first == I->first);
79       }
80       for (typename VectorTy::const_iterator I = Vector.begin(),
81            E = Vector.end(); I != E; ++I)
82         assert(!I->first ||
83                (Map.count(I->first) &&
84                 Map[I->first] == size_t(I - Vector.begin())));
85     }
86 #endif
87
88     ValueT &operator[](const KeyT &Arg) {
89       std::pair<typename MapTy::iterator, bool> Pair =
90         Map.insert(std::make_pair(Arg, size_t(0)));
91       if (Pair.second) {
92         size_t Num = Vector.size();
93         Pair.first->second = Num;
94         Vector.push_back(std::make_pair(Arg, ValueT()));
95         return Vector[Num].second;
96       }
97       return Vector[Pair.first->second].second;
98     }
99
100     std::pair<iterator, bool>
101     insert(const std::pair<KeyT, ValueT> &InsertPair) {
102       std::pair<typename MapTy::iterator, bool> Pair =
103         Map.insert(std::make_pair(InsertPair.first, size_t(0)));
104       if (Pair.second) {
105         size_t Num = Vector.size();
106         Pair.first->second = Num;
107         Vector.push_back(InsertPair);
108         return std::make_pair(Vector.begin() + Num, true);
109       }
110       return std::make_pair(Vector.begin() + Pair.first->second, false);
111     }
112
113     iterator find(const KeyT &Key) {
114       typename MapTy::iterator It = Map.find(Key);
115       if (It == Map.end()) return Vector.end();
116       return Vector.begin() + It->second;
117     }
118
119     const_iterator find(const KeyT &Key) const {
120       typename MapTy::const_iterator It = Map.find(Key);
121       if (It == Map.end()) return Vector.end();
122       return Vector.begin() + It->second;
123     }
124
125     /// This is similar to erase, but instead of removing the element from the
126     /// vector, it just zeros out the key in the vector. This leaves iterators
127     /// intact, but clients must be prepared for zeroed-out keys when iterating.
128     void blot(const KeyT &Key) {
129       typename MapTy::iterator It = Map.find(Key);
130       if (It == Map.end()) return;
131       Vector[It->second].first = KeyT();
132       Map.erase(It);
133     }
134
135     void clear() {
136       Map.clear();
137       Vector.clear();
138     }
139   };
140 }
141
142 /// @}
143 ///
144 /// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
145 /// @{
146
147 /// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
148 /// as it finds a value with multiple uses.
149 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
150   if (Arg->hasOneUse()) {
151     if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
152       return FindSingleUseIdentifiedObject(BC->getOperand(0));
153     if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
154       if (GEP->hasAllZeroIndices())
155         return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
156     if (IsForwarding(GetBasicInstructionClass(Arg)))
157       return FindSingleUseIdentifiedObject(
158                cast<CallInst>(Arg)->getArgOperand(0));
159     if (!IsObjCIdentifiedObject(Arg))
160       return nullptr;
161     return Arg;
162   }
163
164   // If we found an identifiable object but it has multiple uses, but they are
165   // trivial uses, we can still consider this to be a single-use value.
166   if (IsObjCIdentifiedObject(Arg)) {
167     for (const User *U : Arg->users())
168       if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
169          return nullptr;
170
171     return Arg;
172   }
173
174   return nullptr;
175 }
176
177 /// This is a wrapper around getUnderlyingObjCPtr along the lines of
178 /// GetUnderlyingObjects except that it returns early when it sees the first
179 /// alloca.
180 static inline bool AreAnyUnderlyingObjectsAnAlloca(const Value *V) {
181   SmallPtrSet<const Value *, 4> Visited;
182   SmallVector<const Value *, 4> Worklist;
183   Worklist.push_back(V);
184   do {
185     const Value *P = Worklist.pop_back_val();
186     P = GetUnderlyingObjCPtr(P);
187
188     if (isa<AllocaInst>(P))
189       return true;
190
191     if (!Visited.insert(P))
192       continue;
193
194     if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
195       Worklist.push_back(SI->getTrueValue());
196       Worklist.push_back(SI->getFalseValue());
197       continue;
198     }
199
200     if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
201       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
202         Worklist.push_back(PN->getIncomingValue(i));
203       continue;
204     }
205   } while (!Worklist.empty());
206
207   return false;
208 }
209
210
211 /// @}
212 ///
213 /// \defgroup ARCOpt ARC Optimization.
214 /// @{
215
216 // TODO: On code like this:
217 //
218 // objc_retain(%x)
219 // stuff_that_cannot_release()
220 // objc_autorelease(%x)
221 // stuff_that_cannot_release()
222 // objc_retain(%x)
223 // stuff_that_cannot_release()
224 // objc_autorelease(%x)
225 //
226 // The second retain and autorelease can be deleted.
227
228 // TODO: It should be possible to delete
229 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
230 // pairs if nothing is actually autoreleased between them. Also, autorelease
231 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
232 // after inlining) can be turned into plain release calls.
233
234 // TODO: Critical-edge splitting. If the optimial insertion point is
235 // a critical edge, the current algorithm has to fail, because it doesn't
236 // know how to split edges. It should be possible to make the optimizer
237 // think in terms of edges, rather than blocks, and then split critical
238 // edges on demand.
239
240 // TODO: OptimizeSequences could generalized to be Interprocedural.
241
242 // TODO: Recognize that a bunch of other objc runtime calls have
243 // non-escaping arguments and non-releasing arguments, and may be
244 // non-autoreleasing.
245
246 // TODO: Sink autorelease calls as far as possible. Unfortunately we
247 // usually can't sink them past other calls, which would be the main
248 // case where it would be useful.
249
250 // TODO: The pointer returned from objc_loadWeakRetained is retained.
251
252 // TODO: Delete release+retain pairs (rare).
253
254 STATISTIC(NumNoops,       "Number of no-op objc calls eliminated");
255 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
256 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
257 STATISTIC(NumRets,        "Number of return value forwarding "
258                           "retain+autoreleases eliminated");
259 STATISTIC(NumRRs,         "Number of retain+release paths eliminated");
260 STATISTIC(NumPeeps,       "Number of calls peephole-optimized");
261 #ifndef NDEBUG
262 STATISTIC(NumRetainsBeforeOpt,
263           "Number of retains before optimization");
264 STATISTIC(NumReleasesBeforeOpt,
265           "Number of releases before optimization");
266 STATISTIC(NumRetainsAfterOpt,
267           "Number of retains after optimization");
268 STATISTIC(NumReleasesAfterOpt,
269           "Number of releases after optimization");
270 #endif
271
272 namespace {
273   /// \enum Sequence
274   ///
275   /// \brief A sequence of states that a pointer may go through in which an
276   /// objc_retain and objc_release are actually needed.
277   enum Sequence {
278     S_None,
279     S_Retain,         ///< objc_retain(x).
280     S_CanRelease,     ///< foo(x) -- x could possibly see a ref count decrement.
281     S_Use,            ///< any use of x.
282     S_Stop,           ///< like S_Release, but code motion is stopped.
283     S_Release,        ///< objc_release(x).
284     S_MovableRelease  ///< objc_release(x), !clang.imprecise_release.
285   };
286
287   raw_ostream &operator<<(raw_ostream &OS, const Sequence S)
288     LLVM_ATTRIBUTE_UNUSED;
289   raw_ostream &operator<<(raw_ostream &OS, const Sequence S) {
290     switch (S) {
291     case S_None:
292       return OS << "S_None";
293     case S_Retain:
294       return OS << "S_Retain";
295     case S_CanRelease:
296       return OS << "S_CanRelease";
297     case S_Use:
298       return OS << "S_Use";
299     case S_Release:
300       return OS << "S_Release";
301     case S_MovableRelease:
302       return OS << "S_MovableRelease";
303     case S_Stop:
304       return OS << "S_Stop";
305     }
306     llvm_unreachable("Unknown sequence type.");
307   }
308 }
309
310 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
311   // The easy cases.
312   if (A == B)
313     return A;
314   if (A == S_None || B == S_None)
315     return S_None;
316
317   if (A > B) std::swap(A, B);
318   if (TopDown) {
319     // Choose the side which is further along in the sequence.
320     if ((A == S_Retain || A == S_CanRelease) &&
321         (B == S_CanRelease || B == S_Use))
322       return B;
323   } else {
324     // Choose the side which is further along in the sequence.
325     if ((A == S_Use || A == S_CanRelease) &&
326         (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
327       return A;
328     // If both sides are releases, choose the more conservative one.
329     if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
330       return A;
331     if (A == S_Release && B == S_MovableRelease)
332       return A;
333   }
334
335   return S_None;
336 }
337
338 namespace {
339   /// \brief Unidirectional information about either a
340   /// retain-decrement-use-release sequence or release-use-decrement-retain
341   /// reverse sequence.
342   struct RRInfo {
343     /// After an objc_retain, the reference count of the referenced
344     /// object is known to be positive. Similarly, before an objc_release, the
345     /// reference count of the referenced object is known to be positive. If
346     /// there are retain-release pairs in code regions where the retain count
347     /// is known to be positive, they can be eliminated, regardless of any side
348     /// effects between them.
349     ///
350     /// Also, a retain+release pair nested within another retain+release
351     /// pair all on the known same pointer value can be eliminated, regardless
352     /// of any intervening side effects.
353     ///
354     /// KnownSafe is true when either of these conditions is satisfied.
355     bool KnownSafe;
356
357     /// True of the objc_release calls are all marked with the "tail" keyword.
358     bool IsTailCallRelease;
359
360     /// If the Calls are objc_release calls and they all have a
361     /// clang.imprecise_release tag, this is the metadata tag.
362     MDNode *ReleaseMetadata;
363
364     /// For a top-down sequence, the set of objc_retains or
365     /// objc_retainBlocks. For bottom-up, the set of objc_releases.
366     SmallPtrSet<Instruction *, 2> Calls;
367
368     /// The set of optimal insert positions for moving calls in the opposite
369     /// sequence.
370     SmallPtrSet<Instruction *, 2> ReverseInsertPts;
371
372     /// If this is true, we cannot perform code motion but can still remove
373     /// retain/release pairs.
374     bool CFGHazardAfflicted;
375
376     RRInfo() :
377       KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(nullptr),
378       CFGHazardAfflicted(false) {}
379
380     void clear();
381
382     /// Conservatively merge the two RRInfo. Returns true if a partial merge has
383     /// occurred, false otherwise.
384     bool Merge(const RRInfo &Other);
385
386   };
387 }
388
389 void RRInfo::clear() {
390   KnownSafe = false;
391   IsTailCallRelease = false;
392   ReleaseMetadata = nullptr;
393   Calls.clear();
394   ReverseInsertPts.clear();
395   CFGHazardAfflicted = false;
396 }
397
398 bool RRInfo::Merge(const RRInfo &Other) {
399     // Conservatively merge the ReleaseMetadata information.
400     if (ReleaseMetadata != Other.ReleaseMetadata)
401       ReleaseMetadata = nullptr;
402
403     // Conservatively merge the boolean state.
404     KnownSafe &= Other.KnownSafe;
405     IsTailCallRelease &= Other.IsTailCallRelease;
406     CFGHazardAfflicted |= Other.CFGHazardAfflicted;
407
408     // Merge the call sets.
409     Calls.insert(Other.Calls.begin(), Other.Calls.end());
410
411     // Merge the insert point sets. If there are any differences,
412     // that makes this a partial merge.
413     bool Partial = ReverseInsertPts.size() != Other.ReverseInsertPts.size();
414     for (Instruction *Inst : Other.ReverseInsertPts)
415       Partial |= ReverseInsertPts.insert(Inst);
416     return Partial;
417 }
418
419 namespace {
420   /// \brief This class summarizes several per-pointer runtime properties which
421   /// are propogated through the flow graph.
422   class PtrState {
423     /// True if the reference count is known to be incremented.
424     bool KnownPositiveRefCount;
425
426     /// True if we've seen an opportunity for partial RR elimination, such as
427     /// pushing calls into a CFG triangle or into one side of a CFG diamond.
428     bool Partial;
429
430     /// The current position in the sequence.
431     unsigned char Seq : 8;
432
433     /// Unidirectional information about the current sequence.
434     RRInfo RRI;
435
436   public:
437     PtrState() : KnownPositiveRefCount(false), Partial(false),
438                  Seq(S_None) {}
439
440
441     bool IsKnownSafe() const {
442       return RRI.KnownSafe;
443     }
444
445     void SetKnownSafe(const bool NewValue) {
446       RRI.KnownSafe = NewValue;
447     }
448
449     bool IsTailCallRelease() const {
450       return RRI.IsTailCallRelease;
451     }
452
453     void SetTailCallRelease(const bool NewValue) {
454       RRI.IsTailCallRelease = NewValue;
455     }
456
457     bool IsTrackingImpreciseReleases() const {
458       return RRI.ReleaseMetadata != nullptr;
459     }
460
461     const MDNode *GetReleaseMetadata() const {
462       return RRI.ReleaseMetadata;
463     }
464
465     void SetReleaseMetadata(MDNode *NewValue) {
466       RRI.ReleaseMetadata = NewValue;
467     }
468
469     bool IsCFGHazardAfflicted() const {
470       return RRI.CFGHazardAfflicted;
471     }
472
473     void SetCFGHazardAfflicted(const bool NewValue) {
474       RRI.CFGHazardAfflicted = NewValue;
475     }
476
477     void SetKnownPositiveRefCount() {
478       DEBUG(dbgs() << "Setting Known Positive.\n");
479       KnownPositiveRefCount = true;
480     }
481
482     void ClearKnownPositiveRefCount() {
483       DEBUG(dbgs() << "Clearing Known Positive.\n");
484       KnownPositiveRefCount = false;
485     }
486
487     bool HasKnownPositiveRefCount() const {
488       return KnownPositiveRefCount;
489     }
490
491     void SetSeq(Sequence NewSeq) {
492       DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
493       Seq = NewSeq;
494     }
495
496     Sequence GetSeq() const {
497       return static_cast<Sequence>(Seq);
498     }
499
500     void ClearSequenceProgress() {
501       ResetSequenceProgress(S_None);
502     }
503
504     void ResetSequenceProgress(Sequence NewSeq) {
505       DEBUG(dbgs() << "Resetting sequence progress.\n");
506       SetSeq(NewSeq);
507       Partial = false;
508       RRI.clear();
509     }
510
511     void Merge(const PtrState &Other, bool TopDown);
512
513     void InsertCall(Instruction *I) {
514       RRI.Calls.insert(I);
515     }
516
517     void InsertReverseInsertPt(Instruction *I) {
518       RRI.ReverseInsertPts.insert(I);
519     }
520
521     void ClearReverseInsertPts() {
522       RRI.ReverseInsertPts.clear();
523     }
524
525     bool HasReverseInsertPts() const {
526       return !RRI.ReverseInsertPts.empty();
527     }
528
529     const RRInfo &GetRRInfo() const {
530       return RRI;
531     }
532   };
533 }
534
535 void
536 PtrState::Merge(const PtrState &Other, bool TopDown) {
537   Seq = MergeSeqs(GetSeq(), Other.GetSeq(), TopDown);
538   KnownPositiveRefCount &= Other.KnownPositiveRefCount;
539
540   // If we're not in a sequence (anymore), drop all associated state.
541   if (Seq == S_None) {
542     Partial = false;
543     RRI.clear();
544   } else if (Partial || Other.Partial) {
545     // If we're doing a merge on a path that's previously seen a partial
546     // merge, conservatively drop the sequence, to avoid doing partial
547     // RR elimination. If the branch predicates for the two merge differ,
548     // mixing them is unsafe.
549     ClearSequenceProgress();
550   } else {
551     // Otherwise merge the other PtrState's RRInfo into our RRInfo. At this
552     // point, we know that currently we are not partial. Stash whether or not
553     // the merge operation caused us to undergo a partial merging of reverse
554     // insertion points.
555     Partial = RRI.Merge(Other.RRI);
556   }
557 }
558
559 namespace {
560   /// \brief Per-BasicBlock state.
561   class BBState {
562     /// The number of unique control paths from the entry which can reach this
563     /// block.
564     unsigned TopDownPathCount;
565
566     /// The number of unique control paths to exits from this block.
567     unsigned BottomUpPathCount;
568
569     /// A type for PerPtrTopDown and PerPtrBottomUp.
570     typedef MapVector<const Value *, PtrState> MapTy;
571
572     /// The top-down traversal uses this to record information known about a
573     /// pointer at the bottom of each block.
574     MapTy PerPtrTopDown;
575
576     /// The bottom-up traversal uses this to record information known about a
577     /// pointer at the top of each block.
578     MapTy PerPtrBottomUp;
579
580     /// Effective predecessors of the current block ignoring ignorable edges and
581     /// ignored backedges.
582     SmallVector<BasicBlock *, 2> Preds;
583     /// Effective successors of the current block ignoring ignorable edges and
584     /// ignored backedges.
585     SmallVector<BasicBlock *, 2> Succs;
586
587   public:
588     static const unsigned OverflowOccurredValue;
589
590     BBState() : TopDownPathCount(0), BottomUpPathCount(0) { }
591
592     typedef MapTy::iterator ptr_iterator;
593     typedef MapTy::const_iterator ptr_const_iterator;
594
595     ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
596     ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
597     ptr_const_iterator top_down_ptr_begin() const {
598       return PerPtrTopDown.begin();
599     }
600     ptr_const_iterator top_down_ptr_end() const {
601       return PerPtrTopDown.end();
602     }
603
604     ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
605     ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
606     ptr_const_iterator bottom_up_ptr_begin() const {
607       return PerPtrBottomUp.begin();
608     }
609     ptr_const_iterator bottom_up_ptr_end() const {
610       return PerPtrBottomUp.end();
611     }
612
613     /// Mark this block as being an entry block, which has one path from the
614     /// entry by definition.
615     void SetAsEntry() { TopDownPathCount = 1; }
616
617     /// Mark this block as being an exit block, which has one path to an exit by
618     /// definition.
619     void SetAsExit()  { BottomUpPathCount = 1; }
620
621     /// Attempt to find the PtrState object describing the top down state for
622     /// pointer Arg. Return a new initialized PtrState describing the top down
623     /// state for Arg if we do not find one.
624     PtrState &getPtrTopDownState(const Value *Arg) {
625       return PerPtrTopDown[Arg];
626     }
627
628     /// Attempt to find the PtrState object describing the bottom up state for
629     /// pointer Arg. Return a new initialized PtrState describing the bottom up
630     /// state for Arg if we do not find one.
631     PtrState &getPtrBottomUpState(const Value *Arg) {
632       return PerPtrBottomUp[Arg];
633     }
634
635     /// Attempt to find the PtrState object describing the bottom up state for
636     /// pointer Arg.
637     ptr_iterator findPtrBottomUpState(const Value *Arg) {
638       return PerPtrBottomUp.find(Arg);
639     }
640
641     void clearBottomUpPointers() {
642       PerPtrBottomUp.clear();
643     }
644
645     void clearTopDownPointers() {
646       PerPtrTopDown.clear();
647     }
648
649     void InitFromPred(const BBState &Other);
650     void InitFromSucc(const BBState &Other);
651     void MergePred(const BBState &Other);
652     void MergeSucc(const BBState &Other);
653
654     /// Compute the number of possible unique paths from an entry to an exit
655     /// which pass through this block. This is only valid after both the
656     /// top-down and bottom-up traversals are complete.
657     ///
658     /// Returns true if overflow occurred. Returns false if overflow did not
659     /// occur.
660     bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
661       if (TopDownPathCount == OverflowOccurredValue ||
662           BottomUpPathCount == OverflowOccurredValue)
663         return true;
664       unsigned long long Product =
665         (unsigned long long)TopDownPathCount*BottomUpPathCount;
666       // Overflow occurred if any of the upper bits of Product are set or if all
667       // the lower bits of Product are all set.
668       return (Product >> 32) ||
669              ((PathCount = Product) == OverflowOccurredValue);
670     }
671
672     // Specialized CFG utilities.
673     typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
674     edge_iterator pred_begin() const { return Preds.begin(); }
675     edge_iterator pred_end() const { return Preds.end(); }
676     edge_iterator succ_begin() const { return Succs.begin(); }
677     edge_iterator succ_end() const { return Succs.end(); }
678
679     void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
680     void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
681
682     bool isExit() const { return Succs.empty(); }
683   };
684
685   const unsigned BBState::OverflowOccurredValue = 0xffffffff;
686 }
687
688 void BBState::InitFromPred(const BBState &Other) {
689   PerPtrTopDown = Other.PerPtrTopDown;
690   TopDownPathCount = Other.TopDownPathCount;
691 }
692
693 void BBState::InitFromSucc(const BBState &Other) {
694   PerPtrBottomUp = Other.PerPtrBottomUp;
695   BottomUpPathCount = Other.BottomUpPathCount;
696 }
697
698 /// The top-down traversal uses this to merge information about predecessors to
699 /// form the initial state for a new block.
700 void BBState::MergePred(const BBState &Other) {
701   if (TopDownPathCount == OverflowOccurredValue)
702     return;
703
704   // Other.TopDownPathCount can be 0, in which case it is either dead or a
705   // loop backedge. Loop backedges are special.
706   TopDownPathCount += Other.TopDownPathCount;
707
708   // In order to be consistent, we clear the top down pointers when by adding
709   // TopDownPathCount becomes OverflowOccurredValue even though "true" overflow
710   // has not occurred.
711   if (TopDownPathCount == OverflowOccurredValue) {
712     clearTopDownPointers();
713     return;
714   }
715
716   // Check for overflow. If we have overflow, fall back to conservative
717   // behavior.
718   if (TopDownPathCount < Other.TopDownPathCount) {
719     TopDownPathCount = OverflowOccurredValue;
720     clearTopDownPointers();
721     return;
722   }
723
724   // For each entry in the other set, if our set has an entry with the same key,
725   // merge the entries. Otherwise, copy the entry and merge it with an empty
726   // entry.
727   for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
728        ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
729     std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
730     Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
731                              /*TopDown=*/true);
732   }
733
734   // For each entry in our set, if the other set doesn't have an entry with the
735   // same key, force it to merge with an empty entry.
736   for (ptr_iterator MI = top_down_ptr_begin(),
737        ME = top_down_ptr_end(); MI != ME; ++MI)
738     if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
739       MI->second.Merge(PtrState(), /*TopDown=*/true);
740 }
741
742 /// The bottom-up traversal uses this to merge information about successors to
743 /// form the initial state for a new block.
744 void BBState::MergeSucc(const BBState &Other) {
745   if (BottomUpPathCount == OverflowOccurredValue)
746     return;
747
748   // Other.BottomUpPathCount can be 0, in which case it is either dead or a
749   // loop backedge. Loop backedges are special.
750   BottomUpPathCount += Other.BottomUpPathCount;
751
752   // In order to be consistent, we clear the top down pointers when by adding
753   // BottomUpPathCount becomes OverflowOccurredValue even though "true" overflow
754   // has not occurred.
755   if (BottomUpPathCount == OverflowOccurredValue) {
756     clearBottomUpPointers();
757     return;
758   }
759
760   // Check for overflow. If we have overflow, fall back to conservative
761   // behavior.
762   if (BottomUpPathCount < Other.BottomUpPathCount) {
763     BottomUpPathCount = OverflowOccurredValue;
764     clearBottomUpPointers();
765     return;
766   }
767
768   // For each entry in the other set, if our set has an entry with the
769   // same key, merge the entries. Otherwise, copy the entry and merge
770   // it with an empty entry.
771   for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
772        ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
773     std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
774     Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
775                              /*TopDown=*/false);
776   }
777
778   // For each entry in our set, if the other set doesn't have an entry
779   // with the same key, force it to merge with an empty entry.
780   for (ptr_iterator MI = bottom_up_ptr_begin(),
781        ME = bottom_up_ptr_end(); MI != ME; ++MI)
782     if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
783       MI->second.Merge(PtrState(), /*TopDown=*/false);
784 }
785
786 // Only enable ARC Annotations if we are building a debug version of
787 // libObjCARCOpts.
788 #ifndef NDEBUG
789 #define ARC_ANNOTATIONS
790 #endif
791
792 // Define some macros along the lines of DEBUG and some helper functions to make
793 // it cleaner to create annotations in the source code and to no-op when not
794 // building in debug mode.
795 #ifdef ARC_ANNOTATIONS
796
797 #include "llvm/Support/CommandLine.h"
798
799 /// Enable/disable ARC sequence annotations.
800 static cl::opt<bool>
801 EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
802                      cl::desc("Enable emission of arc data flow analysis "
803                               "annotations"));
804 static cl::opt<bool>
805 DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
806                           cl::desc("Disable check for cfg hazards when "
807                                    "annotating"));
808 static cl::opt<std::string>
809 ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
810                               cl::init(""),
811                               cl::desc("filter out all data flow annotations "
812                                        "but those that apply to the given "
813                                        "target llvm identifier."));
814
815 /// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
816 /// instruction so that we can track backwards when post processing via the llvm
817 /// arc annotation processor tool. If the function is an
818 static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
819                                          Value *Ptr) {
820   MDString *Hash = nullptr;
821
822   // If pointer is a result of an instruction and it does not have a source
823   // MDNode it, attach a new MDNode onto it. If pointer is a result of
824   // an instruction and does have a source MDNode attached to it, return a
825   // reference to said Node. Otherwise just return 0.
826   if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
827     MDNode *Node;
828     if (!(Node = Inst->getMetadata(NodeId))) {
829       // We do not have any node. Generate and attatch the hash MDString to the
830       // instruction.
831
832       // We just use an MDString to ensure that this metadata gets written out
833       // of line at the module level and to provide a very simple format
834       // encoding the information herein. Both of these makes it simpler to
835       // parse the annotations by a simple external program.
836       std::string Str;
837       raw_string_ostream os(Str);
838       os << "(" << Inst->getParent()->getParent()->getName() << ",%"
839          << Inst->getName() << ")";
840
841       Hash = MDString::get(Inst->getContext(), os.str());
842       Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
843     } else {
844       // We have a node. Grab its hash and return it.
845       assert(Node->getNumOperands() == 1 &&
846         "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
847       Hash = cast<MDString>(Node->getOperand(0));
848     }
849   } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
850     std::string str;
851     raw_string_ostream os(str);
852     os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
853        << ")";
854     Hash = MDString::get(Arg->getContext(), os.str());
855   }
856
857   return Hash;
858 }
859
860 static std::string SequenceToString(Sequence A) {
861   std::string str;
862   raw_string_ostream os(str);
863   os << A;
864   return os.str();
865 }
866
867 /// Helper function to change a Sequence into a String object using our overload
868 /// for raw_ostream so we only have printing code in one location.
869 static MDString *SequenceToMDString(LLVMContext &Context,
870                                     Sequence A) {
871   return MDString::get(Context, SequenceToString(A));
872 }
873
874 /// A simple function to generate a MDNode which describes the change in state
875 /// for Value *Ptr caused by Instruction *Inst.
876 static void AppendMDNodeToInstForPtr(unsigned NodeId,
877                                      Instruction *Inst,
878                                      Value *Ptr,
879                                      MDString *PtrSourceMDNodeID,
880                                      Sequence OldSeq,
881                                      Sequence NewSeq) {
882   MDNode *Node = nullptr;
883   Value *tmp[3] = {PtrSourceMDNodeID,
884                    SequenceToMDString(Inst->getContext(),
885                                       OldSeq),
886                    SequenceToMDString(Inst->getContext(),
887                                       NewSeq)};
888   Node = MDNode::get(Inst->getContext(),
889                      ArrayRef<Value*>(tmp, 3));
890
891   Inst->setMetadata(NodeId, Node);
892 }
893
894 /// Add to the beginning of the basic block llvm.ptr.annotations which show the
895 /// state of a pointer at the entrance to a basic block.
896 static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
897                                             Value *Ptr, Sequence Seq) {
898   // If we have a target identifier, make sure that we match it before
899   // continuing.
900   if(!ARCAnnotationTargetIdentifier.empty() &&
901      !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
902     return;
903
904   Module *M = BB->getParent()->getParent();
905   LLVMContext &C = M->getContext();
906   Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
907   Type *I8XX = PointerType::getUnqual(I8X);
908   Type *Params[] = {I8XX, I8XX};
909   FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
910                                         ArrayRef<Type*>(Params, 2),
911                                         /*isVarArg=*/false);
912   Constant *Callee = M->getOrInsertFunction(Name, FTy);
913
914   IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
915
916   Value *PtrName;
917   StringRef Tmp = Ptr->getName();
918   if (nullptr == (PtrName = M->getGlobalVariable(Tmp, true))) {
919     Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
920                                                          Tmp + "_STR");
921     PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
922                                  cast<Constant>(ActualPtrName), Tmp);
923   }
924
925   Value *S;
926   std::string SeqStr = SequenceToString(Seq);
927   if (nullptr == (S = M->getGlobalVariable(SeqStr, true))) {
928     Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
929                                                          SeqStr + "_STR");
930     S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
931                            cast<Constant>(ActualPtrName), SeqStr);
932   }
933
934   Builder.CreateCall2(Callee, PtrName, S);
935 }
936
937 /// Add to the end of the basic block llvm.ptr.annotations which show the state
938 /// of the pointer at the bottom of the basic block.
939 static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
940                                               Value *Ptr, Sequence Seq) {
941   // If we have a target identifier, make sure that we match it before emitting
942   // an annotation.
943   if(!ARCAnnotationTargetIdentifier.empty() &&
944      !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
945     return;
946
947   Module *M = BB->getParent()->getParent();
948   LLVMContext &C = M->getContext();
949   Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
950   Type *I8XX = PointerType::getUnqual(I8X);
951   Type *Params[] = {I8XX, I8XX};
952   FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
953                                         ArrayRef<Type*>(Params, 2),
954                                         /*isVarArg=*/false);
955   Constant *Callee = M->getOrInsertFunction(Name, FTy);
956
957   IRBuilder<> Builder(BB, std::prev(BB->end()));
958
959   Value *PtrName;
960   StringRef Tmp = Ptr->getName();
961   if (nullptr == (PtrName = M->getGlobalVariable(Tmp, true))) {
962     Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
963                                                          Tmp + "_STR");
964     PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
965                                  cast<Constant>(ActualPtrName), Tmp);
966   }
967
968   Value *S;
969   std::string SeqStr = SequenceToString(Seq);
970   if (nullptr == (S = M->getGlobalVariable(SeqStr, true))) {
971     Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
972                                                          SeqStr + "_STR");
973     S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
974                            cast<Constant>(ActualPtrName), SeqStr);
975   }
976   Builder.CreateCall2(Callee, PtrName, S);
977 }
978
979 /// Adds a source annotation to pointer and a state change annotation to Inst
980 /// referencing the source annotation and the old/new state of pointer.
981 static void GenerateARCAnnotation(unsigned InstMDId,
982                                   unsigned PtrMDId,
983                                   Instruction *Inst,
984                                   Value *Ptr,
985                                   Sequence OldSeq,
986                                   Sequence NewSeq) {
987   if (EnableARCAnnotations) {
988     // If we have a target identifier, make sure that we match it before
989     // emitting an annotation.
990     if(!ARCAnnotationTargetIdentifier.empty() &&
991        !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
992       return;
993
994     // First generate the source annotation on our pointer. This will return an
995     // MDString* if Ptr actually comes from an instruction implying we can put
996     // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
997     // then we know that our pointer is from an Argument so we put a reference
998     // to the argument number.
999     //
1000     // The point of this is to make it easy for the
1001     // llvm-arc-annotation-processor tool to cross reference where the source
1002     // pointer is in the LLVM IR since the LLVM IR parser does not submit such
1003     // information via debug info for backends to use (since why would anyone
1004     // need such a thing from LLVM IR besides in non-standard cases
1005     // [i.e. this]).
1006     MDString *SourcePtrMDNode =
1007       AppendMDNodeToSourcePtr(PtrMDId, Ptr);
1008     AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
1009                              NewSeq);
1010   }
1011 }
1012
1013 // The actual interface for accessing the above functionality is defined via
1014 // some simple macros which are defined below. We do this so that the user does
1015 // not need to pass in what metadata id is needed resulting in cleaner code and
1016 // additionally since it provides an easy way to conditionally no-op all
1017 // annotation support in a non-debug build.
1018
1019 /// Use this macro to annotate a sequence state change when processing
1020 /// instructions bottom up,
1021 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new)                          \
1022   GenerateARCAnnotation(ARCAnnotationBottomUpMDKind,                    \
1023                         ARCAnnotationProvenanceSourceMDKind, (inst),    \
1024                         const_cast<Value*>(ptr), (old), (new))
1025 /// Use this macro to annotate a sequence state change when processing
1026 /// instructions top down.
1027 #define ANNOTATE_TOPDOWN(inst, ptr, old, new)                           \
1028   GenerateARCAnnotation(ARCAnnotationTopDownMDKind,                     \
1029                         ARCAnnotationProvenanceSourceMDKind, (inst),    \
1030                         const_cast<Value*>(ptr), (old), (new))
1031
1032 #define ANNOTATE_BB(_states, _bb, _name, _type, _direction)                   \
1033   do {                                                                        \
1034     if (EnableARCAnnotations) {                                               \
1035       for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
1036           E = (_states)._direction##_ptr_end(); I != E; ++I) {                \
1037         Value *Ptr = const_cast<Value*>(I->first);                            \
1038         Sequence Seq = I->second.GetSeq();                                    \
1039         GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq);         \
1040       }                                                                       \
1041     }                                                                         \
1042   } while (0)
1043
1044 #define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock)                       \
1045     ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
1046                 Entrance, bottom_up)
1047 #define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock)                         \
1048     ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend",   \
1049                 Terminator, bottom_up)
1050 #define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock)                        \
1051     ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart",  \
1052                 Entrance, top_down)
1053 #define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock)                          \
1054     ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend",    \
1055                 Terminator, top_down)
1056
1057 #else // !ARC_ANNOTATION
1058 // If annotations are off, noop.
1059 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
1060 #define ANNOTATE_TOPDOWN(inst, ptr, old, new)
1061 #define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
1062 #define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
1063 #define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
1064 #define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
1065 #endif // !ARC_ANNOTATION
1066
1067 namespace {
1068   /// \brief The main ARC optimization pass.
1069   class ObjCARCOpt : public FunctionPass {
1070     bool Changed;
1071     ProvenanceAnalysis PA;
1072     ARCRuntimeEntryPoints EP;
1073
1074     // This is used to track if a pointer is stored into an alloca.
1075     DenseSet<const Value *> MultiOwnersSet;
1076
1077     /// A flag indicating whether this optimization pass should run.
1078     bool Run;
1079
1080     /// Flags which determine whether each of the interesting runtine functions
1081     /// is in fact used in the current function.
1082     unsigned UsedInThisFunction;
1083
1084     /// The Metadata Kind for clang.imprecise_release metadata.
1085     unsigned ImpreciseReleaseMDKind;
1086
1087     /// The Metadata Kind for clang.arc.copy_on_escape metadata.
1088     unsigned CopyOnEscapeMDKind;
1089
1090     /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
1091     unsigned NoObjCARCExceptionsMDKind;
1092
1093 #ifdef ARC_ANNOTATIONS
1094     /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1095     unsigned ARCAnnotationBottomUpMDKind;
1096     /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1097     unsigned ARCAnnotationTopDownMDKind;
1098     /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1099     unsigned ARCAnnotationProvenanceSourceMDKind;
1100 #endif // ARC_ANNOATIONS
1101
1102     bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1103     void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1104                                    InstructionClass &Class);
1105     void OptimizeIndividualCalls(Function &F);
1106
1107     void CheckForCFGHazards(const BasicBlock *BB,
1108                             DenseMap<const BasicBlock *, BBState> &BBStates,
1109                             BBState &MyStates) const;
1110     bool VisitInstructionBottomUp(Instruction *Inst,
1111                                   BasicBlock *BB,
1112                                   MapVector<Value *, RRInfo> &Retains,
1113                                   BBState &MyStates);
1114     bool VisitBottomUp(BasicBlock *BB,
1115                        DenseMap<const BasicBlock *, BBState> &BBStates,
1116                        MapVector<Value *, RRInfo> &Retains);
1117     bool VisitInstructionTopDown(Instruction *Inst,
1118                                  DenseMap<Value *, RRInfo> &Releases,
1119                                  BBState &MyStates);
1120     bool VisitTopDown(BasicBlock *BB,
1121                       DenseMap<const BasicBlock *, BBState> &BBStates,
1122                       DenseMap<Value *, RRInfo> &Releases);
1123     bool Visit(Function &F,
1124                DenseMap<const BasicBlock *, BBState> &BBStates,
1125                MapVector<Value *, RRInfo> &Retains,
1126                DenseMap<Value *, RRInfo> &Releases);
1127
1128     void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1129                    MapVector<Value *, RRInfo> &Retains,
1130                    DenseMap<Value *, RRInfo> &Releases,
1131                    SmallVectorImpl<Instruction *> &DeadInsts,
1132                    Module *M);
1133
1134     bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1135                                MapVector<Value *, RRInfo> &Retains,
1136                                DenseMap<Value *, RRInfo> &Releases,
1137                                Module *M,
1138                                SmallVectorImpl<Instruction *> &NewRetains,
1139                                SmallVectorImpl<Instruction *> &NewReleases,
1140                                SmallVectorImpl<Instruction *> &DeadInsts,
1141                                RRInfo &RetainsToMove,
1142                                RRInfo &ReleasesToMove,
1143                                Value *Arg,
1144                                bool KnownSafe,
1145                                bool &AnyPairsCompletelyEliminated);
1146
1147     bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1148                               MapVector<Value *, RRInfo> &Retains,
1149                               DenseMap<Value *, RRInfo> &Releases,
1150                               Module *M);
1151
1152     void OptimizeWeakCalls(Function &F);
1153
1154     bool OptimizeSequences(Function &F);
1155
1156     void OptimizeReturns(Function &F);
1157
1158 #ifndef NDEBUG
1159     void GatherStatistics(Function &F, bool AfterOptimization = false);
1160 #endif
1161
1162     void getAnalysisUsage(AnalysisUsage &AU) const override;
1163     bool doInitialization(Module &M) override;
1164     bool runOnFunction(Function &F) override;
1165     void releaseMemory() override;
1166
1167   public:
1168     static char ID;
1169     ObjCARCOpt() : FunctionPass(ID) {
1170       initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1171     }
1172   };
1173 }
1174
1175 char ObjCARCOpt::ID = 0;
1176 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1177                       "objc-arc", "ObjC ARC optimization", false, false)
1178 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1179 INITIALIZE_PASS_END(ObjCARCOpt,
1180                     "objc-arc", "ObjC ARC optimization", false, false)
1181
1182 Pass *llvm::createObjCARCOptPass() {
1183   return new ObjCARCOpt();
1184 }
1185
1186 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1187   AU.addRequired<ObjCARCAliasAnalysis>();
1188   AU.addRequired<AliasAnalysis>();
1189   // ARC optimization doesn't currently split critical edges.
1190   AU.setPreservesCFG();
1191 }
1192
1193 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1194 /// not a return value.  Or, if it can be paired with an
1195 /// objc_autoreleaseReturnValue, delete the pair and return true.
1196 bool
1197 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1198   // Check for the argument being from an immediately preceding call or invoke.
1199   const Value *Arg = GetObjCArg(RetainRV);
1200   ImmutableCallSite CS(Arg);
1201   if (const Instruction *Call = CS.getInstruction()) {
1202     if (Call->getParent() == RetainRV->getParent()) {
1203       BasicBlock::const_iterator I = Call;
1204       ++I;
1205       while (IsNoopInstruction(I)) ++I;
1206       if (&*I == RetainRV)
1207         return false;
1208     } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
1209       BasicBlock *RetainRVParent = RetainRV->getParent();
1210       if (II->getNormalDest() == RetainRVParent) {
1211         BasicBlock::const_iterator I = RetainRVParent->begin();
1212         while (IsNoopInstruction(I)) ++I;
1213         if (&*I == RetainRV)
1214           return false;
1215       }
1216     }
1217   }
1218
1219   // Check for being preceded by an objc_autoreleaseReturnValue on the same
1220   // pointer. In this case, we can delete the pair.
1221   BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1222   if (I != Begin) {
1223     do --I; while (I != Begin && IsNoopInstruction(I));
1224     if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1225         GetObjCArg(I) == Arg) {
1226       Changed = true;
1227       ++NumPeeps;
1228
1229       DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1230                    << "Erasing " << *RetainRV << "\n");
1231
1232       EraseInstruction(I);
1233       EraseInstruction(RetainRV);
1234       return true;
1235     }
1236   }
1237
1238   // Turn it to a plain objc_retain.
1239   Changed = true;
1240   ++NumPeeps;
1241
1242   DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
1243                   "objc_retain since the operand is not a return value.\n"
1244                   "Old = " << *RetainRV << "\n");
1245
1246   Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
1247   cast<CallInst>(RetainRV)->setCalledFunction(NewDecl);
1248
1249   DEBUG(dbgs() << "New = " << *RetainRV << "\n");
1250
1251   return false;
1252 }
1253
1254 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1255 /// used as a return value.
1256 void
1257 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1258                                       InstructionClass &Class) {
1259   // Check for a return of the pointer value.
1260   const Value *Ptr = GetObjCArg(AutoreleaseRV);
1261   SmallVector<const Value *, 2> Users;
1262   Users.push_back(Ptr);
1263   do {
1264     Ptr = Users.pop_back_val();
1265     for (const User *U : Ptr->users()) {
1266       if (isa<ReturnInst>(U) || GetBasicInstructionClass(U) == IC_RetainRV)
1267         return;
1268       if (isa<BitCastInst>(U))
1269         Users.push_back(U);
1270     }
1271   } while (!Users.empty());
1272
1273   Changed = true;
1274   ++NumPeeps;
1275
1276   DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
1277                   "objc_autorelease since its operand is not used as a return "
1278                   "value.\n"
1279                   "Old = " << *AutoreleaseRV << "\n");
1280
1281   CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1282   Constant *NewDecl = EP.get(ARCRuntimeEntryPoints::EPT_Autorelease);
1283   AutoreleaseRVCI->setCalledFunction(NewDecl);
1284   AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
1285   Class = IC_Autorelease;
1286
1287   DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
1288
1289 }
1290
1291 /// Visit each call, one at a time, and make simplifications without doing any
1292 /// additional analysis.
1293 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1294   DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
1295   // Reset all the flags in preparation for recomputing them.
1296   UsedInThisFunction = 0;
1297
1298   // Visit all objc_* calls in F.
1299   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1300     Instruction *Inst = &*I++;
1301
1302     InstructionClass Class = GetBasicInstructionClass(Inst);
1303
1304     DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
1305
1306     switch (Class) {
1307     default: break;
1308
1309     // Delete no-op casts. These function calls have special semantics, but
1310     // the semantics are entirely implemented via lowering in the front-end,
1311     // so by the time they reach the optimizer, they are just no-op calls
1312     // which return their argument.
1313     //
1314     // There are gray areas here, as the ability to cast reference-counted
1315     // pointers to raw void* and back allows code to break ARC assumptions,
1316     // however these are currently considered to be unimportant.
1317     case IC_NoopCast:
1318       Changed = true;
1319       ++NumNoops;
1320       DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
1321       EraseInstruction(Inst);
1322       continue;
1323
1324     // If the pointer-to-weak-pointer is null, it's undefined behavior.
1325     case IC_StoreWeak:
1326     case IC_LoadWeak:
1327     case IC_LoadWeakRetained:
1328     case IC_InitWeak:
1329     case IC_DestroyWeak: {
1330       CallInst *CI = cast<CallInst>(Inst);
1331       if (IsNullOrUndef(CI->getArgOperand(0))) {
1332         Changed = true;
1333         Type *Ty = CI->getArgOperand(0)->getType();
1334         new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1335                       Constant::getNullValue(Ty),
1336                       CI);
1337         llvm::Value *NewValue = UndefValue::get(CI->getType());
1338         DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1339                        "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1340         CI->replaceAllUsesWith(NewValue);
1341         CI->eraseFromParent();
1342         continue;
1343       }
1344       break;
1345     }
1346     case IC_CopyWeak:
1347     case IC_MoveWeak: {
1348       CallInst *CI = cast<CallInst>(Inst);
1349       if (IsNullOrUndef(CI->getArgOperand(0)) ||
1350           IsNullOrUndef(CI->getArgOperand(1))) {
1351         Changed = true;
1352         Type *Ty = CI->getArgOperand(0)->getType();
1353         new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1354                       Constant::getNullValue(Ty),
1355                       CI);
1356
1357         llvm::Value *NewValue = UndefValue::get(CI->getType());
1358         DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1359                         "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1360
1361         CI->replaceAllUsesWith(NewValue);
1362         CI->eraseFromParent();
1363         continue;
1364       }
1365       break;
1366     }
1367     case IC_RetainRV:
1368       if (OptimizeRetainRVCall(F, Inst))
1369         continue;
1370       break;
1371     case IC_AutoreleaseRV:
1372       OptimizeAutoreleaseRVCall(F, Inst, Class);
1373       break;
1374     }
1375
1376     // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
1377     if (IsAutorelease(Class) && Inst->use_empty()) {
1378       CallInst *Call = cast<CallInst>(Inst);
1379       const Value *Arg = Call->getArgOperand(0);
1380       Arg = FindSingleUseIdentifiedObject(Arg);
1381       if (Arg) {
1382         Changed = true;
1383         ++NumAutoreleases;
1384
1385         // Create the declaration lazily.
1386         LLVMContext &C = Inst->getContext();
1387
1388         Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Release);
1389         CallInst *NewCall = CallInst::Create(Decl, Call->getArgOperand(0), "",
1390                                              Call);
1391         NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
1392
1393         DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1394               "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1395               << *NewCall << "\n");
1396
1397         EraseInstruction(Call);
1398         Inst = NewCall;
1399         Class = IC_Release;
1400       }
1401     }
1402
1403     // For functions which can never be passed stack arguments, add
1404     // a tail keyword.
1405     if (IsAlwaysTail(Class)) {
1406       Changed = true;
1407       DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1408                       "passed stack args: " << *Inst << "\n");
1409       cast<CallInst>(Inst)->setTailCall();
1410     }
1411
1412     // Ensure that functions that can never have a "tail" keyword due to the
1413     // semantics of ARC truly do not do so.
1414     if (IsNeverTail(Class)) {
1415       Changed = true;
1416       DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
1417             "\n");
1418       cast<CallInst>(Inst)->setTailCall(false);
1419     }
1420
1421     // Set nounwind as needed.
1422     if (IsNoThrow(Class)) {
1423       Changed = true;
1424       DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1425                    << "\n");
1426       cast<CallInst>(Inst)->setDoesNotThrow();
1427     }
1428
1429     if (!IsNoopOnNull(Class)) {
1430       UsedInThisFunction |= 1 << Class;
1431       continue;
1432     }
1433
1434     const Value *Arg = GetObjCArg(Inst);
1435
1436     // ARC calls with null are no-ops. Delete them.
1437     if (IsNullOrUndef(Arg)) {
1438       Changed = true;
1439       ++NumNoops;
1440       DEBUG(dbgs() << "ARC calls with  null are no-ops. Erasing: " << *Inst
1441             << "\n");
1442       EraseInstruction(Inst);
1443       continue;
1444     }
1445
1446     // Keep track of which of retain, release, autorelease, and retain_block
1447     // are actually present in this function.
1448     UsedInThisFunction |= 1 << Class;
1449
1450     // If Arg is a PHI, and one or more incoming values to the
1451     // PHI are null, and the call is control-equivalent to the PHI, and there
1452     // are no relevant side effects between the PHI and the call, the call
1453     // could be pushed up to just those paths with non-null incoming values.
1454     // For now, don't bother splitting critical edges for this.
1455     SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1456     Worklist.push_back(std::make_pair(Inst, Arg));
1457     do {
1458       std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1459       Inst = Pair.first;
1460       Arg = Pair.second;
1461
1462       const PHINode *PN = dyn_cast<PHINode>(Arg);
1463       if (!PN) continue;
1464
1465       // Determine if the PHI has any null operands, or any incoming
1466       // critical edges.
1467       bool HasNull = false;
1468       bool HasCriticalEdges = false;
1469       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1470         Value *Incoming =
1471           StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1472         if (IsNullOrUndef(Incoming))
1473           HasNull = true;
1474         else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1475                    .getNumSuccessors() != 1) {
1476           HasCriticalEdges = true;
1477           break;
1478         }
1479       }
1480       // If we have null operands and no critical edges, optimize.
1481       if (!HasCriticalEdges && HasNull) {
1482         SmallPtrSet<Instruction *, 4> DependingInstructions;
1483         SmallPtrSet<const BasicBlock *, 4> Visited;
1484
1485         // Check that there is nothing that cares about the reference
1486         // count between the call and the phi.
1487         switch (Class) {
1488         case IC_Retain:
1489         case IC_RetainBlock:
1490           // These can always be moved up.
1491           break;
1492         case IC_Release:
1493           // These can't be moved across things that care about the retain
1494           // count.
1495           FindDependencies(NeedsPositiveRetainCount, Arg,
1496                            Inst->getParent(), Inst,
1497                            DependingInstructions, Visited, PA);
1498           break;
1499         case IC_Autorelease:
1500           // These can't be moved across autorelease pool scope boundaries.
1501           FindDependencies(AutoreleasePoolBoundary, Arg,
1502                            Inst->getParent(), Inst,
1503                            DependingInstructions, Visited, PA);
1504           break;
1505         case IC_RetainRV:
1506         case IC_AutoreleaseRV:
1507           // Don't move these; the RV optimization depends on the autoreleaseRV
1508           // being tail called, and the retainRV being immediately after a call
1509           // (which might still happen if we get lucky with codegen layout, but
1510           // it's not worth taking the chance).
1511           continue;
1512         default:
1513           llvm_unreachable("Invalid dependence flavor");
1514         }
1515
1516         if (DependingInstructions.size() == 1 &&
1517             *DependingInstructions.begin() == PN) {
1518           Changed = true;
1519           ++NumPartialNoops;
1520           // Clone the call into each predecessor that has a non-null value.
1521           CallInst *CInst = cast<CallInst>(Inst);
1522           Type *ParamTy = CInst->getArgOperand(0)->getType();
1523           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1524             Value *Incoming =
1525               StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1526             if (!IsNullOrUndef(Incoming)) {
1527               CallInst *Clone = cast<CallInst>(CInst->clone());
1528               Value *Op = PN->getIncomingValue(i);
1529               Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1530               if (Op->getType() != ParamTy)
1531                 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1532               Clone->setArgOperand(0, Op);
1533               Clone->insertBefore(InsertPos);
1534
1535               DEBUG(dbgs() << "Cloning "
1536                            << *CInst << "\n"
1537                            "And inserting clone at " << *InsertPos << "\n");
1538               Worklist.push_back(std::make_pair(Clone, Incoming));
1539             }
1540           }
1541           // Erase the original call.
1542           DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
1543           EraseInstruction(CInst);
1544           continue;
1545         }
1546       }
1547     } while (!Worklist.empty());
1548   }
1549 }
1550
1551 /// If we have a top down pointer in the S_Use state, make sure that there are
1552 /// no CFG hazards by checking the states of various bottom up pointers.
1553 static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1554                                  const bool SuccSRRIKnownSafe,
1555                                  PtrState &S,
1556                                  bool &SomeSuccHasSame,
1557                                  bool &AllSuccsHaveSame,
1558                                  bool &NotAllSeqEqualButKnownSafe,
1559                                  bool &ShouldContinue) {
1560   switch (SuccSSeq) {
1561   case S_CanRelease: {
1562     if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
1563       S.ClearSequenceProgress();
1564       break;
1565     }
1566     S.SetCFGHazardAfflicted(true);
1567     ShouldContinue = true;
1568     break;
1569   }
1570   case S_Use:
1571     SomeSuccHasSame = true;
1572     break;
1573   case S_Stop:
1574   case S_Release:
1575   case S_MovableRelease:
1576     if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
1577       AllSuccsHaveSame = false;
1578     else
1579       NotAllSeqEqualButKnownSafe = true;
1580     break;
1581   case S_Retain:
1582     llvm_unreachable("bottom-up pointer in retain state!");
1583   case S_None:
1584     llvm_unreachable("This should have been handled earlier.");
1585   }
1586 }
1587
1588 /// If we have a Top Down pointer in the S_CanRelease state, make sure that
1589 /// there are no CFG hazards by checking the states of various bottom up
1590 /// pointers.
1591 static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1592                                         const bool SuccSRRIKnownSafe,
1593                                         PtrState &S,
1594                                         bool &SomeSuccHasSame,
1595                                         bool &AllSuccsHaveSame,
1596                                         bool &NotAllSeqEqualButKnownSafe) {
1597   switch (SuccSSeq) {
1598   case S_CanRelease:
1599     SomeSuccHasSame = true;
1600     break;
1601   case S_Stop:
1602   case S_Release:
1603   case S_MovableRelease:
1604   case S_Use:
1605     if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
1606       AllSuccsHaveSame = false;
1607     else
1608       NotAllSeqEqualButKnownSafe = true;
1609     break;
1610   case S_Retain:
1611     llvm_unreachable("bottom-up pointer in retain state!");
1612   case S_None:
1613     llvm_unreachable("This should have been handled earlier.");
1614   }
1615 }
1616
1617 /// Check for critical edges, loop boundaries, irreducible control flow, or
1618 /// other CFG structures where moving code across the edge would result in it
1619 /// being executed more.
1620 void
1621 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1622                                DenseMap<const BasicBlock *, BBState> &BBStates,
1623                                BBState &MyStates) const {
1624   // If any top-down local-use or possible-dec has a succ which is earlier in
1625   // the sequence, forget it.
1626   for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
1627          E = MyStates.top_down_ptr_end(); I != E; ++I) {
1628     PtrState &S = I->second;
1629     const Sequence Seq = I->second.GetSeq();
1630
1631     // We only care about S_Retain, S_CanRelease, and S_Use.
1632     if (Seq == S_None)
1633       continue;
1634
1635     // Make sure that if extra top down states are added in the future that this
1636     // code is updated to handle it.
1637     assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1638            "Unknown top down sequence state.");
1639
1640     const Value *Arg = I->first;
1641     const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1642     bool SomeSuccHasSame = false;
1643     bool AllSuccsHaveSame = true;
1644     bool NotAllSeqEqualButKnownSafe = false;
1645
1646     succ_const_iterator SI(TI), SE(TI, false);
1647
1648     for (; SI != SE; ++SI) {
1649       // If VisitBottomUp has pointer information for this successor, take
1650       // what we know about it.
1651       const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1652         BBStates.find(*SI);
1653       assert(BBI != BBStates.end());
1654       const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1655       const Sequence SuccSSeq = SuccS.GetSeq();
1656
1657       // If bottom up, the pointer is in an S_None state, clear the sequence
1658       // progress since the sequence in the bottom up state finished
1659       // suggesting a mismatch in between retains/releases. This is true for
1660       // all three cases that we are handling here: S_Retain, S_Use, and
1661       // S_CanRelease.
1662       if (SuccSSeq == S_None) {
1663         S.ClearSequenceProgress();
1664         continue;
1665       }
1666
1667       // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1668       // checks.
1669       const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
1670
1671       // *NOTE* We do not use Seq from above here since we are allowing for
1672       // S.GetSeq() to change while we are visiting basic blocks.
1673       switch(S.GetSeq()) {
1674       case S_Use: {
1675         bool ShouldContinue = false;
1676         CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1677                              AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
1678                              ShouldContinue);
1679         if (ShouldContinue)
1680           continue;
1681         break;
1682       }
1683       case S_CanRelease: {
1684         CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1685                                     SomeSuccHasSame, AllSuccsHaveSame,
1686                                     NotAllSeqEqualButKnownSafe);
1687         break;
1688       }
1689       case S_Retain:
1690       case S_None:
1691       case S_Stop:
1692       case S_Release:
1693       case S_MovableRelease:
1694         break;
1695       }
1696     }
1697
1698     // If the state at the other end of any of the successor edges
1699     // matches the current state, require all edges to match. This
1700     // guards against loops in the middle of a sequence.
1701     if (SomeSuccHasSame && !AllSuccsHaveSame) {
1702       S.ClearSequenceProgress();
1703     } else if (NotAllSeqEqualButKnownSafe) {
1704       // If we would have cleared the state foregoing the fact that we are known
1705       // safe, stop code motion. This is because whether or not it is safe to
1706       // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1707       // are allowed to perform code motion.
1708       S.SetCFGHazardAfflicted(true);
1709     }
1710   }
1711 }
1712
1713 bool
1714 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
1715                                      BasicBlock *BB,
1716                                      MapVector<Value *, RRInfo> &Retains,
1717                                      BBState &MyStates) {
1718   bool NestingDetected = false;
1719   InstructionClass Class = GetInstructionClass(Inst);
1720   const Value *Arg = nullptr;
1721
1722   DEBUG(dbgs() << "Class: " << Class << "\n");
1723
1724   switch (Class) {
1725   case IC_Release: {
1726     Arg = GetObjCArg(Inst);
1727
1728     PtrState &S = MyStates.getPtrBottomUpState(Arg);
1729
1730     // If we see two releases in a row on the same pointer. If so, make
1731     // a note, and we'll cicle back to revisit it after we've
1732     // hopefully eliminated the second release, which may allow us to
1733     // eliminate the first release too.
1734     // Theoretically we could implement removal of nested retain+release
1735     // pairs by making PtrState hold a stack of states, but this is
1736     // simple and avoids adding overhead for the non-nested case.
1737     if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
1738       DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
1739       NestingDetected = true;
1740     }
1741
1742     MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
1743     Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1744     ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1745     S.ResetSequenceProgress(NewSeq);
1746     S.SetReleaseMetadata(ReleaseMetadata);
1747     S.SetKnownSafe(S.HasKnownPositiveRefCount());
1748     S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
1749     S.InsertCall(Inst);
1750     S.SetKnownPositiveRefCount();
1751     break;
1752   }
1753   case IC_RetainBlock:
1754     // In OptimizeIndividualCalls, we have strength reduced all optimizable
1755     // objc_retainBlocks to objc_retains. Thus at this point any
1756     // objc_retainBlocks that we see are not optimizable.
1757     break;
1758   case IC_Retain:
1759   case IC_RetainRV: {
1760     Arg = GetObjCArg(Inst);
1761
1762     PtrState &S = MyStates.getPtrBottomUpState(Arg);
1763     S.SetKnownPositiveRefCount();
1764
1765     Sequence OldSeq = S.GetSeq();
1766     switch (OldSeq) {
1767     case S_Stop:
1768     case S_Release:
1769     case S_MovableRelease:
1770     case S_Use:
1771       // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1772       // imprecise release, clear our reverse insertion points.
1773       if (OldSeq != S_Use || S.IsTrackingImpreciseReleases())
1774         S.ClearReverseInsertPts();
1775       // FALL THROUGH
1776     case S_CanRelease:
1777       // Don't do retain+release tracking for IC_RetainRV, because it's
1778       // better to let it remain as the first instruction after a call.
1779       if (Class != IC_RetainRV)
1780         Retains[Inst] = S.GetRRInfo();
1781       S.ClearSequenceProgress();
1782       break;
1783     case S_None:
1784       break;
1785     case S_Retain:
1786       llvm_unreachable("bottom-up pointer in retain state!");
1787     }
1788     ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
1789     // A retain moving bottom up can be a use.
1790     break;
1791   }
1792   case IC_AutoreleasepoolPop:
1793     // Conservatively, clear MyStates for all known pointers.
1794     MyStates.clearBottomUpPointers();
1795     return NestingDetected;
1796   case IC_AutoreleasepoolPush:
1797   case IC_None:
1798     // These are irrelevant.
1799     return NestingDetected;
1800   case IC_User:
1801     // If we have a store into an alloca of a pointer we are tracking, the
1802     // pointer has multiple owners implying that we must be more conservative.
1803     //
1804     // This comes up in the context of a pointer being ``KnownSafe''. In the
1805     // presence of a block being initialized, the frontend will emit the
1806     // objc_retain on the original pointer and the release on the pointer loaded
1807     // from the alloca. The optimizer will through the provenance analysis
1808     // realize that the two are related, but since we only require KnownSafe in
1809     // one direction, will match the inner retain on the original pointer with
1810     // the guard release on the original pointer. This is fixed by ensuring that
1811     // in the presence of allocas we only unconditionally remove pointers if
1812     // both our retain and our release are KnownSafe.
1813     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1814       if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
1815         BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
1816           StripPointerCastsAndObjCCalls(SI->getValueOperand()));
1817         if (I != MyStates.bottom_up_ptr_end())
1818           MultiOwnersSet.insert(I->first);
1819       }
1820     }
1821     break;
1822   default:
1823     break;
1824   }
1825
1826   // Consider any other possible effects of this instruction on each
1827   // pointer being tracked.
1828   for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1829        ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1830     const Value *Ptr = MI->first;
1831     if (Ptr == Arg)
1832       continue; // Handled above.
1833     PtrState &S = MI->second;
1834     Sequence Seq = S.GetSeq();
1835
1836     // Check for possible releases.
1837     if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
1838       DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1839             << "\n");
1840       S.ClearKnownPositiveRefCount();
1841       switch (Seq) {
1842       case S_Use:
1843         S.SetSeq(S_CanRelease);
1844         ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
1845         continue;
1846       case S_CanRelease:
1847       case S_Release:
1848       case S_MovableRelease:
1849       case S_Stop:
1850       case S_None:
1851         break;
1852       case S_Retain:
1853         llvm_unreachable("bottom-up pointer in retain state!");
1854       }
1855     }
1856
1857     // Check for possible direct uses.
1858     switch (Seq) {
1859     case S_Release:
1860     case S_MovableRelease:
1861       if (CanUse(Inst, Ptr, PA, Class)) {
1862         DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1863               << "\n");
1864         assert(!S.HasReverseInsertPts());
1865         // If this is an invoke instruction, we're scanning it as part of
1866         // one of its successor blocks, since we can't insert code after it
1867         // in its own block, and we don't want to split critical edges.
1868         if (isa<InvokeInst>(Inst))
1869           S.InsertReverseInsertPt(BB->getFirstInsertionPt());
1870         else
1871           S.InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
1872         S.SetSeq(S_Use);
1873         ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
1874       } else if (Seq == S_Release && IsUser(Class)) {
1875         DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
1876               << "\n");
1877         // Non-movable releases depend on any possible objc pointer use.
1878         S.SetSeq(S_Stop);
1879         ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
1880         assert(!S.HasReverseInsertPts());
1881         // As above; handle invoke specially.
1882         if (isa<InvokeInst>(Inst))
1883           S.InsertReverseInsertPt(BB->getFirstInsertionPt());
1884         else
1885           S.InsertReverseInsertPt(std::next(BasicBlock::iterator(Inst)));
1886       }
1887       break;
1888     case S_Stop:
1889       if (CanUse(Inst, Ptr, PA, Class)) {
1890         DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
1891               << "\n");
1892         S.SetSeq(S_Use);
1893         ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
1894       }
1895       break;
1896     case S_CanRelease:
1897     case S_Use:
1898     case S_None:
1899       break;
1900     case S_Retain:
1901       llvm_unreachable("bottom-up pointer in retain state!");
1902     }
1903   }
1904
1905   return NestingDetected;
1906 }
1907
1908 bool
1909 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1910                           DenseMap<const BasicBlock *, BBState> &BBStates,
1911                           MapVector<Value *, RRInfo> &Retains) {
1912
1913   DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
1914
1915   bool NestingDetected = false;
1916   BBState &MyStates = BBStates[BB];
1917
1918   // Merge the states from each successor to compute the initial state
1919   // for the current block.
1920   BBState::edge_iterator SI(MyStates.succ_begin()),
1921                          SE(MyStates.succ_end());
1922   if (SI != SE) {
1923     const BasicBlock *Succ = *SI;
1924     DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1925     assert(I != BBStates.end());
1926     MyStates.InitFromSucc(I->second);
1927     ++SI;
1928     for (; SI != SE; ++SI) {
1929       Succ = *SI;
1930       I = BBStates.find(Succ);
1931       assert(I != BBStates.end());
1932       MyStates.MergeSucc(I->second);
1933     }
1934   }
1935
1936   // If ARC Annotations are enabled, output the current state of pointers at the
1937   // bottom of the basic block.
1938   ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
1939
1940   // Visit all the instructions, bottom-up.
1941   for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
1942     Instruction *Inst = std::prev(I);
1943
1944     // Invoke instructions are visited as part of their successors (below).
1945     if (isa<InvokeInst>(Inst))
1946       continue;
1947
1948     DEBUG(dbgs() << "Visiting " << *Inst << "\n");
1949
1950     NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1951   }
1952
1953   // If there's a predecessor with an invoke, visit the invoke as if it were
1954   // part of this block, since we can't insert code after an invoke in its own
1955   // block, and we don't want to split critical edges.
1956   for (BBState::edge_iterator PI(MyStates.pred_begin()),
1957        PE(MyStates.pred_end()); PI != PE; ++PI) {
1958     BasicBlock *Pred = *PI;
1959     if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1960       NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
1961   }
1962
1963   // If ARC Annotations are enabled, output the current state of pointers at the
1964   // top of the basic block.
1965   ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
1966
1967   return NestingDetected;
1968 }
1969
1970 bool
1971 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1972                                     DenseMap<Value *, RRInfo> &Releases,
1973                                     BBState &MyStates) {
1974   bool NestingDetected = false;
1975   InstructionClass Class = GetInstructionClass(Inst);
1976   const Value *Arg = nullptr;
1977
1978   switch (Class) {
1979   case IC_RetainBlock:
1980     // In OptimizeIndividualCalls, we have strength reduced all optimizable
1981     // objc_retainBlocks to objc_retains. Thus at this point any
1982     // objc_retainBlocks that we see are not optimizable.
1983     break;
1984   case IC_Retain:
1985   case IC_RetainRV: {
1986     Arg = GetObjCArg(Inst);
1987
1988     PtrState &S = MyStates.getPtrTopDownState(Arg);
1989
1990     // Don't do retain+release tracking for IC_RetainRV, because it's
1991     // better to let it remain as the first instruction after a call.
1992     if (Class != IC_RetainRV) {
1993       // If we see two retains in a row on the same pointer. If so, make
1994       // a note, and we'll cicle back to revisit it after we've
1995       // hopefully eliminated the second retain, which may allow us to
1996       // eliminate the first retain too.
1997       // Theoretically we could implement removal of nested retain+release
1998       // pairs by making PtrState hold a stack of states, but this is
1999       // simple and avoids adding overhead for the non-nested case.
2000       if (S.GetSeq() == S_Retain)
2001         NestingDetected = true;
2002
2003       ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
2004       S.ResetSequenceProgress(S_Retain);
2005       S.SetKnownSafe(S.HasKnownPositiveRefCount());
2006       S.InsertCall(Inst);
2007     }
2008
2009     S.SetKnownPositiveRefCount();
2010
2011     // A retain can be a potential use; procede to the generic checking
2012     // code below.
2013     break;
2014   }
2015   case IC_Release: {
2016     Arg = GetObjCArg(Inst);
2017
2018     PtrState &S = MyStates.getPtrTopDownState(Arg);
2019     S.ClearKnownPositiveRefCount();
2020
2021     Sequence OldSeq = S.GetSeq();
2022
2023     MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2024
2025     switch (OldSeq) {
2026     case S_Retain:
2027     case S_CanRelease:
2028       if (OldSeq == S_Retain || ReleaseMetadata != nullptr)
2029         S.ClearReverseInsertPts();
2030       // FALL THROUGH
2031     case S_Use:
2032       S.SetReleaseMetadata(ReleaseMetadata);
2033       S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
2034       Releases[Inst] = S.GetRRInfo();
2035       ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
2036       S.ClearSequenceProgress();
2037       break;
2038     case S_None:
2039       break;
2040     case S_Stop:
2041     case S_Release:
2042     case S_MovableRelease:
2043       llvm_unreachable("top-down pointer in release state!");
2044     }
2045     break;
2046   }
2047   case IC_AutoreleasepoolPop:
2048     // Conservatively, clear MyStates for all known pointers.
2049     MyStates.clearTopDownPointers();
2050     return NestingDetected;
2051   case IC_AutoreleasepoolPush:
2052   case IC_None:
2053     // These are irrelevant.
2054     return NestingDetected;
2055   default:
2056     break;
2057   }
2058
2059   // Consider any other possible effects of this instruction on each
2060   // pointer being tracked.
2061   for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2062        ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2063     const Value *Ptr = MI->first;
2064     if (Ptr == Arg)
2065       continue; // Handled above.
2066     PtrState &S = MI->second;
2067     Sequence Seq = S.GetSeq();
2068
2069     // Check for possible releases.
2070     if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2071       DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
2072             << "\n");
2073       S.ClearKnownPositiveRefCount();
2074       switch (Seq) {
2075       case S_Retain:
2076         S.SetSeq(S_CanRelease);
2077         ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
2078         assert(!S.HasReverseInsertPts());
2079         S.InsertReverseInsertPt(Inst);
2080
2081         // One call can't cause a transition from S_Retain to S_CanRelease
2082         // and S_CanRelease to S_Use. If we've made the first transition,
2083         // we're done.
2084         continue;
2085       case S_Use:
2086       case S_CanRelease:
2087       case S_None:
2088         break;
2089       case S_Stop:
2090       case S_Release:
2091       case S_MovableRelease:
2092         llvm_unreachable("top-down pointer in release state!");
2093       }
2094     }
2095
2096     // Check for possible direct uses.
2097     switch (Seq) {
2098     case S_CanRelease:
2099       if (CanUse(Inst, Ptr, PA, Class)) {
2100         DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2101               << "\n");
2102         S.SetSeq(S_Use);
2103         ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2104       }
2105       break;
2106     case S_Retain:
2107     case S_Use:
2108     case S_None:
2109       break;
2110     case S_Stop:
2111     case S_Release:
2112     case S_MovableRelease:
2113       llvm_unreachable("top-down pointer in release state!");
2114     }
2115   }
2116
2117   return NestingDetected;
2118 }
2119
2120 bool
2121 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2122                          DenseMap<const BasicBlock *, BBState> &BBStates,
2123                          DenseMap<Value *, RRInfo> &Releases) {
2124   DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
2125   bool NestingDetected = false;
2126   BBState &MyStates = BBStates[BB];
2127
2128   // Merge the states from each predecessor to compute the initial state
2129   // for the current block.
2130   BBState::edge_iterator PI(MyStates.pred_begin()),
2131                          PE(MyStates.pred_end());
2132   if (PI != PE) {
2133     const BasicBlock *Pred = *PI;
2134     DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2135     assert(I != BBStates.end());
2136     MyStates.InitFromPred(I->second);
2137     ++PI;
2138     for (; PI != PE; ++PI) {
2139       Pred = *PI;
2140       I = BBStates.find(Pred);
2141       assert(I != BBStates.end());
2142       MyStates.MergePred(I->second);
2143     }
2144   }
2145
2146   // If ARC Annotations are enabled, output the current state of pointers at the
2147   // top of the basic block.
2148   ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
2149
2150   // Visit all the instructions, top-down.
2151   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2152     Instruction *Inst = I;
2153
2154     DEBUG(dbgs() << "Visiting " << *Inst << "\n");
2155
2156     NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
2157   }
2158
2159   // If ARC Annotations are enabled, output the current state of pointers at the
2160   // bottom of the basic block.
2161   ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
2162
2163 #ifdef ARC_ANNOTATIONS
2164   if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
2165 #endif
2166   CheckForCFGHazards(BB, BBStates, MyStates);
2167   return NestingDetected;
2168 }
2169
2170 static void
2171 ComputePostOrders(Function &F,
2172                   SmallVectorImpl<BasicBlock *> &PostOrder,
2173                   SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2174                   unsigned NoObjCARCExceptionsMDKind,
2175                   DenseMap<const BasicBlock *, BBState> &BBStates) {
2176   /// The visited set, for doing DFS walks.
2177   SmallPtrSet<BasicBlock *, 16> Visited;
2178
2179   // Do DFS, computing the PostOrder.
2180   SmallPtrSet<BasicBlock *, 16> OnStack;
2181   SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2182
2183   // Functions always have exactly one entry block, and we don't have
2184   // any other block that we treat like an entry block.
2185   BasicBlock *EntryBB = &F.getEntryBlock();
2186   BBState &MyStates = BBStates[EntryBB];
2187   MyStates.SetAsEntry();
2188   TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2189   SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
2190   Visited.insert(EntryBB);
2191   OnStack.insert(EntryBB);
2192   do {
2193   dfs_next_succ:
2194     BasicBlock *CurrBB = SuccStack.back().first;
2195     TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2196     succ_iterator SE(TI, false);
2197
2198     while (SuccStack.back().second != SE) {
2199       BasicBlock *SuccBB = *SuccStack.back().second++;
2200       if (Visited.insert(SuccBB)) {
2201         TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2202         SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
2203         BBStates[CurrBB].addSucc(SuccBB);
2204         BBState &SuccStates = BBStates[SuccBB];
2205         SuccStates.addPred(CurrBB);
2206         OnStack.insert(SuccBB);
2207         goto dfs_next_succ;
2208       }
2209
2210       if (!OnStack.count(SuccBB)) {
2211         BBStates[CurrBB].addSucc(SuccBB);
2212         BBStates[SuccBB].addPred(CurrBB);
2213       }
2214     }
2215     OnStack.erase(CurrBB);
2216     PostOrder.push_back(CurrBB);
2217     SuccStack.pop_back();
2218   } while (!SuccStack.empty());
2219
2220   Visited.clear();
2221
2222   // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2223   // Functions may have many exits, and there also blocks which we treat
2224   // as exits due to ignored edges.
2225   SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2226   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2227     BasicBlock *ExitBB = I;
2228     BBState &MyStates = BBStates[ExitBB];
2229     if (!MyStates.isExit())
2230       continue;
2231
2232     MyStates.SetAsExit();
2233
2234     PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
2235     Visited.insert(ExitBB);
2236     while (!PredStack.empty()) {
2237     reverse_dfs_next_succ:
2238       BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2239       while (PredStack.back().second != PE) {
2240         BasicBlock *BB = *PredStack.back().second++;
2241         if (Visited.insert(BB)) {
2242           PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
2243           goto reverse_dfs_next_succ;
2244         }
2245       }
2246       ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2247     }
2248   }
2249 }
2250
2251 // Visit the function both top-down and bottom-up.
2252 bool
2253 ObjCARCOpt::Visit(Function &F,
2254                   DenseMap<const BasicBlock *, BBState> &BBStates,
2255                   MapVector<Value *, RRInfo> &Retains,
2256                   DenseMap<Value *, RRInfo> &Releases) {
2257
2258   // Use reverse-postorder traversals, because we magically know that loops
2259   // will be well behaved, i.e. they won't repeatedly call retain on a single
2260   // pointer without doing a release. We can't use the ReversePostOrderTraversal
2261   // class here because we want the reverse-CFG postorder to consider each
2262   // function exit point, and we want to ignore selected cycle edges.
2263   SmallVector<BasicBlock *, 16> PostOrder;
2264   SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2265   ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2266                     NoObjCARCExceptionsMDKind,
2267                     BBStates);
2268
2269   // Use reverse-postorder on the reverse CFG for bottom-up.
2270   bool BottomUpNestingDetected = false;
2271   for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2272        ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2273        I != E; ++I)
2274     BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
2275
2276   // Use reverse-postorder for top-down.
2277   bool TopDownNestingDetected = false;
2278   for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2279        PostOrder.rbegin(), E = PostOrder.rend();
2280        I != E; ++I)
2281     TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
2282
2283   return TopDownNestingDetected && BottomUpNestingDetected;
2284 }
2285
2286 /// Move the calls in RetainsToMove and ReleasesToMove.
2287 void ObjCARCOpt::MoveCalls(Value *Arg,
2288                            RRInfo &RetainsToMove,
2289                            RRInfo &ReleasesToMove,
2290                            MapVector<Value *, RRInfo> &Retains,
2291                            DenseMap<Value *, RRInfo> &Releases,
2292                            SmallVectorImpl<Instruction *> &DeadInsts,
2293                            Module *M) {
2294   Type *ArgTy = Arg->getType();
2295   Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2296
2297   DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
2298
2299   // Insert the new retain and release calls.
2300   for (Instruction *InsertPt : ReleasesToMove.ReverseInsertPts) {
2301     Value *MyArg = ArgTy == ParamTy ? Arg :
2302                    new BitCastInst(Arg, ParamTy, "", InsertPt);
2303     Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
2304     CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
2305     Call->setDoesNotThrow();
2306     Call->setTailCall();
2307
2308     DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
2309                     "At insertion point: " << *InsertPt << "\n");
2310   }
2311   for (Instruction *InsertPt : RetainsToMove.ReverseInsertPts) {
2312     Value *MyArg = ArgTy == ParamTy ? Arg :
2313                    new BitCastInst(Arg, ParamTy, "", InsertPt);
2314     Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Release);
2315     CallInst *Call = CallInst::Create(Decl, MyArg, "", InsertPt);
2316     // Attach a clang.imprecise_release metadata tag, if appropriate.
2317     if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2318       Call->setMetadata(ImpreciseReleaseMDKind, M);
2319     Call->setDoesNotThrow();
2320     if (ReleasesToMove.IsTailCallRelease)
2321       Call->setTailCall();
2322
2323     DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2324                     "At insertion point: " << *InsertPt << "\n");
2325   }
2326
2327   // Delete the original retain and release calls.
2328   for (Instruction *OrigRetain : RetainsToMove.Calls) {
2329     Retains.blot(OrigRetain);
2330     DeadInsts.push_back(OrigRetain);
2331     DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
2332   }
2333   for (Instruction *OrigRelease : ReleasesToMove.Calls) {
2334     Releases.erase(OrigRelease);
2335     DeadInsts.push_back(OrigRelease);
2336     DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
2337   }
2338
2339 }
2340
2341 bool
2342 ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2343                                     &BBStates,
2344                                   MapVector<Value *, RRInfo> &Retains,
2345                                   DenseMap<Value *, RRInfo> &Releases,
2346                                   Module *M,
2347                                   SmallVectorImpl<Instruction *> &NewRetains,
2348                                   SmallVectorImpl<Instruction *> &NewReleases,
2349                                   SmallVectorImpl<Instruction *> &DeadInsts,
2350                                   RRInfo &RetainsToMove,
2351                                   RRInfo &ReleasesToMove,
2352                                   Value *Arg,
2353                                   bool KnownSafe,
2354                                   bool &AnyPairsCompletelyEliminated) {
2355   // If a pair happens in a region where it is known that the reference count
2356   // is already incremented, we can similarly ignore possible decrements unless
2357   // we are dealing with a retainable object with multiple provenance sources.
2358   bool KnownSafeTD = true, KnownSafeBU = true;
2359   bool MultipleOwners = false;
2360   bool CFGHazardAfflicted = false;
2361
2362   // Connect the dots between the top-down-collected RetainsToMove and
2363   // bottom-up-collected ReleasesToMove to form sets of related calls.
2364   // This is an iterative process so that we connect multiple releases
2365   // to multiple retains if needed.
2366   unsigned OldDelta = 0;
2367   unsigned NewDelta = 0;
2368   unsigned OldCount = 0;
2369   unsigned NewCount = 0;
2370   bool FirstRelease = true;
2371   for (;;) {
2372     for (SmallVectorImpl<Instruction *>::const_iterator
2373            NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2374       Instruction *NewRetain = *NI;
2375       MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2376       assert(It != Retains.end());
2377       const RRInfo &NewRetainRRI = It->second;
2378       KnownSafeTD &= NewRetainRRI.KnownSafe;
2379       MultipleOwners =
2380         MultipleOwners || MultiOwnersSet.count(GetObjCArg(NewRetain));
2381       for (Instruction *NewRetainRelease : NewRetainRRI.Calls) {
2382         DenseMap<Value *, RRInfo>::const_iterator Jt =
2383           Releases.find(NewRetainRelease);
2384         if (Jt == Releases.end())
2385           return false;
2386         const RRInfo &NewRetainReleaseRRI = Jt->second;
2387
2388         // If the release does not have a reference to the retain as well,
2389         // something happened which is unaccounted for. Do not do anything.
2390         //
2391         // This can happen if we catch an additive overflow during path count
2392         // merging.
2393         if (!NewRetainReleaseRRI.Calls.count(NewRetain))
2394           return false;
2395
2396         if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2397
2398           // If we overflow when we compute the path count, don't remove/move
2399           // anything.
2400           const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
2401           unsigned PathCount = BBState::OverflowOccurredValue;
2402           if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2403             return false;
2404           assert(PathCount != BBState::OverflowOccurredValue &&
2405                  "PathCount at this point can not be "
2406                  "OverflowOccurredValue.");
2407           OldDelta -= PathCount;
2408
2409           // Merge the ReleaseMetadata and IsTailCallRelease values.
2410           if (FirstRelease) {
2411             ReleasesToMove.ReleaseMetadata =
2412               NewRetainReleaseRRI.ReleaseMetadata;
2413             ReleasesToMove.IsTailCallRelease =
2414               NewRetainReleaseRRI.IsTailCallRelease;
2415             FirstRelease = false;
2416           } else {
2417             if (ReleasesToMove.ReleaseMetadata !=
2418                 NewRetainReleaseRRI.ReleaseMetadata)
2419               ReleasesToMove.ReleaseMetadata = nullptr;
2420             if (ReleasesToMove.IsTailCallRelease !=
2421                 NewRetainReleaseRRI.IsTailCallRelease)
2422               ReleasesToMove.IsTailCallRelease = false;
2423           }
2424
2425           // Collect the optimal insertion points.
2426           if (!KnownSafe)
2427             for (Instruction *RIP : NewRetainReleaseRRI.ReverseInsertPts) {
2428               if (ReleasesToMove.ReverseInsertPts.insert(RIP)) {
2429                 // If we overflow when we compute the path count, don't
2430                 // remove/move anything.
2431                 const BBState &RIPBBState = BBStates[RIP->getParent()];
2432                 PathCount = BBState::OverflowOccurredValue;
2433                 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2434                   return false;
2435                 assert(PathCount != BBState::OverflowOccurredValue &&
2436                        "PathCount at this point can not be "
2437                        "OverflowOccurredValue.");
2438                 NewDelta -= PathCount;
2439               }
2440             }
2441           NewReleases.push_back(NewRetainRelease);
2442         }
2443       }
2444     }
2445     NewRetains.clear();
2446     if (NewReleases.empty()) break;
2447
2448     // Back the other way.
2449     for (SmallVectorImpl<Instruction *>::const_iterator
2450            NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2451       Instruction *NewRelease = *NI;
2452       DenseMap<Value *, RRInfo>::const_iterator It =
2453         Releases.find(NewRelease);
2454       assert(It != Releases.end());
2455       const RRInfo &NewReleaseRRI = It->second;
2456       KnownSafeBU &= NewReleaseRRI.KnownSafe;
2457       CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
2458       for (Instruction *NewReleaseRetain : NewReleaseRRI.Calls) {
2459         MapVector<Value *, RRInfo>::const_iterator Jt =
2460           Retains.find(NewReleaseRetain);
2461         if (Jt == Retains.end())
2462           return false;
2463         const RRInfo &NewReleaseRetainRRI = Jt->second;
2464
2465         // If the retain does not have a reference to the release as well,
2466         // something happened which is unaccounted for. Do not do anything.
2467         //
2468         // This can happen if we catch an additive overflow during path count
2469         // merging.
2470         if (!NewReleaseRetainRRI.Calls.count(NewRelease))
2471           return false;
2472
2473         if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2474           // If we overflow when we compute the path count, don't remove/move
2475           // anything.
2476           const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
2477           unsigned PathCount = BBState::OverflowOccurredValue;
2478           if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2479             return false;
2480           assert(PathCount != BBState::OverflowOccurredValue &&
2481                  "PathCount at this point can not be "
2482                  "OverflowOccurredValue.");
2483           OldDelta += PathCount;
2484           OldCount += PathCount;
2485
2486           // Collect the optimal insertion points.
2487           if (!KnownSafe)
2488             for (Instruction *RIP : NewReleaseRetainRRI.ReverseInsertPts) {
2489               if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2490                 // If we overflow when we compute the path count, don't
2491                 // remove/move anything.
2492                 const BBState &RIPBBState = BBStates[RIP->getParent()];
2493
2494                 PathCount = BBState::OverflowOccurredValue;
2495                 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2496                   return false;
2497                 assert(PathCount != BBState::OverflowOccurredValue &&
2498                        "PathCount at this point can not be "
2499                        "OverflowOccurredValue.");
2500                 NewDelta += PathCount;
2501                 NewCount += PathCount;
2502               }
2503             }
2504           NewRetains.push_back(NewReleaseRetain);
2505         }
2506       }
2507     }
2508     NewReleases.clear();
2509     if (NewRetains.empty()) break;
2510   }
2511
2512   // If the pointer is known incremented in 1 direction and we do not have
2513   // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2514   // to be known safe in both directions.
2515   bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2516     ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2517   if (UnconditionallySafe) {
2518     RetainsToMove.ReverseInsertPts.clear();
2519     ReleasesToMove.ReverseInsertPts.clear();
2520     NewCount = 0;
2521   } else {
2522     // Determine whether the new insertion points we computed preserve the
2523     // balance of retain and release calls through the program.
2524     // TODO: If the fully aggressive solution isn't valid, try to find a
2525     // less aggressive solution which is.
2526     if (NewDelta != 0)
2527       return false;
2528
2529     // At this point, we are not going to remove any RR pairs, but we still are
2530     // able to move RR pairs. If one of our pointers is afflicted with
2531     // CFGHazards, we cannot perform such code motion so exit early.
2532     const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
2533       ReleasesToMove.ReverseInsertPts.size();
2534     if (CFGHazardAfflicted && WillPerformCodeMotion)
2535       return false;
2536   }
2537
2538   // Determine whether the original call points are balanced in the retain and
2539   // release calls through the program. If not, conservatively don't touch
2540   // them.
2541   // TODO: It's theoretically possible to do code motion in this case, as
2542   // long as the existing imbalances are maintained.
2543   if (OldDelta != 0)
2544     return false;
2545
2546 #ifdef ARC_ANNOTATIONS
2547   // Do not move calls if ARC annotations are requested.
2548   if (EnableARCAnnotations)
2549     return false;
2550 #endif // ARC_ANNOTATIONS
2551
2552   Changed = true;
2553   assert(OldCount != 0 && "Unreachable code?");
2554   NumRRs += OldCount - NewCount;
2555   // Set to true if we completely removed any RR pairs.
2556   AnyPairsCompletelyEliminated = NewCount == 0;
2557
2558   // We can move calls!
2559   return true;
2560 }
2561
2562 /// Identify pairings between the retains and releases, and delete and/or move
2563 /// them.
2564 bool
2565 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2566                                    &BBStates,
2567                                  MapVector<Value *, RRInfo> &Retains,
2568                                  DenseMap<Value *, RRInfo> &Releases,
2569                                  Module *M) {
2570   DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2571
2572   bool AnyPairsCompletelyEliminated = false;
2573   RRInfo RetainsToMove;
2574   RRInfo ReleasesToMove;
2575   SmallVector<Instruction *, 4> NewRetains;
2576   SmallVector<Instruction *, 4> NewReleases;
2577   SmallVector<Instruction *, 8> DeadInsts;
2578
2579   // Visit each retain.
2580   for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2581        E = Retains.end(); I != E; ++I) {
2582     Value *V = I->first;
2583     if (!V) continue; // blotted
2584
2585     Instruction *Retain = cast<Instruction>(V);
2586
2587     DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
2588
2589     Value *Arg = GetObjCArg(Retain);
2590
2591     // If the object being released is in static or stack storage, we know it's
2592     // not being managed by ObjC reference counting, so we can delete pairs
2593     // regardless of what possible decrements or uses lie between them.
2594     bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
2595
2596     // A constant pointer can't be pointing to an object on the heap. It may
2597     // be reference-counted, but it won't be deleted.
2598     if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2599       if (const GlobalVariable *GV =
2600             dyn_cast<GlobalVariable>(
2601               StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2602         if (GV->isConstant())
2603           KnownSafe = true;
2604
2605     // Connect the dots between the top-down-collected RetainsToMove and
2606     // bottom-up-collected ReleasesToMove to form sets of related calls.
2607     NewRetains.push_back(Retain);
2608     bool PerformMoveCalls =
2609       ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2610                             NewReleases, DeadInsts, RetainsToMove,
2611                             ReleasesToMove, Arg, KnownSafe,
2612                             AnyPairsCompletelyEliminated);
2613
2614     if (PerformMoveCalls) {
2615       // Ok, everything checks out and we're all set. Let's move/delete some
2616       // code!
2617       MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2618                 Retains, Releases, DeadInsts, M);
2619     }
2620
2621     // Clean up state for next retain.
2622     NewReleases.clear();
2623     NewRetains.clear();
2624     RetainsToMove.clear();
2625     ReleasesToMove.clear();
2626   }
2627
2628   // Now that we're done moving everything, we can delete the newly dead
2629   // instructions, as we no longer need them as insert points.
2630   while (!DeadInsts.empty())
2631     EraseInstruction(DeadInsts.pop_back_val());
2632
2633   return AnyPairsCompletelyEliminated;
2634 }
2635
2636 /// Weak pointer optimizations.
2637 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2638   DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
2639
2640   // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2641   // itself because it uses AliasAnalysis and we need to do provenance
2642   // queries instead.
2643   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2644     Instruction *Inst = &*I++;
2645
2646     DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
2647
2648     InstructionClass Class = GetBasicInstructionClass(Inst);
2649     if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2650       continue;
2651
2652     // Delete objc_loadWeak calls with no users.
2653     if (Class == IC_LoadWeak && Inst->use_empty()) {
2654       Inst->eraseFromParent();
2655       continue;
2656     }
2657
2658     // TODO: For now, just look for an earlier available version of this value
2659     // within the same block. Theoretically, we could do memdep-style non-local
2660     // analysis too, but that would want caching. A better approach would be to
2661     // use the technique that EarlyCSE uses.
2662     inst_iterator Current = std::prev(I);
2663     BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2664     for (BasicBlock::iterator B = CurrentBB->begin(),
2665                               J = Current.getInstructionIterator();
2666          J != B; --J) {
2667       Instruction *EarlierInst = &*std::prev(J);
2668       InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2669       switch (EarlierClass) {
2670       case IC_LoadWeak:
2671       case IC_LoadWeakRetained: {
2672         // If this is loading from the same pointer, replace this load's value
2673         // with that one.
2674         CallInst *Call = cast<CallInst>(Inst);
2675         CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2676         Value *Arg = Call->getArgOperand(0);
2677         Value *EarlierArg = EarlierCall->getArgOperand(0);
2678         switch (PA.getAA()->alias(Arg, EarlierArg)) {
2679         case AliasAnalysis::MustAlias:
2680           Changed = true;
2681           // If the load has a builtin retain, insert a plain retain for it.
2682           if (Class == IC_LoadWeakRetained) {
2683             Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
2684             CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
2685             CI->setTailCall();
2686           }
2687           // Zap the fully redundant load.
2688           Call->replaceAllUsesWith(EarlierCall);
2689           Call->eraseFromParent();
2690           goto clobbered;
2691         case AliasAnalysis::MayAlias:
2692         case AliasAnalysis::PartialAlias:
2693           goto clobbered;
2694         case AliasAnalysis::NoAlias:
2695           break;
2696         }
2697         break;
2698       }
2699       case IC_StoreWeak:
2700       case IC_InitWeak: {
2701         // If this is storing to the same pointer and has the same size etc.
2702         // replace this load's value with the stored value.
2703         CallInst *Call = cast<CallInst>(Inst);
2704         CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2705         Value *Arg = Call->getArgOperand(0);
2706         Value *EarlierArg = EarlierCall->getArgOperand(0);
2707         switch (PA.getAA()->alias(Arg, EarlierArg)) {
2708         case AliasAnalysis::MustAlias:
2709           Changed = true;
2710           // If the load has a builtin retain, insert a plain retain for it.
2711           if (Class == IC_LoadWeakRetained) {
2712             Constant *Decl = EP.get(ARCRuntimeEntryPoints::EPT_Retain);
2713             CallInst *CI = CallInst::Create(Decl, EarlierCall, "", Call);
2714             CI->setTailCall();
2715           }
2716           // Zap the fully redundant load.
2717           Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2718           Call->eraseFromParent();
2719           goto clobbered;
2720         case AliasAnalysis::MayAlias:
2721         case AliasAnalysis::PartialAlias:
2722           goto clobbered;
2723         case AliasAnalysis::NoAlias:
2724           break;
2725         }
2726         break;
2727       }
2728       case IC_MoveWeak:
2729       case IC_CopyWeak:
2730         // TOOD: Grab the copied value.
2731         goto clobbered;
2732       case IC_AutoreleasepoolPush:
2733       case IC_None:
2734       case IC_IntrinsicUser:
2735       case IC_User:
2736         // Weak pointers are only modified through the weak entry points
2737         // (and arbitrary calls, which could call the weak entry points).
2738         break;
2739       default:
2740         // Anything else could modify the weak pointer.
2741         goto clobbered;
2742       }
2743     }
2744   clobbered:;
2745   }
2746
2747   // Then, for each destroyWeak with an alloca operand, check to see if
2748   // the alloca and all its users can be zapped.
2749   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2750     Instruction *Inst = &*I++;
2751     InstructionClass Class = GetBasicInstructionClass(Inst);
2752     if (Class != IC_DestroyWeak)
2753       continue;
2754
2755     CallInst *Call = cast<CallInst>(Inst);
2756     Value *Arg = Call->getArgOperand(0);
2757     if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2758       for (User *U : Alloca->users()) {
2759         const Instruction *UserInst = cast<Instruction>(U);
2760         switch (GetBasicInstructionClass(UserInst)) {
2761         case IC_InitWeak:
2762         case IC_StoreWeak:
2763         case IC_DestroyWeak:
2764           continue;
2765         default:
2766           goto done;
2767         }
2768       }
2769       Changed = true;
2770       for (auto UI = Alloca->user_begin(), UE = Alloca->user_end(); UI != UE;) {
2771         CallInst *UserInst = cast<CallInst>(*UI++);
2772         switch (GetBasicInstructionClass(UserInst)) {
2773         case IC_InitWeak:
2774         case IC_StoreWeak:
2775           // These functions return their second argument.
2776           UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2777           break;
2778         case IC_DestroyWeak:
2779           // No return value.
2780           break;
2781         default:
2782           llvm_unreachable("alloca really is used!");
2783         }
2784         UserInst->eraseFromParent();
2785       }
2786       Alloca->eraseFromParent();
2787     done:;
2788     }
2789   }
2790 }
2791
2792 /// Identify program paths which execute sequences of retains and releases which
2793 /// can be eliminated.
2794 bool ObjCARCOpt::OptimizeSequences(Function &F) {
2795   // Releases, Retains - These are used to store the results of the main flow
2796   // analysis. These use Value* as the key instead of Instruction* so that the
2797   // map stays valid when we get around to rewriting code and calls get
2798   // replaced by arguments.
2799   DenseMap<Value *, RRInfo> Releases;
2800   MapVector<Value *, RRInfo> Retains;
2801
2802   // This is used during the traversal of the function to track the
2803   // states for each identified object at each block.
2804   DenseMap<const BasicBlock *, BBState> BBStates;
2805
2806   // Analyze the CFG of the function, and all instructions.
2807   bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2808
2809   // Transform.
2810   bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2811                                                            Releases,
2812                                                            F.getParent());
2813
2814   // Cleanup.
2815   MultiOwnersSet.clear();
2816
2817   return AnyPairsCompletelyEliminated && NestingDetected;
2818 }
2819
2820 /// Check if there is a dependent call earlier that does not have anything in
2821 /// between the Retain and the call that can affect the reference count of their
2822 /// shared pointer argument. Note that Retain need not be in BB.
2823 static bool
2824 HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2825                              SmallPtrSetImpl<Instruction *> &DepInsts,
2826                              SmallPtrSetImpl<const BasicBlock *> &Visited,
2827                              ProvenanceAnalysis &PA) {
2828   FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2829                    DepInsts, Visited, PA);
2830   if (DepInsts.size() != 1)
2831     return false;
2832
2833   CallInst *Call =
2834     dyn_cast_or_null<CallInst>(*DepInsts.begin());
2835
2836   // Check that the pointer is the return value of the call.
2837   if (!Call || Arg != Call)
2838     return false;
2839
2840   // Check that the call is a regular call.
2841   InstructionClass Class = GetBasicInstructionClass(Call);
2842   if (Class != IC_CallOrUser && Class != IC_Call)
2843     return false;
2844
2845   return true;
2846 }
2847
2848 /// Find a dependent retain that precedes the given autorelease for which there
2849 /// is nothing in between the two instructions that can affect the ref count of
2850 /// Arg.
2851 static CallInst *
2852 FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2853                                   Instruction *Autorelease,
2854                                   SmallPtrSetImpl<Instruction *> &DepInsts,
2855                                   SmallPtrSetImpl<const BasicBlock *> &Visited,
2856                                   ProvenanceAnalysis &PA) {
2857   FindDependencies(CanChangeRetainCount, Arg,
2858                    BB, Autorelease, DepInsts, Visited, PA);
2859   if (DepInsts.size() != 1)
2860     return nullptr;
2861
2862   CallInst *Retain =
2863     dyn_cast_or_null<CallInst>(*DepInsts.begin());
2864
2865   // Check that we found a retain with the same argument.
2866   if (!Retain ||
2867       !IsRetain(GetBasicInstructionClass(Retain)) ||
2868       GetObjCArg(Retain) != Arg) {
2869     return nullptr;
2870   }
2871
2872   return Retain;
2873 }
2874
2875 /// Look for an ``autorelease'' instruction dependent on Arg such that there are
2876 /// no instructions dependent on Arg that need a positive ref count in between
2877 /// the autorelease and the ret.
2878 static CallInst *
2879 FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
2880                                        ReturnInst *Ret,
2881                                        SmallPtrSetImpl<Instruction *> &DepInsts,
2882                                        SmallPtrSetImpl<const BasicBlock *> &V,
2883                                        ProvenanceAnalysis &PA) {
2884   FindDependencies(NeedsPositiveRetainCount, Arg,
2885                    BB, Ret, DepInsts, V, PA);
2886   if (DepInsts.size() != 1)
2887     return nullptr;
2888
2889   CallInst *Autorelease =
2890     dyn_cast_or_null<CallInst>(*DepInsts.begin());
2891   if (!Autorelease)
2892     return nullptr;
2893   InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
2894   if (!IsAutorelease(AutoreleaseClass))
2895     return nullptr;
2896   if (GetObjCArg(Autorelease) != Arg)
2897     return nullptr;
2898
2899   return Autorelease;
2900 }
2901
2902 /// Look for this pattern:
2903 /// \code
2904 ///    %call = call i8* @something(...)
2905 ///    %2 = call i8* @objc_retain(i8* %call)
2906 ///    %3 = call i8* @objc_autorelease(i8* %2)
2907 ///    ret i8* %3
2908 /// \endcode
2909 /// And delete the retain and autorelease.
2910 void ObjCARCOpt::OptimizeReturns(Function &F) {
2911   if (!F.getReturnType()->isPointerTy())
2912     return;
2913
2914   DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
2915
2916   SmallPtrSet<Instruction *, 4> DependingInstructions;
2917   SmallPtrSet<const BasicBlock *, 4> Visited;
2918   for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2919     BasicBlock *BB = FI;
2920     ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
2921
2922     DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
2923
2924     if (!Ret)
2925       continue;
2926
2927     const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
2928
2929     // Look for an ``autorelease'' instruction that is a predecessor of Ret and
2930     // dependent on Arg such that there are no instructions dependent on Arg
2931     // that need a positive ref count in between the autorelease and Ret.
2932     CallInst *Autorelease =
2933       FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
2934                                              DependingInstructions, Visited,
2935                                              PA);
2936     DependingInstructions.clear();
2937     Visited.clear();
2938
2939     if (!Autorelease)
2940       continue;
2941
2942     CallInst *Retain =
2943       FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
2944                                         DependingInstructions, Visited, PA);
2945     DependingInstructions.clear();
2946     Visited.clear();
2947
2948     if (!Retain)
2949       continue;
2950
2951     // Check that there is nothing that can affect the reference count
2952     // between the retain and the call.  Note that Retain need not be in BB.
2953     bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
2954                                                           DependingInstructions,
2955                                                           Visited, PA);
2956     DependingInstructions.clear();
2957     Visited.clear();
2958
2959     if (!HasSafePathToCall)
2960       continue;
2961
2962     // If so, we can zap the retain and autorelease.
2963     Changed = true;
2964     ++NumRets;
2965     DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
2966           << *Autorelease << "\n");
2967     EraseInstruction(Retain);
2968     EraseInstruction(Autorelease);
2969   }
2970 }
2971
2972 #ifndef NDEBUG
2973 void
2974 ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
2975   llvm::Statistic &NumRetains =
2976     AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
2977   llvm::Statistic &NumReleases =
2978     AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
2979
2980   for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2981     Instruction *Inst = &*I++;
2982     switch (GetBasicInstructionClass(Inst)) {
2983     default:
2984       break;
2985     case IC_Retain:
2986       ++NumRetains;
2987       break;
2988     case IC_Release:
2989       ++NumReleases;
2990       break;
2991     }
2992   }
2993 }
2994 #endif
2995
2996 bool ObjCARCOpt::doInitialization(Module &M) {
2997   if (!EnableARCOpts)
2998     return false;
2999
3000   // If nothing in the Module uses ARC, don't do anything.
3001   Run = ModuleHasARC(M);
3002   if (!Run)
3003     return false;
3004
3005   // Identify the imprecise release metadata kind.
3006   ImpreciseReleaseMDKind =
3007     M.getContext().getMDKindID("clang.imprecise_release");
3008   CopyOnEscapeMDKind =
3009     M.getContext().getMDKindID("clang.arc.copy_on_escape");
3010   NoObjCARCExceptionsMDKind =
3011     M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3012 #ifdef ARC_ANNOTATIONS
3013   ARCAnnotationBottomUpMDKind =
3014     M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3015   ARCAnnotationTopDownMDKind =
3016     M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3017   ARCAnnotationProvenanceSourceMDKind =
3018     M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3019 #endif // ARC_ANNOTATIONS
3020
3021   // Intuitively, objc_retain and others are nocapture, however in practice
3022   // they are not, because they return their argument value. And objc_release
3023   // calls finalizers which can have arbitrary side effects.
3024
3025   // Initialize our runtime entry point cache.
3026   EP.Initialize(&M);
3027
3028   return false;
3029 }
3030
3031 bool ObjCARCOpt::runOnFunction(Function &F) {
3032   if (!EnableARCOpts)
3033     return false;
3034
3035   // If nothing in the Module uses ARC, don't do anything.
3036   if (!Run)
3037     return false;
3038
3039   Changed = false;
3040
3041   DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3042         "\n");
3043
3044   PA.setAA(&getAnalysis<AliasAnalysis>());
3045
3046 #ifndef NDEBUG
3047   if (AreStatisticsEnabled()) {
3048     GatherStatistics(F, false);
3049   }
3050 #endif
3051
3052   // This pass performs several distinct transformations. As a compile-time aid
3053   // when compiling code that isn't ObjC, skip these if the relevant ObjC
3054   // library functions aren't declared.
3055
3056   // Preliminary optimizations. This also computes UsedInThisFunction.
3057   OptimizeIndividualCalls(F);
3058
3059   // Optimizations for weak pointers.
3060   if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3061                             (1 << IC_LoadWeakRetained) |
3062                             (1 << IC_StoreWeak) |
3063                             (1 << IC_InitWeak) |
3064                             (1 << IC_CopyWeak) |
3065                             (1 << IC_MoveWeak) |
3066                             (1 << IC_DestroyWeak)))
3067     OptimizeWeakCalls(F);
3068
3069   // Optimizations for retain+release pairs.
3070   if (UsedInThisFunction & ((1 << IC_Retain) |
3071                             (1 << IC_RetainRV) |
3072                             (1 << IC_RetainBlock)))
3073     if (UsedInThisFunction & (1 << IC_Release))
3074       // Run OptimizeSequences until it either stops making changes or
3075       // no retain+release pair nesting is detected.
3076       while (OptimizeSequences(F)) {}
3077
3078   // Optimizations if objc_autorelease is used.
3079   if (UsedInThisFunction & ((1 << IC_Autorelease) |
3080                             (1 << IC_AutoreleaseRV)))
3081     OptimizeReturns(F);
3082
3083   // Gather statistics after optimization.
3084 #ifndef NDEBUG
3085   if (AreStatisticsEnabled()) {
3086     GatherStatistics(F, true);
3087   }
3088 #endif
3089
3090   DEBUG(dbgs() << "\n");
3091
3092   return Changed;
3093 }
3094
3095 void ObjCARCOpt::releaseMemory() {
3096   PA.clear();
3097 }
3098
3099 /// @}
3100 ///