1 //===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This file defines ObjC ARC optimizations. ARC stands for Automatic
11 /// Reference Counting and is a system for managing reference counts for objects
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.
18 /// WARNING: This file knows about certain library functions. It recognizes them
19 /// by name, and hardwires knowledge of their semantics.
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.
25 //===----------------------------------------------------------------------===//
27 #define DEBUG_TYPE "objc-arc-opts"
29 #include "DependencyAnalysis.h"
30 #include "ObjCARCAliasAnalysis.h"
31 #include "ProvenanceAnalysis.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/DenseSet.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/IR/IRBuilder.h"
38 #include "llvm/IR/LLVMContext.h"
39 #include "llvm/Support/CFG.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
44 using namespace llvm::objcarc;
46 /// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
50 /// \brief An associative container with fast insertion-order (deterministic)
51 /// iteration over its elements. Plus the special blot operation.
52 template<class KeyT, class ValueT>
54 /// Map keys to indices in Vector.
55 typedef DenseMap<KeyT, size_t> MapTy;
58 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
63 typedef typename VectorTy::iterator iterator;
64 typedef typename VectorTy::const_iterator const_iterator;
65 iterator begin() { return Vector.begin(); }
66 iterator end() { return Vector.end(); }
67 const_iterator begin() const { return Vector.begin(); }
68 const_iterator end() const { return Vector.end(); }
72 assert(Vector.size() >= Map.size()); // May differ due to blotting.
73 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
75 assert(I->second < Vector.size());
76 assert(Vector[I->second].first == I->first);
78 for (typename VectorTy::const_iterator I = Vector.begin(),
79 E = Vector.end(); I != E; ++I)
81 (Map.count(I->first) &&
82 Map[I->first] == size_t(I - Vector.begin())));
86 ValueT &operator[](const KeyT &Arg) {
87 std::pair<typename MapTy::iterator, bool> Pair =
88 Map.insert(std::make_pair(Arg, size_t(0)));
90 size_t Num = Vector.size();
91 Pair.first->second = Num;
92 Vector.push_back(std::make_pair(Arg, ValueT()));
93 return Vector[Num].second;
95 return Vector[Pair.first->second].second;
98 std::pair<iterator, bool>
99 insert(const std::pair<KeyT, ValueT> &InsertPair) {
100 std::pair<typename MapTy::iterator, bool> Pair =
101 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
103 size_t Num = Vector.size();
104 Pair.first->second = Num;
105 Vector.push_back(InsertPair);
106 return std::make_pair(Vector.begin() + Num, true);
108 return std::make_pair(Vector.begin() + Pair.first->second, false);
111 iterator find(const KeyT &Key) {
112 typename MapTy::iterator It = Map.find(Key);
113 if (It == Map.end()) return Vector.end();
114 return Vector.begin() + It->second;
117 const_iterator find(const KeyT &Key) const {
118 typename MapTy::const_iterator It = Map.find(Key);
119 if (It == Map.end()) return Vector.end();
120 return Vector.begin() + It->second;
123 /// This is similar to erase, but instead of removing the element from the
124 /// vector, it just zeros out the key in the vector. This leaves iterators
125 /// intact, but clients must be prepared for zeroed-out keys when iterating.
126 void blot(const KeyT &Key) {
127 typename MapTy::iterator It = Map.find(Key);
128 if (It == Map.end()) return;
129 Vector[It->second].first = KeyT();
142 /// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
145 /// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
146 /// as it finds a value with multiple uses.
147 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
148 if (Arg->hasOneUse()) {
149 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
150 return FindSingleUseIdentifiedObject(BC->getOperand(0));
151 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
152 if (GEP->hasAllZeroIndices())
153 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
154 if (IsForwarding(GetBasicInstructionClass(Arg)))
155 return FindSingleUseIdentifiedObject(
156 cast<CallInst>(Arg)->getArgOperand(0));
157 if (!IsObjCIdentifiedObject(Arg))
162 // If we found an identifiable object but it has multiple uses, but they are
163 // trivial uses, we can still consider this to be a single-use value.
164 if (IsObjCIdentifiedObject(Arg)) {
165 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
168 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
178 /// \brief Test whether the given retainable object pointer escapes.
180 /// This differs from regular escape analysis in that a use as an
181 /// argument to a call is not considered an escape.
183 static bool DoesRetainableObjPtrEscape(const User *Ptr) {
184 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Target: " << *Ptr << "\n");
186 // Walk the def-use chains.
187 SmallVector<const Value *, 4> Worklist;
188 Worklist.push_back(Ptr);
189 // If Ptr has any operands add them as well.
190 for (User::const_op_iterator I = Ptr->op_begin(), E = Ptr->op_end(); I != E;
192 Worklist.push_back(*I);
195 // Ensure we do not visit any value twice.
196 SmallPtrSet<const Value *, 8> VisitedSet;
199 const Value *V = Worklist.pop_back_val();
201 DEBUG(dbgs() << "Visiting: " << *V << "\n");
203 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
205 const User *UUser = *UI;
207 DEBUG(dbgs() << "User: " << *UUser << "\n");
209 // Special - Use by a call (callee or argument) is not considered
211 switch (GetBasicInstructionClass(UUser)) {
216 case IC_AutoreleaseRV: {
217 DEBUG(dbgs() << "User copies pointer arguments. Pointer Escapes!\n");
218 // These special functions make copies of their pointer arguments.
221 case IC_IntrinsicUser:
222 // Use by the use intrinsic is not an escape.
226 // Use by an instruction which copies the value is an escape if the
227 // result is an escape.
228 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
229 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
231 if (VisitedSet.insert(UUser)) {
232 DEBUG(dbgs() << "User copies value. Ptr escapes if result escapes."
233 " Adding to list.\n");
234 Worklist.push_back(UUser);
236 DEBUG(dbgs() << "Already visited node.\n");
240 // Use by a load is not an escape.
241 if (isa<LoadInst>(UUser))
243 // Use by a store is not an escape if the use is the address.
244 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
245 if (V != SI->getValueOperand())
249 // Regular calls and other stuff are not considered escapes.
252 // Otherwise, conservatively assume an escape.
253 DEBUG(dbgs() << "Assuming ptr escapes.\n");
256 } while (!Worklist.empty());
259 DEBUG(dbgs() << "Ptr does not escape.\n");
263 /// This is a wrapper around getUnderlyingObjCPtr along the lines of
264 /// GetUnderlyingObjects except that it returns early when it sees the first
266 static inline bool AreAnyUnderlyingObjectsAnAlloca(const Value *V) {
267 SmallPtrSet<const Value *, 4> Visited;
268 SmallVector<const Value *, 4> Worklist;
269 Worklist.push_back(V);
271 const Value *P = Worklist.pop_back_val();
272 P = GetUnderlyingObjCPtr(P);
274 if (isa<AllocaInst>(P))
277 if (!Visited.insert(P))
280 if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
281 Worklist.push_back(SI->getTrueValue());
282 Worklist.push_back(SI->getFalseValue());
286 if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
287 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
288 Worklist.push_back(PN->getIncomingValue(i));
291 } while (!Worklist.empty());
299 /// \defgroup ARCOpt ARC Optimization.
302 // TODO: On code like this:
305 // stuff_that_cannot_release()
306 // objc_autorelease(%x)
307 // stuff_that_cannot_release()
309 // stuff_that_cannot_release()
310 // objc_autorelease(%x)
312 // The second retain and autorelease can be deleted.
314 // TODO: It should be possible to delete
315 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
316 // pairs if nothing is actually autoreleased between them. Also, autorelease
317 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
318 // after inlining) can be turned into plain release calls.
320 // TODO: Critical-edge splitting. If the optimial insertion point is
321 // a critical edge, the current algorithm has to fail, because it doesn't
322 // know how to split edges. It should be possible to make the optimizer
323 // think in terms of edges, rather than blocks, and then split critical
326 // TODO: OptimizeSequences could generalized to be Interprocedural.
328 // TODO: Recognize that a bunch of other objc runtime calls have
329 // non-escaping arguments and non-releasing arguments, and may be
330 // non-autoreleasing.
332 // TODO: Sink autorelease calls as far as possible. Unfortunately we
333 // usually can't sink them past other calls, which would be the main
334 // case where it would be useful.
336 // TODO: The pointer returned from objc_loadWeakRetained is retained.
338 // TODO: Delete release+retain pairs (rare).
340 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
341 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
342 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
343 STATISTIC(NumRets, "Number of return value forwarding "
344 "retain+autoreleases eliminated");
345 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
346 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
348 STATISTIC(NumRetainsBeforeOpt,
349 "Number of retains before optimization");
350 STATISTIC(NumReleasesBeforeOpt,
351 "Number of releases before optimization");
352 STATISTIC(NumRetainsAfterOpt,
353 "Number of retains after optimization");
354 STATISTIC(NumReleasesAfterOpt,
355 "Number of releases after optimization");
361 /// \brief A sequence of states that a pointer may go through in which an
362 /// objc_retain and objc_release are actually needed.
365 S_Retain, ///< objc_retain(x).
366 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement.
367 S_Use, ///< any use of x.
368 S_Stop, ///< like S_Release, but code motion is stopped.
369 S_Release, ///< objc_release(x).
370 S_MovableRelease ///< objc_release(x), !clang.imprecise_release.
373 raw_ostream &operator<<(raw_ostream &OS, const Sequence S)
374 LLVM_ATTRIBUTE_UNUSED;
375 raw_ostream &operator<<(raw_ostream &OS, const Sequence S) {
378 return OS << "S_None";
380 return OS << "S_Retain";
382 return OS << "S_CanRelease";
384 return OS << "S_Use";
386 return OS << "S_Release";
387 case S_MovableRelease:
388 return OS << "S_MovableRelease";
390 return OS << "S_Stop";
392 llvm_unreachable("Unknown sequence type.");
396 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
400 if (A == S_None || B == S_None)
403 if (A > B) std::swap(A, B);
405 // Choose the side which is further along in the sequence.
406 if ((A == S_Retain || A == S_CanRelease) &&
407 (B == S_CanRelease || B == S_Use))
410 // Choose the side which is further along in the sequence.
411 if ((A == S_Use || A == S_CanRelease) &&
412 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
414 // If both sides are releases, choose the more conservative one.
415 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
417 if (A == S_Release && B == S_MovableRelease)
425 /// \brief Unidirectional information about either a
426 /// retain-decrement-use-release sequence or release-use-decrement-retain
427 /// reverse sequence.
429 /// After an objc_retain, the reference count of the referenced
430 /// object is known to be positive. Similarly, before an objc_release, the
431 /// reference count of the referenced object is known to be positive. If
432 /// there are retain-release pairs in code regions where the retain count
433 /// is known to be positive, they can be eliminated, regardless of any side
434 /// effects between them.
436 /// Also, a retain+release pair nested within another retain+release
437 /// pair all on the known same pointer value can be eliminated, regardless
438 /// of any intervening side effects.
440 /// KnownSafe is true when either of these conditions is satisfied.
443 /// True of the objc_release calls are all marked with the "tail" keyword.
444 bool IsTailCallRelease;
446 /// If the Calls are objc_release calls and they all have a
447 /// clang.imprecise_release tag, this is the metadata tag.
448 MDNode *ReleaseMetadata;
450 /// For a top-down sequence, the set of objc_retains or
451 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
452 SmallPtrSet<Instruction *, 2> Calls;
454 /// The set of optimal insert positions for moving calls in the opposite
456 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
458 /// If this is true, we cannot perform code motion but can still remove
459 /// retain/release pairs.
460 bool CFGHazardAfflicted;
463 KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(0),
464 CFGHazardAfflicted(false) {}
468 /// Conservatively merge the two RRInfo. Returns true if a partial merge has
469 /// occured, false otherwise.
470 bool Merge(const RRInfo &Other);
472 bool IsTrackingImpreciseReleases() {
473 return ReleaseMetadata != 0;
478 void RRInfo::clear() {
480 IsTailCallRelease = false;
483 ReverseInsertPts.clear();
484 CFGHazardAfflicted = false;
487 bool RRInfo::Merge(const RRInfo &Other) {
488 // Conservatively merge the ReleaseMetadata information.
489 if (ReleaseMetadata != Other.ReleaseMetadata)
492 // Conservatively merge the boolean state.
493 KnownSafe &= Other.KnownSafe;
494 IsTailCallRelease &= Other.IsTailCallRelease;
495 CFGHazardAfflicted |= Other.CFGHazardAfflicted;
497 // Merge the call sets.
498 Calls.insert(Other.Calls.begin(), Other.Calls.end());
500 // Merge the insert point sets. If there are any differences,
501 // that makes this a partial merge.
502 bool Partial = ReverseInsertPts.size() != Other.ReverseInsertPts.size();
503 for (SmallPtrSet<Instruction *, 2>::const_iterator
504 I = Other.ReverseInsertPts.begin(),
505 E = Other.ReverseInsertPts.end(); I != E; ++I)
506 Partial |= ReverseInsertPts.insert(*I);
511 /// \brief This class summarizes several per-pointer runtime properties which
512 /// are propogated through the flow graph.
514 /// True if the reference count is known to be incremented.
515 bool KnownPositiveRefCount;
517 /// True if we've seen an opportunity for partial RR elimination, such as
518 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
521 /// The current position in the sequence.
525 /// Unidirectional information about the current sequence.
527 /// TODO: Encapsulate this better.
530 PtrState() : KnownPositiveRefCount(false), Partial(false),
534 bool IsKnownSafe() const {
535 return RRI.KnownSafe;
538 void SetKnownSafe(const bool NewValue) {
539 RRI.KnownSafe = NewValue;
542 bool IsTailCallRelease() const {
543 return RRI.IsTailCallRelease;
546 void SetTailCallRelease(const bool NewValue) {
547 RRI.IsTailCallRelease = NewValue;
550 void SetKnownPositiveRefCount() {
551 DEBUG(dbgs() << "Setting Known Positive.\n");
552 KnownPositiveRefCount = true;
555 void ClearKnownPositiveRefCount() {
556 DEBUG(dbgs() << "Clearing Known Positive.\n");
557 KnownPositiveRefCount = false;
560 bool HasKnownPositiveRefCount() const {
561 return KnownPositiveRefCount;
564 void SetSeq(Sequence NewSeq) {
565 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
569 Sequence GetSeq() const {
573 void ClearSequenceProgress() {
574 ResetSequenceProgress(S_None);
577 void ResetSequenceProgress(Sequence NewSeq) {
578 DEBUG(dbgs() << "Resetting sequence progress.\n");
584 void Merge(const PtrState &Other, bool TopDown);
589 PtrState::Merge(const PtrState &Other, bool TopDown) {
590 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
591 KnownPositiveRefCount &= Other.KnownPositiveRefCount;
593 // If we're not in a sequence (anymore), drop all associated state.
597 } else if (Partial || Other.Partial) {
598 // If we're doing a merge on a path that's previously seen a partial
599 // merge, conservatively drop the sequence, to avoid doing partial
600 // RR elimination. If the branch predicates for the two merge differ,
601 // mixing them is unsafe.
602 ClearSequenceProgress();
604 // Otherwise merge the other PtrState's RRInfo into our RRInfo. At this
605 // point, we know that currently we are not partial. Stash whether or not
606 // the merge operation caused us to undergo a partial merging of reverse
608 Partial = RRI.Merge(Other.RRI);
613 /// \brief Per-BasicBlock state.
615 /// The number of unique control paths from the entry which can reach this
617 unsigned TopDownPathCount;
619 /// The number of unique control paths to exits from this block.
620 unsigned BottomUpPathCount;
622 /// A type for PerPtrTopDown and PerPtrBottomUp.
623 typedef MapVector<const Value *, PtrState> MapTy;
625 /// The top-down traversal uses this to record information known about a
626 /// pointer at the bottom of each block.
629 /// The bottom-up traversal uses this to record information known about a
630 /// pointer at the top of each block.
631 MapTy PerPtrBottomUp;
633 /// Effective predecessors of the current block ignoring ignorable edges and
634 /// ignored backedges.
635 SmallVector<BasicBlock *, 2> Preds;
636 /// Effective successors of the current block ignoring ignorable edges and
637 /// ignored backedges.
638 SmallVector<BasicBlock *, 2> Succs;
641 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
643 typedef MapTy::iterator ptr_iterator;
644 typedef MapTy::const_iterator ptr_const_iterator;
646 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
647 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
648 ptr_const_iterator top_down_ptr_begin() const {
649 return PerPtrTopDown.begin();
651 ptr_const_iterator top_down_ptr_end() const {
652 return PerPtrTopDown.end();
655 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
656 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
657 ptr_const_iterator bottom_up_ptr_begin() const {
658 return PerPtrBottomUp.begin();
660 ptr_const_iterator bottom_up_ptr_end() const {
661 return PerPtrBottomUp.end();
664 /// Mark this block as being an entry block, which has one path from the
665 /// entry by definition.
666 void SetAsEntry() { TopDownPathCount = 1; }
668 /// Mark this block as being an exit block, which has one path to an exit by
670 void SetAsExit() { BottomUpPathCount = 1; }
672 /// Attempt to find the PtrState object describing the top down state for
673 /// pointer Arg. Return a new initialized PtrState describing the top down
674 /// state for Arg if we do not find one.
675 PtrState &getPtrTopDownState(const Value *Arg) {
676 return PerPtrTopDown[Arg];
679 /// Attempt to find the PtrState object describing the bottom up state for
680 /// pointer Arg. Return a new initialized PtrState describing the bottom up
681 /// state for Arg if we do not find one.
682 PtrState &getPtrBottomUpState(const Value *Arg) {
683 return PerPtrBottomUp[Arg];
686 /// Attempt to find the PtrState object describing the bottom up state for
688 ptr_iterator findPtrBottomUpState(const Value *Arg) {
689 return PerPtrBottomUp.find(Arg);
692 void clearBottomUpPointers() {
693 PerPtrBottomUp.clear();
696 void clearTopDownPointers() {
697 PerPtrTopDown.clear();
700 void InitFromPred(const BBState &Other);
701 void InitFromSucc(const BBState &Other);
702 void MergePred(const BBState &Other);
703 void MergeSucc(const BBState &Other);
705 /// Compute the number of possible unique paths from an entry to an exit
706 /// which pass through this block. This is only valid after both the
707 /// top-down and bottom-up traversals are complete.
709 /// Returns true if overflow occured. Returns false if overflow did not
711 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
712 assert(TopDownPathCount != 0);
713 assert(BottomUpPathCount != 0);
714 unsigned long long Product =
715 (unsigned long long)TopDownPathCount*BottomUpPathCount;
717 // Overflow occured if any of the upper bits of Product are set.
718 return Product >> 32;
721 // Specialized CFG utilities.
722 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
723 edge_iterator pred_begin() { return Preds.begin(); }
724 edge_iterator pred_end() { return Preds.end(); }
725 edge_iterator succ_begin() { return Succs.begin(); }
726 edge_iterator succ_end() { return Succs.end(); }
728 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
729 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
731 bool isExit() const { return Succs.empty(); }
735 void BBState::InitFromPred(const BBState &Other) {
736 PerPtrTopDown = Other.PerPtrTopDown;
737 TopDownPathCount = Other.TopDownPathCount;
740 void BBState::InitFromSucc(const BBState &Other) {
741 PerPtrBottomUp = Other.PerPtrBottomUp;
742 BottomUpPathCount = Other.BottomUpPathCount;
745 /// The top-down traversal uses this to merge information about predecessors to
746 /// form the initial state for a new block.
747 void BBState::MergePred(const BBState &Other) {
748 // Other.TopDownPathCount can be 0, in which case it is either dead or a
749 // loop backedge. Loop backedges are special.
750 TopDownPathCount += Other.TopDownPathCount;
752 // Check for overflow. If we have overflow, fall back to conservative
754 if (TopDownPathCount < Other.TopDownPathCount) {
755 clearTopDownPointers();
759 // For each entry in the other set, if our set has an entry with the same key,
760 // merge the entries. Otherwise, copy the entry and merge it with an empty
762 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
763 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
764 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
765 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
769 // For each entry in our set, if the other set doesn't have an entry with the
770 // same key, force it to merge with an empty entry.
771 for (ptr_iterator MI = top_down_ptr_begin(),
772 ME = top_down_ptr_end(); MI != ME; ++MI)
773 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
774 MI->second.Merge(PtrState(), /*TopDown=*/true);
777 /// The bottom-up traversal uses this to merge information about successors to
778 /// form the initial state for a new block.
779 void BBState::MergeSucc(const BBState &Other) {
780 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
781 // loop backedge. Loop backedges are special.
782 BottomUpPathCount += Other.BottomUpPathCount;
784 // Check for overflow. If we have overflow, fall back to conservative
786 if (BottomUpPathCount < Other.BottomUpPathCount) {
787 clearBottomUpPointers();
791 // For each entry in the other set, if our set has an entry with the
792 // same key, merge the entries. Otherwise, copy the entry and merge
793 // it with an empty entry.
794 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
795 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
796 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
797 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
801 // For each entry in our set, if the other set doesn't have an entry
802 // with the same key, force it to merge with an empty entry.
803 for (ptr_iterator MI = bottom_up_ptr_begin(),
804 ME = bottom_up_ptr_end(); MI != ME; ++MI)
805 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
806 MI->second.Merge(PtrState(), /*TopDown=*/false);
809 // Only enable ARC Annotations if we are building a debug version of
812 #define ARC_ANNOTATIONS
815 // Define some macros along the lines of DEBUG and some helper functions to make
816 // it cleaner to create annotations in the source code and to no-op when not
817 // building in debug mode.
818 #ifdef ARC_ANNOTATIONS
820 #include "llvm/Support/CommandLine.h"
822 /// Enable/disable ARC sequence annotations.
824 EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
825 cl::desc("Enable emission of arc data flow analysis "
828 DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
829 cl::desc("Disable check for cfg hazards when "
831 static cl::opt<std::string>
832 ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
834 cl::desc("filter out all data flow annotations "
835 "but those that apply to the given "
836 "target llvm identifier."));
838 /// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
839 /// instruction so that we can track backwards when post processing via the llvm
840 /// arc annotation processor tool. If the function is an
841 static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
845 // If pointer is a result of an instruction and it does not have a source
846 // MDNode it, attach a new MDNode onto it. If pointer is a result of
847 // an instruction and does have a source MDNode attached to it, return a
848 // reference to said Node. Otherwise just return 0.
849 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
851 if (!(Node = Inst->getMetadata(NodeId))) {
852 // We do not have any node. Generate and attatch the hash MDString to the
855 // We just use an MDString to ensure that this metadata gets written out
856 // of line at the module level and to provide a very simple format
857 // encoding the information herein. Both of these makes it simpler to
858 // parse the annotations by a simple external program.
860 raw_string_ostream os(Str);
861 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
862 << Inst->getName() << ")";
864 Hash = MDString::get(Inst->getContext(), os.str());
865 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
867 // We have a node. Grab its hash and return it.
868 assert(Node->getNumOperands() == 1 &&
869 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
870 Hash = cast<MDString>(Node->getOperand(0));
872 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
874 raw_string_ostream os(str);
875 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
877 Hash = MDString::get(Arg->getContext(), os.str());
883 static std::string SequenceToString(Sequence A) {
885 raw_string_ostream os(str);
890 /// Helper function to change a Sequence into a String object using our overload
891 /// for raw_ostream so we only have printing code in one location.
892 static MDString *SequenceToMDString(LLVMContext &Context,
894 return MDString::get(Context, SequenceToString(A));
897 /// A simple function to generate a MDNode which describes the change in state
898 /// for Value *Ptr caused by Instruction *Inst.
899 static void AppendMDNodeToInstForPtr(unsigned NodeId,
902 MDString *PtrSourceMDNodeID,
906 Value *tmp[3] = {PtrSourceMDNodeID,
907 SequenceToMDString(Inst->getContext(),
909 SequenceToMDString(Inst->getContext(),
911 Node = MDNode::get(Inst->getContext(),
912 ArrayRef<Value*>(tmp, 3));
914 Inst->setMetadata(NodeId, Node);
917 /// Add to the beginning of the basic block llvm.ptr.annotations which show the
918 /// state of a pointer at the entrance to a basic block.
919 static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
920 Value *Ptr, Sequence Seq) {
921 // If we have a target identifier, make sure that we match it before
923 if(!ARCAnnotationTargetIdentifier.empty() &&
924 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
927 Module *M = BB->getParent()->getParent();
928 LLVMContext &C = M->getContext();
929 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
930 Type *I8XX = PointerType::getUnqual(I8X);
931 Type *Params[] = {I8XX, I8XX};
932 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
933 ArrayRef<Type*>(Params, 2),
935 Constant *Callee = M->getOrInsertFunction(Name, FTy);
937 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
940 StringRef Tmp = Ptr->getName();
941 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
942 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
944 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
945 cast<Constant>(ActualPtrName), Tmp);
949 std::string SeqStr = SequenceToString(Seq);
950 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
951 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
953 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
954 cast<Constant>(ActualPtrName), SeqStr);
957 Builder.CreateCall2(Callee, PtrName, S);
960 /// Add to the end of the basic block llvm.ptr.annotations which show the state
961 /// of the pointer at the bottom of the basic block.
962 static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
963 Value *Ptr, Sequence Seq) {
964 // If we have a target identifier, make sure that we match it before emitting
966 if(!ARCAnnotationTargetIdentifier.empty() &&
967 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
970 Module *M = BB->getParent()->getParent();
971 LLVMContext &C = M->getContext();
972 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
973 Type *I8XX = PointerType::getUnqual(I8X);
974 Type *Params[] = {I8XX, I8XX};
975 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
976 ArrayRef<Type*>(Params, 2),
978 Constant *Callee = M->getOrInsertFunction(Name, FTy);
980 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
983 StringRef Tmp = Ptr->getName();
984 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
985 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
987 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
988 cast<Constant>(ActualPtrName), Tmp);
992 std::string SeqStr = SequenceToString(Seq);
993 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
994 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
996 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
997 cast<Constant>(ActualPtrName), SeqStr);
999 Builder.CreateCall2(Callee, PtrName, S);
1002 /// Adds a source annotation to pointer and a state change annotation to Inst
1003 /// referencing the source annotation and the old/new state of pointer.
1004 static void GenerateARCAnnotation(unsigned InstMDId,
1010 if (EnableARCAnnotations) {
1011 // If we have a target identifier, make sure that we match it before
1012 // emitting an annotation.
1013 if(!ARCAnnotationTargetIdentifier.empty() &&
1014 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
1017 // First generate the source annotation on our pointer. This will return an
1018 // MDString* if Ptr actually comes from an instruction implying we can put
1019 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
1020 // then we know that our pointer is from an Argument so we put a reference
1021 // to the argument number.
1023 // The point of this is to make it easy for the
1024 // llvm-arc-annotation-processor tool to cross reference where the source
1025 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
1026 // information via debug info for backends to use (since why would anyone
1027 // need such a thing from LLVM IR besides in non standard cases
1029 MDString *SourcePtrMDNode =
1030 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
1031 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
1036 // The actual interface for accessing the above functionality is defined via
1037 // some simple macros which are defined below. We do this so that the user does
1038 // not need to pass in what metadata id is needed resulting in cleaner code and
1039 // additionally since it provides an easy way to conditionally no-op all
1040 // annotation support in a non-debug build.
1042 /// Use this macro to annotate a sequence state change when processing
1043 /// instructions bottom up,
1044 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
1045 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
1046 ARCAnnotationProvenanceSourceMDKind, (inst), \
1047 const_cast<Value*>(ptr), (old), (new))
1048 /// Use this macro to annotate a sequence state change when processing
1049 /// instructions top down.
1050 #define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
1051 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
1052 ARCAnnotationProvenanceSourceMDKind, (inst), \
1053 const_cast<Value*>(ptr), (old), (new))
1055 #define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
1057 if (EnableARCAnnotations) { \
1058 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
1059 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
1060 Value *Ptr = const_cast<Value*>(I->first); \
1061 Sequence Seq = I->second.GetSeq(); \
1062 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
1067 #define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
1068 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
1069 Entrance, bottom_up)
1070 #define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
1071 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
1072 Terminator, bottom_up)
1073 #define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
1074 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
1076 #define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
1077 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
1078 Terminator, top_down)
1080 #else // !ARC_ANNOTATION
1081 // If annotations are off, noop.
1082 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
1083 #define ANNOTATE_TOPDOWN(inst, ptr, old, new)
1084 #define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
1085 #define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
1086 #define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
1087 #define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
1088 #endif // !ARC_ANNOTATION
1091 /// \brief The main ARC optimization pass.
1092 class ObjCARCOpt : public FunctionPass {
1094 ProvenanceAnalysis PA;
1096 // This is used to track if a pointer is stored into an alloca.
1097 DenseSet<const Value *> MultiOwnersSet;
1099 /// A flag indicating whether this optimization pass should run.
1102 /// Declarations for ObjC runtime functions, for use in creating calls to
1103 /// them. These are initialized lazily to avoid cluttering up the Module
1104 /// with unused declarations.
1106 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1107 Constant *AutoreleaseRVCallee;
1108 /// Declaration for ObjC runtime function objc_release.
1109 Constant *ReleaseCallee;
1110 /// Declaration for ObjC runtime function objc_retain.
1111 Constant *RetainCallee;
1112 /// Declaration for ObjC runtime function objc_retainBlock.
1113 Constant *RetainBlockCallee;
1114 /// Declaration for ObjC runtime function objc_autorelease.
1115 Constant *AutoreleaseCallee;
1117 /// Flags which determine whether each of the interesting runtine functions
1118 /// is in fact used in the current function.
1119 unsigned UsedInThisFunction;
1121 /// The Metadata Kind for clang.imprecise_release metadata.
1122 unsigned ImpreciseReleaseMDKind;
1124 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
1125 unsigned CopyOnEscapeMDKind;
1127 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
1128 unsigned NoObjCARCExceptionsMDKind;
1130 #ifdef ARC_ANNOTATIONS
1131 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1132 unsigned ARCAnnotationBottomUpMDKind;
1133 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1134 unsigned ARCAnnotationTopDownMDKind;
1135 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1136 unsigned ARCAnnotationProvenanceSourceMDKind;
1137 #endif // ARC_ANNOATIONS
1139 Constant *getAutoreleaseRVCallee(Module *M);
1140 Constant *getReleaseCallee(Module *M);
1141 Constant *getRetainCallee(Module *M);
1142 Constant *getRetainBlockCallee(Module *M);
1143 Constant *getAutoreleaseCallee(Module *M);
1145 bool IsRetainBlockOptimizable(const Instruction *Inst);
1147 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1148 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1149 InstructionClass &Class);
1150 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1151 InstructionClass &Class);
1152 void OptimizeIndividualCalls(Function &F);
1154 void CheckForCFGHazards(const BasicBlock *BB,
1155 DenseMap<const BasicBlock *, BBState> &BBStates,
1156 BBState &MyStates) const;
1157 bool VisitInstructionBottomUp(Instruction *Inst,
1159 MapVector<Value *, RRInfo> &Retains,
1161 bool VisitBottomUp(BasicBlock *BB,
1162 DenseMap<const BasicBlock *, BBState> &BBStates,
1163 MapVector<Value *, RRInfo> &Retains);
1164 bool VisitInstructionTopDown(Instruction *Inst,
1165 DenseMap<Value *, RRInfo> &Releases,
1167 bool VisitTopDown(BasicBlock *BB,
1168 DenseMap<const BasicBlock *, BBState> &BBStates,
1169 DenseMap<Value *, RRInfo> &Releases);
1170 bool Visit(Function &F,
1171 DenseMap<const BasicBlock *, BBState> &BBStates,
1172 MapVector<Value *, RRInfo> &Retains,
1173 DenseMap<Value *, RRInfo> &Releases);
1175 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1176 MapVector<Value *, RRInfo> &Retains,
1177 DenseMap<Value *, RRInfo> &Releases,
1178 SmallVectorImpl<Instruction *> &DeadInsts,
1181 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1182 MapVector<Value *, RRInfo> &Retains,
1183 DenseMap<Value *, RRInfo> &Releases,
1185 SmallVector<Instruction *, 4> &NewRetains,
1186 SmallVector<Instruction *, 4> &NewReleases,
1187 SmallVector<Instruction *, 8> &DeadInsts,
1188 RRInfo &RetainsToMove,
1189 RRInfo &ReleasesToMove,
1192 bool &AnyPairsCompletelyEliminated);
1194 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1195 MapVector<Value *, RRInfo> &Retains,
1196 DenseMap<Value *, RRInfo> &Releases,
1199 void OptimizeWeakCalls(Function &F);
1201 bool OptimizeSequences(Function &F);
1203 void OptimizeReturns(Function &F);
1206 void GatherStatistics(Function &F, bool AfterOptimization = false);
1209 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1210 virtual bool doInitialization(Module &M);
1211 virtual bool runOnFunction(Function &F);
1212 virtual void releaseMemory();
1216 ObjCARCOpt() : FunctionPass(ID) {
1217 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1222 char ObjCARCOpt::ID = 0;
1223 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1224 "objc-arc", "ObjC ARC optimization", false, false)
1225 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1226 INITIALIZE_PASS_END(ObjCARCOpt,
1227 "objc-arc", "ObjC ARC optimization", false, false)
1229 Pass *llvm::createObjCARCOptPass() {
1230 return new ObjCARCOpt();
1233 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1234 AU.addRequired<ObjCARCAliasAnalysis>();
1235 AU.addRequired<AliasAnalysis>();
1236 // ARC optimization doesn't currently split critical edges.
1237 AU.setPreservesCFG();
1240 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1241 // Without the magic metadata tag, we have to assume this might be an
1242 // objc_retainBlock call inserted to convert a block pointer to an id,
1243 // in which case it really is needed.
1244 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1247 // If the pointer "escapes" (not including being used in a call),
1248 // the copy may be needed.
1249 if (DoesRetainableObjPtrEscape(Inst))
1252 // Otherwise, it's not needed.
1256 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1257 if (!AutoreleaseRVCallee) {
1258 LLVMContext &C = M->getContext();
1259 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1260 Type *Params[] = { I8X };
1261 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1262 AttributeSet Attribute =
1263 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1264 Attribute::NoUnwind);
1265 AutoreleaseRVCallee =
1266 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1269 return AutoreleaseRVCallee;
1272 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1273 if (!ReleaseCallee) {
1274 LLVMContext &C = M->getContext();
1275 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1276 AttributeSet Attribute =
1277 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1278 Attribute::NoUnwind);
1280 M->getOrInsertFunction(
1282 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1285 return ReleaseCallee;
1288 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1289 if (!RetainCallee) {
1290 LLVMContext &C = M->getContext();
1291 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1292 AttributeSet Attribute =
1293 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1294 Attribute::NoUnwind);
1296 M->getOrInsertFunction(
1298 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1301 return RetainCallee;
1304 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1305 if (!RetainBlockCallee) {
1306 LLVMContext &C = M->getContext();
1307 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1308 // objc_retainBlock is not nounwind because it calls user copy constructors
1309 // which could theoretically throw.
1311 M->getOrInsertFunction(
1313 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1316 return RetainBlockCallee;
1319 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1320 if (!AutoreleaseCallee) {
1321 LLVMContext &C = M->getContext();
1322 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1323 AttributeSet Attribute =
1324 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1325 Attribute::NoUnwind);
1327 M->getOrInsertFunction(
1329 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1332 return AutoreleaseCallee;
1335 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1336 /// not a return value. Or, if it can be paired with an
1337 /// objc_autoreleaseReturnValue, delete the pair and return true.
1339 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1340 // Check for the argument being from an immediately preceding call or invoke.
1341 const Value *Arg = GetObjCArg(RetainRV);
1342 ImmutableCallSite CS(Arg);
1343 if (const Instruction *Call = CS.getInstruction()) {
1344 if (Call->getParent() == RetainRV->getParent()) {
1345 BasicBlock::const_iterator I = Call;
1347 while (IsNoopInstruction(I)) ++I;
1348 if (&*I == RetainRV)
1350 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
1351 BasicBlock *RetainRVParent = RetainRV->getParent();
1352 if (II->getNormalDest() == RetainRVParent) {
1353 BasicBlock::const_iterator I = RetainRVParent->begin();
1354 while (IsNoopInstruction(I)) ++I;
1355 if (&*I == RetainRV)
1361 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1362 // pointer. In this case, we can delete the pair.
1363 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1365 do --I; while (I != Begin && IsNoopInstruction(I));
1366 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1367 GetObjCArg(I) == Arg) {
1371 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1372 << "Erasing " << *RetainRV << "\n");
1374 EraseInstruction(I);
1375 EraseInstruction(RetainRV);
1380 // Turn it to a plain objc_retain.
1384 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
1385 "objc_retain since the operand is not a return value.\n"
1386 "Old = " << *RetainRV << "\n");
1388 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
1390 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
1395 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1396 /// used as a return value.
1398 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1399 InstructionClass &Class) {
1400 // Check for a return of the pointer value.
1401 const Value *Ptr = GetObjCArg(AutoreleaseRV);
1402 SmallVector<const Value *, 2> Users;
1403 Users.push_back(Ptr);
1405 Ptr = Users.pop_back_val();
1406 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1408 const User *I = *UI;
1409 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1411 if (isa<BitCastInst>(I))
1414 } while (!Users.empty());
1419 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
1420 "objc_autorelease since its operand is not used as a return "
1422 "Old = " << *AutoreleaseRV << "\n");
1424 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1426 setCalledFunction(getAutoreleaseCallee(F.getParent()));
1427 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
1428 Class = IC_Autorelease;
1430 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
1434 // \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1437 // Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1438 // does not escape (following the rules of block escaping), strength reduce the
1439 // objc_retainBlock to an objc_retain.
1441 // TODO: If an objc_retainBlock call is dominated period by a previous
1442 // objc_retainBlock call, strength reduce the objc_retainBlock to an
1445 ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1446 InstructionClass &Class) {
1447 assert(GetBasicInstructionClass(Inst) == Class);
1448 assert(IC_RetainBlock == Class);
1450 // If we can not optimize Inst, return false.
1451 if (!IsRetainBlockOptimizable(Inst))
1457 DEBUG(dbgs() << "Strength reduced retainBlock => retain.\n");
1458 DEBUG(dbgs() << "Old: " << *Inst << "\n");
1459 CallInst *RetainBlock = cast<CallInst>(Inst);
1460 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1461 // Remove copy_on_escape metadata.
1462 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1464 DEBUG(dbgs() << "New: " << *Inst << "\n");
1468 /// Visit each call, one at a time, and make simplifications without doing any
1469 /// additional analysis.
1470 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1471 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
1472 // Reset all the flags in preparation for recomputing them.
1473 UsedInThisFunction = 0;
1475 // Visit all objc_* calls in F.
1476 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1477 Instruction *Inst = &*I++;
1479 InstructionClass Class = GetBasicInstructionClass(Inst);
1481 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
1486 // Delete no-op casts. These function calls have special semantics, but
1487 // the semantics are entirely implemented via lowering in the front-end,
1488 // so by the time they reach the optimizer, they are just no-op calls
1489 // which return their argument.
1491 // There are gray areas here, as the ability to cast reference-counted
1492 // pointers to raw void* and back allows code to break ARC assumptions,
1493 // however these are currently considered to be unimportant.
1497 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
1498 EraseInstruction(Inst);
1501 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1504 case IC_LoadWeakRetained:
1506 case IC_DestroyWeak: {
1507 CallInst *CI = cast<CallInst>(Inst);
1508 if (IsNullOrUndef(CI->getArgOperand(0))) {
1510 Type *Ty = CI->getArgOperand(0)->getType();
1511 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1512 Constant::getNullValue(Ty),
1514 llvm::Value *NewValue = UndefValue::get(CI->getType());
1515 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1516 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1517 CI->replaceAllUsesWith(NewValue);
1518 CI->eraseFromParent();
1525 CallInst *CI = cast<CallInst>(Inst);
1526 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1527 IsNullOrUndef(CI->getArgOperand(1))) {
1529 Type *Ty = CI->getArgOperand(0)->getType();
1530 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1531 Constant::getNullValue(Ty),
1534 llvm::Value *NewValue = UndefValue::get(CI->getType());
1535 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1536 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1538 CI->replaceAllUsesWith(NewValue);
1539 CI->eraseFromParent();
1544 case IC_RetainBlock:
1545 // If we strength reduce an objc_retainBlock to an objc_retain, continue
1546 // onto the objc_retain peephole optimizations. Otherwise break.
1547 OptimizeRetainBlockCall(F, Inst, Class);
1550 if (OptimizeRetainRVCall(F, Inst))
1553 case IC_AutoreleaseRV:
1554 OptimizeAutoreleaseRVCall(F, Inst, Class);
1558 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
1559 if (IsAutorelease(Class) && Inst->use_empty()) {
1560 CallInst *Call = cast<CallInst>(Inst);
1561 const Value *Arg = Call->getArgOperand(0);
1562 Arg = FindSingleUseIdentifiedObject(Arg);
1567 // Create the declaration lazily.
1568 LLVMContext &C = Inst->getContext();
1570 CallInst::Create(getReleaseCallee(F.getParent()),
1571 Call->getArgOperand(0), "", Call);
1572 NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
1574 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1575 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1576 << *NewCall << "\n");
1578 EraseInstruction(Call);
1584 // For functions which can never be passed stack arguments, add
1586 if (IsAlwaysTail(Class)) {
1588 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1589 "passed stack args: " << *Inst << "\n");
1590 cast<CallInst>(Inst)->setTailCall();
1593 // Ensure that functions that can never have a "tail" keyword due to the
1594 // semantics of ARC truly do not do so.
1595 if (IsNeverTail(Class)) {
1597 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
1599 cast<CallInst>(Inst)->setTailCall(false);
1602 // Set nounwind as needed.
1603 if (IsNoThrow(Class)) {
1605 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1607 cast<CallInst>(Inst)->setDoesNotThrow();
1610 if (!IsNoopOnNull(Class)) {
1611 UsedInThisFunction |= 1 << Class;
1615 const Value *Arg = GetObjCArg(Inst);
1617 // ARC calls with null are no-ops. Delete them.
1618 if (IsNullOrUndef(Arg)) {
1621 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1623 EraseInstruction(Inst);
1627 // Keep track of which of retain, release, autorelease, and retain_block
1628 // are actually present in this function.
1629 UsedInThisFunction |= 1 << Class;
1631 // If Arg is a PHI, and one or more incoming values to the
1632 // PHI are null, and the call is control-equivalent to the PHI, and there
1633 // are no relevant side effects between the PHI and the call, the call
1634 // could be pushed up to just those paths with non-null incoming values.
1635 // For now, don't bother splitting critical edges for this.
1636 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1637 Worklist.push_back(std::make_pair(Inst, Arg));
1639 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1643 const PHINode *PN = dyn_cast<PHINode>(Arg);
1646 // Determine if the PHI has any null operands, or any incoming
1648 bool HasNull = false;
1649 bool HasCriticalEdges = false;
1650 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1652 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1653 if (IsNullOrUndef(Incoming))
1655 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1656 .getNumSuccessors() != 1) {
1657 HasCriticalEdges = true;
1661 // If we have null operands and no critical edges, optimize.
1662 if (!HasCriticalEdges && HasNull) {
1663 SmallPtrSet<Instruction *, 4> DependingInstructions;
1664 SmallPtrSet<const BasicBlock *, 4> Visited;
1666 // Check that there is nothing that cares about the reference
1667 // count between the call and the phi.
1670 case IC_RetainBlock:
1671 // These can always be moved up.
1674 // These can't be moved across things that care about the retain
1676 FindDependencies(NeedsPositiveRetainCount, Arg,
1677 Inst->getParent(), Inst,
1678 DependingInstructions, Visited, PA);
1680 case IC_Autorelease:
1681 // These can't be moved across autorelease pool scope boundaries.
1682 FindDependencies(AutoreleasePoolBoundary, Arg,
1683 Inst->getParent(), Inst,
1684 DependingInstructions, Visited, PA);
1687 case IC_AutoreleaseRV:
1688 // Don't move these; the RV optimization depends on the autoreleaseRV
1689 // being tail called, and the retainRV being immediately after a call
1690 // (which might still happen if we get lucky with codegen layout, but
1691 // it's not worth taking the chance).
1694 llvm_unreachable("Invalid dependence flavor");
1697 if (DependingInstructions.size() == 1 &&
1698 *DependingInstructions.begin() == PN) {
1701 // Clone the call into each predecessor that has a non-null value.
1702 CallInst *CInst = cast<CallInst>(Inst);
1703 Type *ParamTy = CInst->getArgOperand(0)->getType();
1704 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1706 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1707 if (!IsNullOrUndef(Incoming)) {
1708 CallInst *Clone = cast<CallInst>(CInst->clone());
1709 Value *Op = PN->getIncomingValue(i);
1710 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1711 if (Op->getType() != ParamTy)
1712 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1713 Clone->setArgOperand(0, Op);
1714 Clone->insertBefore(InsertPos);
1716 DEBUG(dbgs() << "Cloning "
1718 "And inserting clone at " << *InsertPos << "\n");
1719 Worklist.push_back(std::make_pair(Clone, Incoming));
1722 // Erase the original call.
1723 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
1724 EraseInstruction(CInst);
1728 } while (!Worklist.empty());
1732 /// If we have a top down pointer in the S_Use state, make sure that there are
1733 /// no CFG hazards by checking the states of various bottom up pointers.
1734 static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1735 const bool SuccSRRIKnownSafe,
1737 bool &SomeSuccHasSame,
1738 bool &AllSuccsHaveSame,
1739 bool &NotAllSeqEqualButKnownSafe,
1740 bool &ShouldContinue) {
1742 case S_CanRelease: {
1743 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe) {
1744 S.ClearSequenceProgress();
1747 S.RRI.CFGHazardAfflicted = true;
1748 ShouldContinue = true;
1752 SomeSuccHasSame = true;
1756 case S_MovableRelease:
1757 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
1758 AllSuccsHaveSame = false;
1760 NotAllSeqEqualButKnownSafe = true;
1763 llvm_unreachable("bottom-up pointer in retain state!");
1765 llvm_unreachable("This should have been handled earlier.");
1769 /// If we have a Top Down pointer in the S_CanRelease state, make sure that
1770 /// there are no CFG hazards by checking the states of various bottom up
1772 static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1773 const bool SuccSRRIKnownSafe,
1775 bool &SomeSuccHasSame,
1776 bool &AllSuccsHaveSame,
1777 bool &NotAllSeqEqualButKnownSafe) {
1780 SomeSuccHasSame = true;
1784 case S_MovableRelease:
1786 if (!S.IsKnownSafe() && !SuccSRRIKnownSafe)
1787 AllSuccsHaveSame = false;
1789 NotAllSeqEqualButKnownSafe = true;
1792 llvm_unreachable("bottom-up pointer in retain state!");
1794 llvm_unreachable("This should have been handled earlier.");
1798 /// Check for critical edges, loop boundaries, irreducible control flow, or
1799 /// other CFG structures where moving code across the edge would result in it
1800 /// being executed more.
1802 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1803 DenseMap<const BasicBlock *, BBState> &BBStates,
1804 BBState &MyStates) const {
1805 // If any top-down local-use or possible-dec has a succ which is earlier in
1806 // the sequence, forget it.
1807 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
1808 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1809 PtrState &S = I->second;
1810 const Sequence Seq = I->second.GetSeq();
1812 // We only care about S_Retain, S_CanRelease, and S_Use.
1816 // Make sure that if extra top down states are added in the future that this
1817 // code is updated to handle it.
1818 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1819 "Unknown top down sequence state.");
1821 const Value *Arg = I->first;
1822 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1823 bool SomeSuccHasSame = false;
1824 bool AllSuccsHaveSame = true;
1825 bool NotAllSeqEqualButKnownSafe = false;
1827 succ_const_iterator SI(TI), SE(TI, false);
1829 for (; SI != SE; ++SI) {
1830 // If VisitBottomUp has pointer information for this successor, take
1831 // what we know about it.
1832 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1834 assert(BBI != BBStates.end());
1835 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1836 const Sequence SuccSSeq = SuccS.GetSeq();
1838 // If bottom up, the pointer is in an S_None state, clear the sequence
1839 // progress since the sequence in the bottom up state finished
1840 // suggesting a mismatch in between retains/releases. This is true for
1841 // all three cases that we are handling here: S_Retain, S_Use, and
1843 if (SuccSSeq == S_None) {
1844 S.ClearSequenceProgress();
1848 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1850 const bool SuccSRRIKnownSafe = SuccS.IsKnownSafe();
1852 // *NOTE* We do not use Seq from above here since we are allowing for
1853 // S.GetSeq() to change while we are visiting basic blocks.
1854 switch(S.GetSeq()) {
1856 bool ShouldContinue = false;
1857 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1858 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
1864 case S_CanRelease: {
1865 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1866 SomeSuccHasSame, AllSuccsHaveSame,
1867 NotAllSeqEqualButKnownSafe);
1874 case S_MovableRelease:
1879 // If the state at the other end of any of the successor edges
1880 // matches the current state, require all edges to match. This
1881 // guards against loops in the middle of a sequence.
1882 if (SomeSuccHasSame && !AllSuccsHaveSame) {
1883 S.ClearSequenceProgress();
1884 } else if (NotAllSeqEqualButKnownSafe) {
1885 // If we would have cleared the state foregoing the fact that we are known
1886 // safe, stop code motion. This is because whether or not it is safe to
1887 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1888 // are allowed to perform code motion.
1889 S.RRI.CFGHazardAfflicted = true;
1895 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
1897 MapVector<Value *, RRInfo> &Retains,
1898 BBState &MyStates) {
1899 bool NestingDetected = false;
1900 InstructionClass Class = GetInstructionClass(Inst);
1901 const Value *Arg = 0;
1903 DEBUG(dbgs() << "Class: " << Class << "\n");
1907 Arg = GetObjCArg(Inst);
1909 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1911 // If we see two releases in a row on the same pointer. If so, make
1912 // a note, and we'll cicle back to revisit it after we've
1913 // hopefully eliminated the second release, which may allow us to
1914 // eliminate the first release too.
1915 // Theoretically we could implement removal of nested retain+release
1916 // pairs by making PtrState hold a stack of states, but this is
1917 // simple and avoids adding overhead for the non-nested case.
1918 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
1919 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
1920 NestingDetected = true;
1923 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
1924 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1925 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1926 S.ResetSequenceProgress(NewSeq);
1927 S.RRI.ReleaseMetadata = ReleaseMetadata;
1928 S.SetKnownSafe(S.HasKnownPositiveRefCount());
1929 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
1930 S.RRI.Calls.insert(Inst);
1931 S.SetKnownPositiveRefCount();
1934 case IC_RetainBlock:
1935 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1936 // objc_retainBlocks to objc_retains. Thus at this point any
1937 // objc_retainBlocks that we see are not optimizable.
1941 Arg = GetObjCArg(Inst);
1943 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1944 S.SetKnownPositiveRefCount();
1946 Sequence OldSeq = S.GetSeq();
1950 case S_MovableRelease:
1952 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1953 // imprecise release, clear our reverse insertion points.
1954 if (OldSeq != S_Use || S.RRI.IsTrackingImpreciseReleases())
1955 S.RRI.ReverseInsertPts.clear();
1958 // Don't do retain+release tracking for IC_RetainRV, because it's
1959 // better to let it remain as the first instruction after a call.
1960 if (Class != IC_RetainRV)
1961 Retains[Inst] = S.RRI;
1962 S.ClearSequenceProgress();
1967 llvm_unreachable("bottom-up pointer in retain state!");
1969 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
1970 // A retain moving bottom up can be a use.
1973 case IC_AutoreleasepoolPop:
1974 // Conservatively, clear MyStates for all known pointers.
1975 MyStates.clearBottomUpPointers();
1976 return NestingDetected;
1977 case IC_AutoreleasepoolPush:
1979 // These are irrelevant.
1980 return NestingDetected;
1982 // If we have a store into an alloca of a pointer we are tracking, the
1983 // pointer has multiple owners implying that we must be more conservative.
1985 // This comes up in the context of a pointer being ``KnownSafe''. In the
1986 // presense of a block being initialized, the frontend will emit the
1987 // objc_retain on the original pointer and the release on the pointer loaded
1988 // from the alloca. The optimizer will through the provenance analysis
1989 // realize that the two are related, but since we only require KnownSafe in
1990 // one direction, will match the inner retain on the original pointer with
1991 // the guard release on the original pointer. This is fixed by ensuring that
1992 // in the presense of allocas we only unconditionally remove pointers if
1993 // both our retain and our release are KnownSafe.
1994 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1995 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
1996 BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
1997 StripPointerCastsAndObjCCalls(SI->getValueOperand()));
1998 if (I != MyStates.bottom_up_ptr_end())
1999 MultiOwnersSet.insert(I->first);
2007 // Consider any other possible effects of this instruction on each
2008 // pointer being tracked.
2009 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2010 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2011 const Value *Ptr = MI->first;
2013 continue; // Handled above.
2014 PtrState &S = MI->second;
2015 Sequence Seq = S.GetSeq();
2017 // Check for possible releases.
2018 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2019 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
2021 S.ClearKnownPositiveRefCount();
2024 S.SetSeq(S_CanRelease);
2025 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
2029 case S_MovableRelease:
2034 llvm_unreachable("bottom-up pointer in retain state!");
2038 // Check for possible direct uses.
2041 case S_MovableRelease:
2042 if (CanUse(Inst, Ptr, PA, Class)) {
2043 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2045 assert(S.RRI.ReverseInsertPts.empty());
2046 // If this is an invoke instruction, we're scanning it as part of
2047 // one of its successor blocks, since we can't insert code after it
2048 // in its own block, and we don't want to split critical edges.
2049 if (isa<InvokeInst>(Inst))
2050 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2052 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2054 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2055 } else if (Seq == S_Release && IsUser(Class)) {
2056 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
2058 // Non-movable releases depend on any possible objc pointer use.
2060 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
2061 assert(S.RRI.ReverseInsertPts.empty());
2062 // As above; handle invoke specially.
2063 if (isa<InvokeInst>(Inst))
2064 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2066 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2070 if (CanUse(Inst, Ptr, PA, Class)) {
2071 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
2074 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2082 llvm_unreachable("bottom-up pointer in retain state!");
2086 return NestingDetected;
2090 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2091 DenseMap<const BasicBlock *, BBState> &BBStates,
2092 MapVector<Value *, RRInfo> &Retains) {
2094 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
2096 bool NestingDetected = false;
2097 BBState &MyStates = BBStates[BB];
2099 // Merge the states from each successor to compute the initial state
2100 // for the current block.
2101 BBState::edge_iterator SI(MyStates.succ_begin()),
2102 SE(MyStates.succ_end());
2104 const BasicBlock *Succ = *SI;
2105 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2106 assert(I != BBStates.end());
2107 MyStates.InitFromSucc(I->second);
2109 for (; SI != SE; ++SI) {
2111 I = BBStates.find(Succ);
2112 assert(I != BBStates.end());
2113 MyStates.MergeSucc(I->second);
2117 // If ARC Annotations are enabled, output the current state of pointers at the
2118 // bottom of the basic block.
2119 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
2121 // Visit all the instructions, bottom-up.
2122 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2123 Instruction *Inst = llvm::prior(I);
2125 // Invoke instructions are visited as part of their successors (below).
2126 if (isa<InvokeInst>(Inst))
2129 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
2131 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2134 // If there's a predecessor with an invoke, visit the invoke as if it were
2135 // part of this block, since we can't insert code after an invoke in its own
2136 // block, and we don't want to split critical edges.
2137 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2138 PE(MyStates.pred_end()); PI != PE; ++PI) {
2139 BasicBlock *Pred = *PI;
2140 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2141 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
2144 // If ARC Annotations are enabled, output the current state of pointers at the
2145 // top of the basic block.
2146 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
2148 return NestingDetected;
2152 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2153 DenseMap<Value *, RRInfo> &Releases,
2154 BBState &MyStates) {
2155 bool NestingDetected = false;
2156 InstructionClass Class = GetInstructionClass(Inst);
2157 const Value *Arg = 0;
2160 case IC_RetainBlock:
2161 // In OptimizeIndividualCalls, we have strength reduced all optimizable
2162 // objc_retainBlocks to objc_retains. Thus at this point any
2163 // objc_retainBlocks that we see are not optimizable.
2167 Arg = GetObjCArg(Inst);
2169 PtrState &S = MyStates.getPtrTopDownState(Arg);
2171 // Don't do retain+release tracking for IC_RetainRV, because it's
2172 // better to let it remain as the first instruction after a call.
2173 if (Class != IC_RetainRV) {
2174 // If we see two retains in a row on the same pointer. If so, make
2175 // a note, and we'll cicle back to revisit it after we've
2176 // hopefully eliminated the second retain, which may allow us to
2177 // eliminate the first retain too.
2178 // Theoretically we could implement removal of nested retain+release
2179 // pairs by making PtrState hold a stack of states, but this is
2180 // simple and avoids adding overhead for the non-nested case.
2181 if (S.GetSeq() == S_Retain)
2182 NestingDetected = true;
2184 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
2185 S.ResetSequenceProgress(S_Retain);
2186 S.SetKnownSafe(S.HasKnownPositiveRefCount());
2187 S.RRI.Calls.insert(Inst);
2190 S.SetKnownPositiveRefCount();
2192 // A retain can be a potential use; procede to the generic checking
2197 Arg = GetObjCArg(Inst);
2199 PtrState &S = MyStates.getPtrTopDownState(Arg);
2200 S.ClearKnownPositiveRefCount();
2202 Sequence OldSeq = S.GetSeq();
2204 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2209 if (OldSeq == S_Retain || ReleaseMetadata != 0)
2210 S.RRI.ReverseInsertPts.clear();
2213 S.RRI.ReleaseMetadata = ReleaseMetadata;
2214 S.SetTailCallRelease(cast<CallInst>(Inst)->isTailCall());
2215 Releases[Inst] = S.RRI;
2216 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
2217 S.ClearSequenceProgress();
2223 case S_MovableRelease:
2224 llvm_unreachable("top-down pointer in release state!");
2228 case IC_AutoreleasepoolPop:
2229 // Conservatively, clear MyStates for all known pointers.
2230 MyStates.clearTopDownPointers();
2231 return NestingDetected;
2232 case IC_AutoreleasepoolPush:
2234 // These are irrelevant.
2235 return NestingDetected;
2240 // Consider any other possible effects of this instruction on each
2241 // pointer being tracked.
2242 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2243 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2244 const Value *Ptr = MI->first;
2246 continue; // Handled above.
2247 PtrState &S = MI->second;
2248 Sequence Seq = S.GetSeq();
2250 // Check for possible releases.
2251 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2252 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
2254 S.ClearKnownPositiveRefCount();
2257 S.SetSeq(S_CanRelease);
2258 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
2259 assert(S.RRI.ReverseInsertPts.empty());
2260 S.RRI.ReverseInsertPts.insert(Inst);
2262 // One call can't cause a transition from S_Retain to S_CanRelease
2263 // and S_CanRelease to S_Use. If we've made the first transition,
2272 case S_MovableRelease:
2273 llvm_unreachable("top-down pointer in release state!");
2277 // Check for possible direct uses.
2280 if (CanUse(Inst, Ptr, PA, Class)) {
2281 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2284 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2293 case S_MovableRelease:
2294 llvm_unreachable("top-down pointer in release state!");
2298 return NestingDetected;
2302 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2303 DenseMap<const BasicBlock *, BBState> &BBStates,
2304 DenseMap<Value *, RRInfo> &Releases) {
2305 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
2306 bool NestingDetected = false;
2307 BBState &MyStates = BBStates[BB];
2309 // Merge the states from each predecessor to compute the initial state
2310 // for the current block.
2311 BBState::edge_iterator PI(MyStates.pred_begin()),
2312 PE(MyStates.pred_end());
2314 const BasicBlock *Pred = *PI;
2315 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2316 assert(I != BBStates.end());
2317 MyStates.InitFromPred(I->second);
2319 for (; PI != PE; ++PI) {
2321 I = BBStates.find(Pred);
2322 assert(I != BBStates.end());
2323 MyStates.MergePred(I->second);
2327 // If ARC Annotations are enabled, output the current state of pointers at the
2328 // top of the basic block.
2329 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
2331 // Visit all the instructions, top-down.
2332 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2333 Instruction *Inst = I;
2335 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
2337 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
2340 // If ARC Annotations are enabled, output the current state of pointers at the
2341 // bottom of the basic block.
2342 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
2344 #ifdef ARC_ANNOTATIONS
2345 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
2347 CheckForCFGHazards(BB, BBStates, MyStates);
2348 return NestingDetected;
2352 ComputePostOrders(Function &F,
2353 SmallVectorImpl<BasicBlock *> &PostOrder,
2354 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2355 unsigned NoObjCARCExceptionsMDKind,
2356 DenseMap<const BasicBlock *, BBState> &BBStates) {
2357 /// The visited set, for doing DFS walks.
2358 SmallPtrSet<BasicBlock *, 16> Visited;
2360 // Do DFS, computing the PostOrder.
2361 SmallPtrSet<BasicBlock *, 16> OnStack;
2362 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2364 // Functions always have exactly one entry block, and we don't have
2365 // any other block that we treat like an entry block.
2366 BasicBlock *EntryBB = &F.getEntryBlock();
2367 BBState &MyStates = BBStates[EntryBB];
2368 MyStates.SetAsEntry();
2369 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2370 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
2371 Visited.insert(EntryBB);
2372 OnStack.insert(EntryBB);
2375 BasicBlock *CurrBB = SuccStack.back().first;
2376 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2377 succ_iterator SE(TI, false);
2379 while (SuccStack.back().second != SE) {
2380 BasicBlock *SuccBB = *SuccStack.back().second++;
2381 if (Visited.insert(SuccBB)) {
2382 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2383 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
2384 BBStates[CurrBB].addSucc(SuccBB);
2385 BBState &SuccStates = BBStates[SuccBB];
2386 SuccStates.addPred(CurrBB);
2387 OnStack.insert(SuccBB);
2391 if (!OnStack.count(SuccBB)) {
2392 BBStates[CurrBB].addSucc(SuccBB);
2393 BBStates[SuccBB].addPred(CurrBB);
2396 OnStack.erase(CurrBB);
2397 PostOrder.push_back(CurrBB);
2398 SuccStack.pop_back();
2399 } while (!SuccStack.empty());
2403 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2404 // Functions may have many exits, and there also blocks which we treat
2405 // as exits due to ignored edges.
2406 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2407 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2408 BasicBlock *ExitBB = I;
2409 BBState &MyStates = BBStates[ExitBB];
2410 if (!MyStates.isExit())
2413 MyStates.SetAsExit();
2415 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
2416 Visited.insert(ExitBB);
2417 while (!PredStack.empty()) {
2418 reverse_dfs_next_succ:
2419 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2420 while (PredStack.back().second != PE) {
2421 BasicBlock *BB = *PredStack.back().second++;
2422 if (Visited.insert(BB)) {
2423 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
2424 goto reverse_dfs_next_succ;
2427 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2432 // Visit the function both top-down and bottom-up.
2434 ObjCARCOpt::Visit(Function &F,
2435 DenseMap<const BasicBlock *, BBState> &BBStates,
2436 MapVector<Value *, RRInfo> &Retains,
2437 DenseMap<Value *, RRInfo> &Releases) {
2439 // Use reverse-postorder traversals, because we magically know that loops
2440 // will be well behaved, i.e. they won't repeatedly call retain on a single
2441 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2442 // class here because we want the reverse-CFG postorder to consider each
2443 // function exit point, and we want to ignore selected cycle edges.
2444 SmallVector<BasicBlock *, 16> PostOrder;
2445 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2446 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2447 NoObjCARCExceptionsMDKind,
2450 // Use reverse-postorder on the reverse CFG for bottom-up.
2451 bool BottomUpNestingDetected = false;
2452 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2453 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2455 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
2457 // Use reverse-postorder for top-down.
2458 bool TopDownNestingDetected = false;
2459 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2460 PostOrder.rbegin(), E = PostOrder.rend();
2462 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
2464 return TopDownNestingDetected && BottomUpNestingDetected;
2467 /// Move the calls in RetainsToMove and ReleasesToMove.
2468 void ObjCARCOpt::MoveCalls(Value *Arg,
2469 RRInfo &RetainsToMove,
2470 RRInfo &ReleasesToMove,
2471 MapVector<Value *, RRInfo> &Retains,
2472 DenseMap<Value *, RRInfo> &Releases,
2473 SmallVectorImpl<Instruction *> &DeadInsts,
2475 Type *ArgTy = Arg->getType();
2476 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2478 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
2480 // Insert the new retain and release calls.
2481 for (SmallPtrSet<Instruction *, 2>::const_iterator
2482 PI = ReleasesToMove.ReverseInsertPts.begin(),
2483 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2484 Instruction *InsertPt = *PI;
2485 Value *MyArg = ArgTy == ParamTy ? Arg :
2486 new BitCastInst(Arg, ParamTy, "", InsertPt);
2488 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
2489 Call->setDoesNotThrow();
2490 Call->setTailCall();
2492 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
2493 "At insertion point: " << *InsertPt << "\n");
2495 for (SmallPtrSet<Instruction *, 2>::const_iterator
2496 PI = RetainsToMove.ReverseInsertPts.begin(),
2497 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2498 Instruction *InsertPt = *PI;
2499 Value *MyArg = ArgTy == ParamTy ? Arg :
2500 new BitCastInst(Arg, ParamTy, "", InsertPt);
2501 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2503 // Attach a clang.imprecise_release metadata tag, if appropriate.
2504 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2505 Call->setMetadata(ImpreciseReleaseMDKind, M);
2506 Call->setDoesNotThrow();
2507 if (ReleasesToMove.IsTailCallRelease)
2508 Call->setTailCall();
2510 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2511 "At insertion point: " << *InsertPt << "\n");
2514 // Delete the original retain and release calls.
2515 for (SmallPtrSet<Instruction *, 2>::const_iterator
2516 AI = RetainsToMove.Calls.begin(),
2517 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2518 Instruction *OrigRetain = *AI;
2519 Retains.blot(OrigRetain);
2520 DeadInsts.push_back(OrigRetain);
2521 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
2523 for (SmallPtrSet<Instruction *, 2>::const_iterator
2524 AI = ReleasesToMove.Calls.begin(),
2525 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2526 Instruction *OrigRelease = *AI;
2527 Releases.erase(OrigRelease);
2528 DeadInsts.push_back(OrigRelease);
2529 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
2535 ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2537 MapVector<Value *, RRInfo> &Retains,
2538 DenseMap<Value *, RRInfo> &Releases,
2540 SmallVector<Instruction *, 4> &NewRetains,
2541 SmallVector<Instruction *, 4> &NewReleases,
2542 SmallVector<Instruction *, 8> &DeadInsts,
2543 RRInfo &RetainsToMove,
2544 RRInfo &ReleasesToMove,
2547 bool &AnyPairsCompletelyEliminated) {
2548 // If a pair happens in a region where it is known that the reference count
2549 // is already incremented, we can similarly ignore possible decrements unless
2550 // we are dealing with a retainable object with multiple provenance sources.
2551 bool KnownSafeTD = true, KnownSafeBU = true;
2552 bool MultipleOwners = false;
2553 bool CFGHazardAfflicted = false;
2555 // Connect the dots between the top-down-collected RetainsToMove and
2556 // bottom-up-collected ReleasesToMove to form sets of related calls.
2557 // This is an iterative process so that we connect multiple releases
2558 // to multiple retains if needed.
2559 unsigned OldDelta = 0;
2560 unsigned NewDelta = 0;
2561 unsigned OldCount = 0;
2562 unsigned NewCount = 0;
2563 bool FirstRelease = true;
2565 for (SmallVectorImpl<Instruction *>::const_iterator
2566 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2567 Instruction *NewRetain = *NI;
2568 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2569 assert(It != Retains.end());
2570 const RRInfo &NewRetainRRI = It->second;
2571 KnownSafeTD &= NewRetainRRI.KnownSafe;
2573 MultipleOwners || MultiOwnersSet.count(GetObjCArg(NewRetain));
2574 for (SmallPtrSet<Instruction *, 2>::const_iterator
2575 LI = NewRetainRRI.Calls.begin(),
2576 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2577 Instruction *NewRetainRelease = *LI;
2578 DenseMap<Value *, RRInfo>::const_iterator Jt =
2579 Releases.find(NewRetainRelease);
2580 if (Jt == Releases.end())
2582 const RRInfo &NewRetainReleaseRRI = Jt->second;
2583 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2584 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2586 // If we overflow when we compute the path count, don't remove/move
2588 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
2590 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2592 OldDelta -= PathCount;
2594 // Merge the ReleaseMetadata and IsTailCallRelease values.
2596 ReleasesToMove.ReleaseMetadata =
2597 NewRetainReleaseRRI.ReleaseMetadata;
2598 ReleasesToMove.IsTailCallRelease =
2599 NewRetainReleaseRRI.IsTailCallRelease;
2600 FirstRelease = false;
2602 if (ReleasesToMove.ReleaseMetadata !=
2603 NewRetainReleaseRRI.ReleaseMetadata)
2604 ReleasesToMove.ReleaseMetadata = 0;
2605 if (ReleasesToMove.IsTailCallRelease !=
2606 NewRetainReleaseRRI.IsTailCallRelease)
2607 ReleasesToMove.IsTailCallRelease = false;
2610 // Collect the optimal insertion points.
2612 for (SmallPtrSet<Instruction *, 2>::const_iterator
2613 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2614 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2616 Instruction *RIP = *RI;
2617 if (ReleasesToMove.ReverseInsertPts.insert(RIP)) {
2618 // If we overflow when we compute the path count, don't
2619 // remove/move anything.
2620 const BBState &RIPBBState = BBStates[RIP->getParent()];
2621 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2623 NewDelta -= PathCount;
2626 NewReleases.push_back(NewRetainRelease);
2631 if (NewReleases.empty()) break;
2633 // Back the other way.
2634 for (SmallVectorImpl<Instruction *>::const_iterator
2635 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2636 Instruction *NewRelease = *NI;
2637 DenseMap<Value *, RRInfo>::const_iterator It =
2638 Releases.find(NewRelease);
2639 assert(It != Releases.end());
2640 const RRInfo &NewReleaseRRI = It->second;
2641 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2642 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
2643 for (SmallPtrSet<Instruction *, 2>::const_iterator
2644 LI = NewReleaseRRI.Calls.begin(),
2645 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2646 Instruction *NewReleaseRetain = *LI;
2647 MapVector<Value *, RRInfo>::const_iterator Jt =
2648 Retains.find(NewReleaseRetain);
2649 if (Jt == Retains.end())
2651 const RRInfo &NewReleaseRetainRRI = Jt->second;
2652 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2653 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2655 // If we overflow when we compute the path count, don't remove/move
2657 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
2659 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2661 OldDelta += PathCount;
2662 OldCount += PathCount;
2664 // Collect the optimal insertion points.
2666 for (SmallPtrSet<Instruction *, 2>::const_iterator
2667 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2668 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2670 Instruction *RIP = *RI;
2671 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2672 // If we overflow when we compute the path count, don't
2673 // remove/move anything.
2674 const BBState &RIPBBState = BBStates[RIP->getParent()];
2675 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2677 NewDelta += PathCount;
2678 NewCount += PathCount;
2681 NewRetains.push_back(NewReleaseRetain);
2685 NewReleases.clear();
2686 if (NewRetains.empty()) break;
2689 // If the pointer is known incremented in 1 direction and we do not have
2690 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2691 // to be known safe in both directions.
2692 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2693 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2694 if (UnconditionallySafe) {
2695 RetainsToMove.ReverseInsertPts.clear();
2696 ReleasesToMove.ReverseInsertPts.clear();
2699 // Determine whether the new insertion points we computed preserve the
2700 // balance of retain and release calls through the program.
2701 // TODO: If the fully aggressive solution isn't valid, try to find a
2702 // less aggressive solution which is.
2706 // At this point, we are not going to remove any RR pairs, but we still are
2707 // able to move RR pairs. If one of our pointers is afflicted with
2708 // CFGHazards, we cannot perform such code motion so exit early.
2709 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
2710 ReleasesToMove.ReverseInsertPts.size();
2711 if (CFGHazardAfflicted && WillPerformCodeMotion)
2715 // Determine whether the original call points are balanced in the retain and
2716 // release calls through the program. If not, conservatively don't touch
2718 // TODO: It's theoretically possible to do code motion in this case, as
2719 // long as the existing imbalances are maintained.
2723 #ifdef ARC_ANNOTATIONS
2724 // Do not move calls if ARC annotations are requested.
2725 if (EnableARCAnnotations)
2727 #endif // ARC_ANNOTATIONS
2730 assert(OldCount != 0 && "Unreachable code?");
2731 NumRRs += OldCount - NewCount;
2732 // Set to true if we completely removed any RR pairs.
2733 AnyPairsCompletelyEliminated = NewCount == 0;
2735 // We can move calls!
2739 /// Identify pairings between the retains and releases, and delete and/or move
2742 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2744 MapVector<Value *, RRInfo> &Retains,
2745 DenseMap<Value *, RRInfo> &Releases,
2747 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2749 bool AnyPairsCompletelyEliminated = false;
2750 RRInfo RetainsToMove;
2751 RRInfo ReleasesToMove;
2752 SmallVector<Instruction *, 4> NewRetains;
2753 SmallVector<Instruction *, 4> NewReleases;
2754 SmallVector<Instruction *, 8> DeadInsts;
2756 // Visit each retain.
2757 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2758 E = Retains.end(); I != E; ++I) {
2759 Value *V = I->first;
2760 if (!V) continue; // blotted
2762 Instruction *Retain = cast<Instruction>(V);
2764 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
2766 Value *Arg = GetObjCArg(Retain);
2768 // If the object being released is in static or stack storage, we know it's
2769 // not being managed by ObjC reference counting, so we can delete pairs
2770 // regardless of what possible decrements or uses lie between them.
2771 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
2773 // A constant pointer can't be pointing to an object on the heap. It may
2774 // be reference-counted, but it won't be deleted.
2775 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2776 if (const GlobalVariable *GV =
2777 dyn_cast<GlobalVariable>(
2778 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2779 if (GV->isConstant())
2782 // Connect the dots between the top-down-collected RetainsToMove and
2783 // bottom-up-collected ReleasesToMove to form sets of related calls.
2784 NewRetains.push_back(Retain);
2785 bool PerformMoveCalls =
2786 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2787 NewReleases, DeadInsts, RetainsToMove,
2788 ReleasesToMove, Arg, KnownSafe,
2789 AnyPairsCompletelyEliminated);
2791 if (PerformMoveCalls) {
2792 // Ok, everything checks out and we're all set. Let's move/delete some
2794 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2795 Retains, Releases, DeadInsts, M);
2798 // Clean up state for next retain.
2799 NewReleases.clear();
2801 RetainsToMove.clear();
2802 ReleasesToMove.clear();
2805 // Now that we're done moving everything, we can delete the newly dead
2806 // instructions, as we no longer need them as insert points.
2807 while (!DeadInsts.empty())
2808 EraseInstruction(DeadInsts.pop_back_val());
2810 return AnyPairsCompletelyEliminated;
2813 /// Weak pointer optimizations.
2814 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2815 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
2817 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2818 // itself because it uses AliasAnalysis and we need to do provenance
2820 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2821 Instruction *Inst = &*I++;
2823 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
2825 InstructionClass Class = GetBasicInstructionClass(Inst);
2826 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2829 // Delete objc_loadWeak calls with no users.
2830 if (Class == IC_LoadWeak && Inst->use_empty()) {
2831 Inst->eraseFromParent();
2835 // TODO: For now, just look for an earlier available version of this value
2836 // within the same block. Theoretically, we could do memdep-style non-local
2837 // analysis too, but that would want caching. A better approach would be to
2838 // use the technique that EarlyCSE uses.
2839 inst_iterator Current = llvm::prior(I);
2840 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2841 for (BasicBlock::iterator B = CurrentBB->begin(),
2842 J = Current.getInstructionIterator();
2844 Instruction *EarlierInst = &*llvm::prior(J);
2845 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2846 switch (EarlierClass) {
2848 case IC_LoadWeakRetained: {
2849 // If this is loading from the same pointer, replace this load's value
2851 CallInst *Call = cast<CallInst>(Inst);
2852 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2853 Value *Arg = Call->getArgOperand(0);
2854 Value *EarlierArg = EarlierCall->getArgOperand(0);
2855 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2856 case AliasAnalysis::MustAlias:
2858 // If the load has a builtin retain, insert a plain retain for it.
2859 if (Class == IC_LoadWeakRetained) {
2861 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2865 // Zap the fully redundant load.
2866 Call->replaceAllUsesWith(EarlierCall);
2867 Call->eraseFromParent();
2869 case AliasAnalysis::MayAlias:
2870 case AliasAnalysis::PartialAlias:
2872 case AliasAnalysis::NoAlias:
2879 // If this is storing to the same pointer and has the same size etc.
2880 // replace this load's value with the stored value.
2881 CallInst *Call = cast<CallInst>(Inst);
2882 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2883 Value *Arg = Call->getArgOperand(0);
2884 Value *EarlierArg = EarlierCall->getArgOperand(0);
2885 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2886 case AliasAnalysis::MustAlias:
2888 // If the load has a builtin retain, insert a plain retain for it.
2889 if (Class == IC_LoadWeakRetained) {
2891 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2895 // Zap the fully redundant load.
2896 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2897 Call->eraseFromParent();
2899 case AliasAnalysis::MayAlias:
2900 case AliasAnalysis::PartialAlias:
2902 case AliasAnalysis::NoAlias:
2909 // TOOD: Grab the copied value.
2911 case IC_AutoreleasepoolPush:
2913 case IC_IntrinsicUser:
2915 // Weak pointers are only modified through the weak entry points
2916 // (and arbitrary calls, which could call the weak entry points).
2919 // Anything else could modify the weak pointer.
2926 // Then, for each destroyWeak with an alloca operand, check to see if
2927 // the alloca and all its users can be zapped.
2928 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2929 Instruction *Inst = &*I++;
2930 InstructionClass Class = GetBasicInstructionClass(Inst);
2931 if (Class != IC_DestroyWeak)
2934 CallInst *Call = cast<CallInst>(Inst);
2935 Value *Arg = Call->getArgOperand(0);
2936 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2937 for (Value::use_iterator UI = Alloca->use_begin(),
2938 UE = Alloca->use_end(); UI != UE; ++UI) {
2939 const Instruction *UserInst = cast<Instruction>(*UI);
2940 switch (GetBasicInstructionClass(UserInst)) {
2943 case IC_DestroyWeak:
2950 for (Value::use_iterator UI = Alloca->use_begin(),
2951 UE = Alloca->use_end(); UI != UE; ) {
2952 CallInst *UserInst = cast<CallInst>(*UI++);
2953 switch (GetBasicInstructionClass(UserInst)) {
2956 // These functions return their second argument.
2957 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2959 case IC_DestroyWeak:
2963 llvm_unreachable("alloca really is used!");
2965 UserInst->eraseFromParent();
2967 Alloca->eraseFromParent();
2973 /// Identify program paths which execute sequences of retains and releases which
2974 /// can be eliminated.
2975 bool ObjCARCOpt::OptimizeSequences(Function &F) {
2976 // Releases, Retains - These are used to store the results of the main flow
2977 // analysis. These use Value* as the key instead of Instruction* so that the
2978 // map stays valid when we get around to rewriting code and calls get
2979 // replaced by arguments.
2980 DenseMap<Value *, RRInfo> Releases;
2981 MapVector<Value *, RRInfo> Retains;
2983 // This is used during the traversal of the function to track the
2984 // states for each identified object at each block.
2985 DenseMap<const BasicBlock *, BBState> BBStates;
2987 // Analyze the CFG of the function, and all instructions.
2988 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2991 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2996 MultiOwnersSet.clear();
2998 return AnyPairsCompletelyEliminated && NestingDetected;
3001 /// Check if there is a dependent call earlier that does not have anything in
3002 /// between the Retain and the call that can affect the reference count of their
3003 /// shared pointer argument. Note that Retain need not be in BB.
3005 HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
3006 SmallPtrSet<Instruction *, 4> &DepInsts,
3007 SmallPtrSet<const BasicBlock *, 4> &Visited,
3008 ProvenanceAnalysis &PA) {
3009 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3010 DepInsts, Visited, PA);
3011 if (DepInsts.size() != 1)
3015 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3017 // Check that the pointer is the return value of the call.
3018 if (!Call || Arg != Call)
3021 // Check that the call is a regular call.
3022 InstructionClass Class = GetBasicInstructionClass(Call);
3023 if (Class != IC_CallOrUser && Class != IC_Call)
3029 /// Find a dependent retain that precedes the given autorelease for which there
3030 /// is nothing in between the two instructions that can affect the ref count of
3033 FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
3034 Instruction *Autorelease,
3035 SmallPtrSet<Instruction *, 4> &DepInsts,
3036 SmallPtrSet<const BasicBlock *, 4> &Visited,
3037 ProvenanceAnalysis &PA) {
3038 FindDependencies(CanChangeRetainCount, Arg,
3039 BB, Autorelease, DepInsts, Visited, PA);
3040 if (DepInsts.size() != 1)
3044 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3046 // Check that we found a retain with the same argument.
3048 !IsRetain(GetBasicInstructionClass(Retain)) ||
3049 GetObjCArg(Retain) != Arg) {
3056 /// Look for an ``autorelease'' instruction dependent on Arg such that there are
3057 /// no instructions dependent on Arg that need a positive ref count in between
3058 /// the autorelease and the ret.
3060 FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
3062 SmallPtrSet<Instruction *, 4> &DepInsts,
3063 SmallPtrSet<const BasicBlock *, 4> &V,
3064 ProvenanceAnalysis &PA) {
3065 FindDependencies(NeedsPositiveRetainCount, Arg,
3066 BB, Ret, DepInsts, V, PA);
3067 if (DepInsts.size() != 1)
3070 CallInst *Autorelease =
3071 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3074 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3075 if (!IsAutorelease(AutoreleaseClass))
3077 if (GetObjCArg(Autorelease) != Arg)
3083 /// Look for this pattern:
3085 /// %call = call i8* @something(...)
3086 /// %2 = call i8* @objc_retain(i8* %call)
3087 /// %3 = call i8* @objc_autorelease(i8* %2)
3090 /// And delete the retain and autorelease.
3091 void ObjCARCOpt::OptimizeReturns(Function &F) {
3092 if (!F.getReturnType()->isPointerTy())
3095 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
3097 SmallPtrSet<Instruction *, 4> DependingInstructions;
3098 SmallPtrSet<const BasicBlock *, 4> Visited;
3099 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3100 BasicBlock *BB = FI;
3101 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3103 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
3108 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3110 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
3111 // dependent on Arg such that there are no instructions dependent on Arg
3112 // that need a positive ref count in between the autorelease and Ret.
3113 CallInst *Autorelease =
3114 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
3115 DependingInstructions, Visited,
3117 DependingInstructions.clear();
3124 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
3125 DependingInstructions, Visited, PA);
3126 DependingInstructions.clear();
3132 // Check that there is nothing that can affect the reference count
3133 // between the retain and the call. Note that Retain need not be in BB.
3134 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
3135 DependingInstructions,
3137 DependingInstructions.clear();
3140 if (!HasSafePathToCall)
3143 // If so, we can zap the retain and autorelease.
3146 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
3147 << *Autorelease << "\n");
3148 EraseInstruction(Retain);
3149 EraseInstruction(Autorelease);
3155 ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
3156 llvm::Statistic &NumRetains =
3157 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
3158 llvm::Statistic &NumReleases =
3159 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
3161 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3162 Instruction *Inst = &*I++;
3163 switch (GetBasicInstructionClass(Inst)) {
3177 bool ObjCARCOpt::doInitialization(Module &M) {
3181 // If nothing in the Module uses ARC, don't do anything.
3182 Run = ModuleHasARC(M);
3186 // Identify the imprecise release metadata kind.
3187 ImpreciseReleaseMDKind =
3188 M.getContext().getMDKindID("clang.imprecise_release");
3189 CopyOnEscapeMDKind =
3190 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3191 NoObjCARCExceptionsMDKind =
3192 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3193 #ifdef ARC_ANNOTATIONS
3194 ARCAnnotationBottomUpMDKind =
3195 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3196 ARCAnnotationTopDownMDKind =
3197 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3198 ARCAnnotationProvenanceSourceMDKind =
3199 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3200 #endif // ARC_ANNOTATIONS
3202 // Intuitively, objc_retain and others are nocapture, however in practice
3203 // they are not, because they return their argument value. And objc_release
3204 // calls finalizers which can have arbitrary side effects.
3206 // These are initialized lazily.
3207 AutoreleaseRVCallee = 0;
3210 RetainBlockCallee = 0;
3211 AutoreleaseCallee = 0;
3216 bool ObjCARCOpt::runOnFunction(Function &F) {
3220 // If nothing in the Module uses ARC, don't do anything.
3226 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3229 PA.setAA(&getAnalysis<AliasAnalysis>());
3232 if (AreStatisticsEnabled()) {
3233 GatherStatistics(F, false);
3237 // This pass performs several distinct transformations. As a compile-time aid
3238 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3239 // library functions aren't declared.
3241 // Preliminary optimizations. This also computes UsedInThisFunction.
3242 OptimizeIndividualCalls(F);
3244 // Optimizations for weak pointers.
3245 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3246 (1 << IC_LoadWeakRetained) |
3247 (1 << IC_StoreWeak) |
3248 (1 << IC_InitWeak) |
3249 (1 << IC_CopyWeak) |
3250 (1 << IC_MoveWeak) |
3251 (1 << IC_DestroyWeak)))
3252 OptimizeWeakCalls(F);
3254 // Optimizations for retain+release pairs.
3255 if (UsedInThisFunction & ((1 << IC_Retain) |
3256 (1 << IC_RetainRV) |
3257 (1 << IC_RetainBlock)))
3258 if (UsedInThisFunction & (1 << IC_Release))
3259 // Run OptimizeSequences until it either stops making changes or
3260 // no retain+release pair nesting is detected.
3261 while (OptimizeSequences(F)) {}
3263 // Optimizations if objc_autorelease is used.
3264 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3265 (1 << IC_AutoreleaseRV)))
3268 // Gather statistics after optimization.
3270 if (AreStatisticsEnabled()) {
3271 GatherStatistics(F, true);
3275 DEBUG(dbgs() << "\n");
3280 void ObjCARCOpt::releaseMemory() {