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