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