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