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