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