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 bool IsTrackingImpreciseReleases() {
469 return ReleaseMetadata != 0;
474 void RRInfo::clear() {
476 IsTailCallRelease = false;
479 ReverseInsertPts.clear();
480 CFGHazardAfflicted = false;
484 /// \brief This class summarizes several per-pointer runtime properties which
485 /// are propogated through the flow graph.
487 /// True if the reference count is known to be incremented.
488 bool KnownPositiveRefCount;
490 /// True if we've seen an opportunity for partial RR elimination, such as
491 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
494 /// The current position in the sequence.
498 /// Unidirectional information about the current sequence.
500 /// TODO: Encapsulate this better.
503 PtrState() : KnownPositiveRefCount(false), Partial(false),
506 void SetKnownPositiveRefCount() {
507 DEBUG(dbgs() << "Setting Known Positive.\n");
508 KnownPositiveRefCount = true;
511 void ClearKnownPositiveRefCount() {
512 DEBUG(dbgs() << "Clearing Known Positive.\n");
513 KnownPositiveRefCount = false;
516 bool HasKnownPositiveRefCount() const {
517 return KnownPositiveRefCount;
520 void SetSeq(Sequence NewSeq) {
521 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
525 Sequence GetSeq() const {
529 void ClearSequenceProgress() {
530 ResetSequenceProgress(S_None);
533 void ResetSequenceProgress(Sequence NewSeq) {
534 DEBUG(dbgs() << "Resetting sequence progress.\n");
540 void Merge(const PtrState &Other, bool TopDown);
545 PtrState::Merge(const PtrState &Other, bool TopDown) {
546 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
547 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
549 // If we're not in a sequence (anymore), drop all associated state.
553 } else if (Partial || Other.Partial) {
554 // If we're doing a merge on a path that's previously seen a partial
555 // merge, conservatively drop the sequence, to avoid doing partial
556 // RR elimination. If the branch predicates for the two merge differ,
557 // mixing them is unsafe.
558 ClearSequenceProgress();
560 // Conservatively merge the ReleaseMetadata information.
561 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
562 RRI.ReleaseMetadata = 0;
564 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
565 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
566 Other.RRI.IsTailCallRelease;
567 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
568 RRI.CFGHazardAfflicted |= Other.RRI.CFGHazardAfflicted;
570 // Merge the insert point sets. If there are any differences,
571 // that makes this a partial merge.
572 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
573 for (SmallPtrSet<Instruction *, 2>::const_iterator
574 I = Other.RRI.ReverseInsertPts.begin(),
575 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
576 Partial |= RRI.ReverseInsertPts.insert(*I);
581 /// \brief Per-BasicBlock state.
583 /// The number of unique control paths from the entry which can reach this
585 unsigned TopDownPathCount;
587 /// The number of unique control paths to exits from this block.
588 unsigned BottomUpPathCount;
590 /// A type for PerPtrTopDown and PerPtrBottomUp.
591 typedef MapVector<const Value *, PtrState> MapTy;
593 /// The top-down traversal uses this to record information known about a
594 /// pointer at the bottom of each block.
597 /// The bottom-up traversal uses this to record information known about a
598 /// pointer at the top of each block.
599 MapTy PerPtrBottomUp;
601 /// Effective predecessors of the current block ignoring ignorable edges and
602 /// ignored backedges.
603 SmallVector<BasicBlock *, 2> Preds;
604 /// Effective successors of the current block ignoring ignorable edges and
605 /// ignored backedges.
606 SmallVector<BasicBlock *, 2> Succs;
609 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
611 typedef MapTy::iterator ptr_iterator;
612 typedef MapTy::const_iterator ptr_const_iterator;
614 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
615 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
616 ptr_const_iterator top_down_ptr_begin() const {
617 return PerPtrTopDown.begin();
619 ptr_const_iterator top_down_ptr_end() const {
620 return PerPtrTopDown.end();
623 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
624 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
625 ptr_const_iterator bottom_up_ptr_begin() const {
626 return PerPtrBottomUp.begin();
628 ptr_const_iterator bottom_up_ptr_end() const {
629 return PerPtrBottomUp.end();
632 /// Mark this block as being an entry block, which has one path from the
633 /// entry by definition.
634 void SetAsEntry() { TopDownPathCount = 1; }
636 /// Mark this block as being an exit block, which has one path to an exit by
638 void SetAsExit() { BottomUpPathCount = 1; }
640 /// Attempt to find the PtrState object describing the top down state for
641 /// pointer Arg. Return a new initialized PtrState describing the top down
642 /// state for Arg if we do not find one.
643 PtrState &getPtrTopDownState(const Value *Arg) {
644 return PerPtrTopDown[Arg];
647 /// Attempt to find the PtrState object describing the bottom up state for
648 /// pointer Arg. Return a new initialized PtrState describing the bottom up
649 /// state for Arg if we do not find one.
650 PtrState &getPtrBottomUpState(const Value *Arg) {
651 return PerPtrBottomUp[Arg];
654 /// Attempt to find the PtrState object describing the bottom up state for
656 ptr_iterator findPtrBottomUpState(const Value *Arg) {
657 return PerPtrBottomUp.find(Arg);
660 void clearBottomUpPointers() {
661 PerPtrBottomUp.clear();
664 void clearTopDownPointers() {
665 PerPtrTopDown.clear();
668 void InitFromPred(const BBState &Other);
669 void InitFromSucc(const BBState &Other);
670 void MergePred(const BBState &Other);
671 void MergeSucc(const BBState &Other);
673 /// Compute the number of possible unique paths from an entry to an exit
674 /// which pass through this block. This is only valid after both the
675 /// top-down and bottom-up traversals are complete.
677 /// Returns true if overflow occured. Returns false if overflow did not
679 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
680 assert(TopDownPathCount != 0);
681 assert(BottomUpPathCount != 0);
682 unsigned long long Product =
683 (unsigned long long)TopDownPathCount*BottomUpPathCount;
685 // Overflow occured if any of the upper bits of Product are set.
686 return Product >> 32;
689 // Specialized CFG utilities.
690 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
691 edge_iterator pred_begin() { return Preds.begin(); }
692 edge_iterator pred_end() { return Preds.end(); }
693 edge_iterator succ_begin() { return Succs.begin(); }
694 edge_iterator succ_end() { return Succs.end(); }
696 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
697 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
699 bool isExit() const { return Succs.empty(); }
703 void BBState::InitFromPred(const BBState &Other) {
704 PerPtrTopDown = Other.PerPtrTopDown;
705 TopDownPathCount = Other.TopDownPathCount;
708 void BBState::InitFromSucc(const BBState &Other) {
709 PerPtrBottomUp = Other.PerPtrBottomUp;
710 BottomUpPathCount = Other.BottomUpPathCount;
713 /// The top-down traversal uses this to merge information about predecessors to
714 /// form the initial state for a new block.
715 void BBState::MergePred(const BBState &Other) {
716 // Other.TopDownPathCount can be 0, in which case it is either dead or a
717 // loop backedge. Loop backedges are special.
718 TopDownPathCount += Other.TopDownPathCount;
720 // Check for overflow. If we have overflow, fall back to conservative
722 if (TopDownPathCount < Other.TopDownPathCount) {
723 clearTopDownPointers();
727 // For each entry in the other set, if our set has an entry with the same key,
728 // merge the entries. Otherwise, copy the entry and merge it with an empty
730 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
731 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
732 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
733 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
737 // For each entry in our set, if the other set doesn't have an entry with the
738 // same key, force it to merge with an empty entry.
739 for (ptr_iterator MI = top_down_ptr_begin(),
740 ME = top_down_ptr_end(); MI != ME; ++MI)
741 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
742 MI->second.Merge(PtrState(), /*TopDown=*/true);
745 /// The bottom-up traversal uses this to merge information about successors to
746 /// form the initial state for a new block.
747 void BBState::MergeSucc(const BBState &Other) {
748 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
749 // loop backedge. Loop backedges are special.
750 BottomUpPathCount += Other.BottomUpPathCount;
752 // Check for overflow. If we have overflow, fall back to conservative
754 if (BottomUpPathCount < Other.BottomUpPathCount) {
755 clearBottomUpPointers();
759 // For each entry in the other set, if our set has an entry with the
760 // same key, merge the entries. Otherwise, copy the entry and merge
761 // it with an empty entry.
762 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
763 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
764 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
765 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
769 // For each entry in our set, if the other set doesn't have an entry
770 // with the same key, force it to merge with an empty entry.
771 for (ptr_iterator MI = bottom_up_ptr_begin(),
772 ME = bottom_up_ptr_end(); MI != ME; ++MI)
773 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
774 MI->second.Merge(PtrState(), /*TopDown=*/false);
777 // Only enable ARC Annotations if we are building a debug version of
780 #define ARC_ANNOTATIONS
783 // Define some macros along the lines of DEBUG and some helper functions to make
784 // it cleaner to create annotations in the source code and to no-op when not
785 // building in debug mode.
786 #ifdef ARC_ANNOTATIONS
788 #include "llvm/Support/CommandLine.h"
790 /// Enable/disable ARC sequence annotations.
792 EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
793 cl::desc("Enable emission of arc data flow analysis "
796 DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
797 cl::desc("Disable check for cfg hazards when "
799 static cl::opt<std::string>
800 ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
802 cl::desc("filter out all data flow annotations "
803 "but those that apply to the given "
804 "target llvm identifier."));
806 /// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
807 /// instruction so that we can track backwards when post processing via the llvm
808 /// arc annotation processor tool. If the function is an
809 static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
813 // If pointer is a result of an instruction and it does not have a source
814 // MDNode it, attach a new MDNode onto it. If pointer is a result of
815 // an instruction and does have a source MDNode attached to it, return a
816 // reference to said Node. Otherwise just return 0.
817 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
819 if (!(Node = Inst->getMetadata(NodeId))) {
820 // We do not have any node. Generate and attatch the hash MDString to the
823 // We just use an MDString to ensure that this metadata gets written out
824 // of line at the module level and to provide a very simple format
825 // encoding the information herein. Both of these makes it simpler to
826 // parse the annotations by a simple external program.
828 raw_string_ostream os(Str);
829 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
830 << Inst->getName() << ")";
832 Hash = MDString::get(Inst->getContext(), os.str());
833 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
835 // We have a node. Grab its hash and return it.
836 assert(Node->getNumOperands() == 1 &&
837 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
838 Hash = cast<MDString>(Node->getOperand(0));
840 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
842 raw_string_ostream os(str);
843 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
845 Hash = MDString::get(Arg->getContext(), os.str());
851 static std::string SequenceToString(Sequence A) {
853 raw_string_ostream os(str);
858 /// Helper function to change a Sequence into a String object using our overload
859 /// for raw_ostream so we only have printing code in one location.
860 static MDString *SequenceToMDString(LLVMContext &Context,
862 return MDString::get(Context, SequenceToString(A));
865 /// A simple function to generate a MDNode which describes the change in state
866 /// for Value *Ptr caused by Instruction *Inst.
867 static void AppendMDNodeToInstForPtr(unsigned NodeId,
870 MDString *PtrSourceMDNodeID,
874 Value *tmp[3] = {PtrSourceMDNodeID,
875 SequenceToMDString(Inst->getContext(),
877 SequenceToMDString(Inst->getContext(),
879 Node = MDNode::get(Inst->getContext(),
880 ArrayRef<Value*>(tmp, 3));
882 Inst->setMetadata(NodeId, Node);
885 /// Add to the beginning of the basic block llvm.ptr.annotations which show the
886 /// state of a pointer at the entrance to a basic block.
887 static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
888 Value *Ptr, Sequence Seq) {
889 // If we have a target identifier, make sure that we match it before
891 if(!ARCAnnotationTargetIdentifier.empty() &&
892 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
895 Module *M = BB->getParent()->getParent();
896 LLVMContext &C = M->getContext();
897 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
898 Type *I8XX = PointerType::getUnqual(I8X);
899 Type *Params[] = {I8XX, I8XX};
900 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
901 ArrayRef<Type*>(Params, 2),
903 Constant *Callee = M->getOrInsertFunction(Name, FTy);
905 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
908 StringRef Tmp = Ptr->getName();
909 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
910 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
912 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
913 cast<Constant>(ActualPtrName), Tmp);
917 std::string SeqStr = SequenceToString(Seq);
918 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
919 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
921 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
922 cast<Constant>(ActualPtrName), SeqStr);
925 Builder.CreateCall2(Callee, PtrName, S);
928 /// Add to the end of the basic block llvm.ptr.annotations which show the state
929 /// of the pointer at the bottom of the basic block.
930 static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
931 Value *Ptr, Sequence Seq) {
932 // If we have a target identifier, make sure that we match it before emitting
934 if(!ARCAnnotationTargetIdentifier.empty() &&
935 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
938 Module *M = BB->getParent()->getParent();
939 LLVMContext &C = M->getContext();
940 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
941 Type *I8XX = PointerType::getUnqual(I8X);
942 Type *Params[] = {I8XX, I8XX};
943 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
944 ArrayRef<Type*>(Params, 2),
946 Constant *Callee = M->getOrInsertFunction(Name, FTy);
948 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
951 StringRef Tmp = Ptr->getName();
952 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
953 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
955 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
956 cast<Constant>(ActualPtrName), Tmp);
960 std::string SeqStr = SequenceToString(Seq);
961 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
962 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
964 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
965 cast<Constant>(ActualPtrName), SeqStr);
967 Builder.CreateCall2(Callee, PtrName, S);
970 /// Adds a source annotation to pointer and a state change annotation to Inst
971 /// referencing the source annotation and the old/new state of pointer.
972 static void GenerateARCAnnotation(unsigned InstMDId,
978 if (EnableARCAnnotations) {
979 // If we have a target identifier, make sure that we match it before
980 // emitting an annotation.
981 if(!ARCAnnotationTargetIdentifier.empty() &&
982 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
985 // First generate the source annotation on our pointer. This will return an
986 // MDString* if Ptr actually comes from an instruction implying we can put
987 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
988 // then we know that our pointer is from an Argument so we put a reference
989 // to the argument number.
991 // The point of this is to make it easy for the
992 // llvm-arc-annotation-processor tool to cross reference where the source
993 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
994 // information via debug info for backends to use (since why would anyone
995 // need such a thing from LLVM IR besides in non standard cases
997 MDString *SourcePtrMDNode =
998 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
999 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
1004 // The actual interface for accessing the above functionality is defined via
1005 // some simple macros which are defined below. We do this so that the user does
1006 // not need to pass in what metadata id is needed resulting in cleaner code and
1007 // additionally since it provides an easy way to conditionally no-op all
1008 // annotation support in a non-debug build.
1010 /// Use this macro to annotate a sequence state change when processing
1011 /// instructions bottom up,
1012 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
1013 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
1014 ARCAnnotationProvenanceSourceMDKind, (inst), \
1015 const_cast<Value*>(ptr), (old), (new))
1016 /// Use this macro to annotate a sequence state change when processing
1017 /// instructions top down.
1018 #define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
1019 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
1020 ARCAnnotationProvenanceSourceMDKind, (inst), \
1021 const_cast<Value*>(ptr), (old), (new))
1023 #define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
1025 if (EnableARCAnnotations) { \
1026 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
1027 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
1028 Value *Ptr = const_cast<Value*>(I->first); \
1029 Sequence Seq = I->second.GetSeq(); \
1030 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
1035 #define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
1036 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
1037 Entrance, bottom_up)
1038 #define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
1039 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
1040 Terminator, bottom_up)
1041 #define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
1042 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
1044 #define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
1045 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
1046 Terminator, top_down)
1048 #else // !ARC_ANNOTATION
1049 // If annotations are off, noop.
1050 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
1051 #define ANNOTATE_TOPDOWN(inst, ptr, old, new)
1052 #define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
1053 #define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
1054 #define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
1055 #define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
1056 #endif // !ARC_ANNOTATION
1059 /// \brief The main ARC optimization pass.
1060 class ObjCARCOpt : public FunctionPass {
1062 ProvenanceAnalysis PA;
1064 // This is used to track if a pointer is stored into an alloca.
1065 DenseSet<const Value *> MultiOwnersSet;
1067 /// A flag indicating whether this optimization pass should run.
1070 /// Declarations for ObjC runtime functions, for use in creating calls to
1071 /// them. These are initialized lazily to avoid cluttering up the Module
1072 /// with unused declarations.
1074 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1075 Constant *AutoreleaseRVCallee;
1076 /// Declaration for ObjC runtime function objc_release.
1077 Constant *ReleaseCallee;
1078 /// Declaration for ObjC runtime function objc_retain.
1079 Constant *RetainCallee;
1080 /// Declaration for ObjC runtime function objc_retainBlock.
1081 Constant *RetainBlockCallee;
1082 /// Declaration for ObjC runtime function objc_autorelease.
1083 Constant *AutoreleaseCallee;
1085 /// Flags which determine whether each of the interesting runtine functions
1086 /// is in fact used in the current function.
1087 unsigned UsedInThisFunction;
1089 /// The Metadata Kind for clang.imprecise_release metadata.
1090 unsigned ImpreciseReleaseMDKind;
1092 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
1093 unsigned CopyOnEscapeMDKind;
1095 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
1096 unsigned NoObjCARCExceptionsMDKind;
1098 #ifdef ARC_ANNOTATIONS
1099 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1100 unsigned ARCAnnotationBottomUpMDKind;
1101 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1102 unsigned ARCAnnotationTopDownMDKind;
1103 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1104 unsigned ARCAnnotationProvenanceSourceMDKind;
1105 #endif // ARC_ANNOATIONS
1107 Constant *getAutoreleaseRVCallee(Module *M);
1108 Constant *getReleaseCallee(Module *M);
1109 Constant *getRetainCallee(Module *M);
1110 Constant *getRetainBlockCallee(Module *M);
1111 Constant *getAutoreleaseCallee(Module *M);
1113 bool IsRetainBlockOptimizable(const Instruction *Inst);
1115 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1116 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1117 InstructionClass &Class);
1118 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1119 InstructionClass &Class);
1120 void OptimizeIndividualCalls(Function &F);
1122 void CheckForCFGHazards(const BasicBlock *BB,
1123 DenseMap<const BasicBlock *, BBState> &BBStates,
1124 BBState &MyStates) const;
1125 bool VisitInstructionBottomUp(Instruction *Inst,
1127 MapVector<Value *, RRInfo> &Retains,
1129 bool VisitBottomUp(BasicBlock *BB,
1130 DenseMap<const BasicBlock *, BBState> &BBStates,
1131 MapVector<Value *, RRInfo> &Retains);
1132 bool VisitInstructionTopDown(Instruction *Inst,
1133 DenseMap<Value *, RRInfo> &Releases,
1135 bool VisitTopDown(BasicBlock *BB,
1136 DenseMap<const BasicBlock *, BBState> &BBStates,
1137 DenseMap<Value *, RRInfo> &Releases);
1138 bool Visit(Function &F,
1139 DenseMap<const BasicBlock *, BBState> &BBStates,
1140 MapVector<Value *, RRInfo> &Retains,
1141 DenseMap<Value *, RRInfo> &Releases);
1143 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1144 MapVector<Value *, RRInfo> &Retains,
1145 DenseMap<Value *, RRInfo> &Releases,
1146 SmallVectorImpl<Instruction *> &DeadInsts,
1149 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1150 MapVector<Value *, RRInfo> &Retains,
1151 DenseMap<Value *, RRInfo> &Releases,
1153 SmallVector<Instruction *, 4> &NewRetains,
1154 SmallVector<Instruction *, 4> &NewReleases,
1155 SmallVector<Instruction *, 8> &DeadInsts,
1156 RRInfo &RetainsToMove,
1157 RRInfo &ReleasesToMove,
1160 bool &AnyPairsCompletelyEliminated);
1162 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1163 MapVector<Value *, RRInfo> &Retains,
1164 DenseMap<Value *, RRInfo> &Releases,
1167 void OptimizeWeakCalls(Function &F);
1169 bool OptimizeSequences(Function &F);
1171 void OptimizeReturns(Function &F);
1174 void GatherStatistics(Function &F, bool AfterOptimization = false);
1177 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1178 virtual bool doInitialization(Module &M);
1179 virtual bool runOnFunction(Function &F);
1180 virtual void releaseMemory();
1184 ObjCARCOpt() : FunctionPass(ID) {
1185 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1190 char ObjCARCOpt::ID = 0;
1191 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1192 "objc-arc", "ObjC ARC optimization", false, false)
1193 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1194 INITIALIZE_PASS_END(ObjCARCOpt,
1195 "objc-arc", "ObjC ARC optimization", false, false)
1197 Pass *llvm::createObjCARCOptPass() {
1198 return new ObjCARCOpt();
1201 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1202 AU.addRequired<ObjCARCAliasAnalysis>();
1203 AU.addRequired<AliasAnalysis>();
1204 // ARC optimization doesn't currently split critical edges.
1205 AU.setPreservesCFG();
1208 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1209 // Without the magic metadata tag, we have to assume this might be an
1210 // objc_retainBlock call inserted to convert a block pointer to an id,
1211 // in which case it really is needed.
1212 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1215 // If the pointer "escapes" (not including being used in a call),
1216 // the copy may be needed.
1217 if (DoesRetainableObjPtrEscape(Inst))
1220 // Otherwise, it's not needed.
1224 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1225 if (!AutoreleaseRVCallee) {
1226 LLVMContext &C = M->getContext();
1227 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1228 Type *Params[] = { I8X };
1229 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1230 AttributeSet Attribute =
1231 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1232 Attribute::NoUnwind);
1233 AutoreleaseRVCallee =
1234 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1237 return AutoreleaseRVCallee;
1240 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1241 if (!ReleaseCallee) {
1242 LLVMContext &C = M->getContext();
1243 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1244 AttributeSet Attribute =
1245 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1246 Attribute::NoUnwind);
1248 M->getOrInsertFunction(
1250 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1253 return ReleaseCallee;
1256 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1257 if (!RetainCallee) {
1258 LLVMContext &C = M->getContext();
1259 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1260 AttributeSet Attribute =
1261 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1262 Attribute::NoUnwind);
1264 M->getOrInsertFunction(
1266 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1269 return RetainCallee;
1272 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1273 if (!RetainBlockCallee) {
1274 LLVMContext &C = M->getContext();
1275 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1276 // objc_retainBlock is not nounwind because it calls user copy constructors
1277 // which could theoretically throw.
1279 M->getOrInsertFunction(
1281 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1284 return RetainBlockCallee;
1287 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1288 if (!AutoreleaseCallee) {
1289 LLVMContext &C = M->getContext();
1290 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1291 AttributeSet Attribute =
1292 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1293 Attribute::NoUnwind);
1295 M->getOrInsertFunction(
1297 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1300 return AutoreleaseCallee;
1303 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1304 /// not a return value. Or, if it can be paired with an
1305 /// objc_autoreleaseReturnValue, delete the pair and return true.
1307 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1308 // Check for the argument being from an immediately preceding call or invoke.
1309 const Value *Arg = GetObjCArg(RetainRV);
1310 ImmutableCallSite CS(Arg);
1311 if (const Instruction *Call = CS.getInstruction()) {
1312 if (Call->getParent() == RetainRV->getParent()) {
1313 BasicBlock::const_iterator I = Call;
1315 while (IsNoopInstruction(I)) ++I;
1316 if (&*I == RetainRV)
1318 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
1319 BasicBlock *RetainRVParent = RetainRV->getParent();
1320 if (II->getNormalDest() == RetainRVParent) {
1321 BasicBlock::const_iterator I = RetainRVParent->begin();
1322 while (IsNoopInstruction(I)) ++I;
1323 if (&*I == RetainRV)
1329 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1330 // pointer. In this case, we can delete the pair.
1331 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1333 do --I; while (I != Begin && IsNoopInstruction(I));
1334 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1335 GetObjCArg(I) == Arg) {
1339 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1340 << "Erasing " << *RetainRV << "\n");
1342 EraseInstruction(I);
1343 EraseInstruction(RetainRV);
1348 // Turn it to a plain objc_retain.
1352 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
1353 "objc_retain since the operand is not a return value.\n"
1354 "Old = " << *RetainRV << "\n");
1356 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
1358 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
1363 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1364 /// used as a return value.
1366 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1367 InstructionClass &Class) {
1368 // Check for a return of the pointer value.
1369 const Value *Ptr = GetObjCArg(AutoreleaseRV);
1370 SmallVector<const Value *, 2> Users;
1371 Users.push_back(Ptr);
1373 Ptr = Users.pop_back_val();
1374 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1376 const User *I = *UI;
1377 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1379 if (isa<BitCastInst>(I))
1382 } while (!Users.empty());
1387 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
1388 "objc_autorelease since its operand is not used as a return "
1390 "Old = " << *AutoreleaseRV << "\n");
1392 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1394 setCalledFunction(getAutoreleaseCallee(F.getParent()));
1395 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
1396 Class = IC_Autorelease;
1398 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
1402 // \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1405 // Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1406 // does not escape (following the rules of block escaping), strength reduce the
1407 // objc_retainBlock to an objc_retain.
1409 // TODO: If an objc_retainBlock call is dominated period by a previous
1410 // objc_retainBlock call, strength reduce the objc_retainBlock to an
1413 ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1414 InstructionClass &Class) {
1415 assert(GetBasicInstructionClass(Inst) == Class);
1416 assert(IC_RetainBlock == Class);
1418 // If we can not optimize Inst, return false.
1419 if (!IsRetainBlockOptimizable(Inst))
1425 DEBUG(dbgs() << "Strength reduced retainBlock => retain.\n");
1426 DEBUG(dbgs() << "Old: " << *Inst << "\n");
1427 CallInst *RetainBlock = cast<CallInst>(Inst);
1428 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1429 // Remove copy_on_escape metadata.
1430 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1432 DEBUG(dbgs() << "New: " << *Inst << "\n");
1436 /// Visit each call, one at a time, and make simplifications without doing any
1437 /// additional analysis.
1438 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1439 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
1440 // Reset all the flags in preparation for recomputing them.
1441 UsedInThisFunction = 0;
1443 // Visit all objc_* calls in F.
1444 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1445 Instruction *Inst = &*I++;
1447 InstructionClass Class = GetBasicInstructionClass(Inst);
1449 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
1454 // Delete no-op casts. These function calls have special semantics, but
1455 // the semantics are entirely implemented via lowering in the front-end,
1456 // so by the time they reach the optimizer, they are just no-op calls
1457 // which return their argument.
1459 // There are gray areas here, as the ability to cast reference-counted
1460 // pointers to raw void* and back allows code to break ARC assumptions,
1461 // however these are currently considered to be unimportant.
1465 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
1466 EraseInstruction(Inst);
1469 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1472 case IC_LoadWeakRetained:
1474 case IC_DestroyWeak: {
1475 CallInst *CI = cast<CallInst>(Inst);
1476 if (IsNullOrUndef(CI->getArgOperand(0))) {
1478 Type *Ty = CI->getArgOperand(0)->getType();
1479 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1480 Constant::getNullValue(Ty),
1482 llvm::Value *NewValue = UndefValue::get(CI->getType());
1483 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1484 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1485 CI->replaceAllUsesWith(NewValue);
1486 CI->eraseFromParent();
1493 CallInst *CI = cast<CallInst>(Inst);
1494 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1495 IsNullOrUndef(CI->getArgOperand(1))) {
1497 Type *Ty = CI->getArgOperand(0)->getType();
1498 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1499 Constant::getNullValue(Ty),
1502 llvm::Value *NewValue = UndefValue::get(CI->getType());
1503 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1504 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1506 CI->replaceAllUsesWith(NewValue);
1507 CI->eraseFromParent();
1512 case IC_RetainBlock:
1513 // If we strength reduce an objc_retainBlock to an objc_retain, continue
1514 // onto the objc_retain peephole optimizations. Otherwise break.
1515 OptimizeRetainBlockCall(F, Inst, Class);
1518 if (OptimizeRetainRVCall(F, Inst))
1521 case IC_AutoreleaseRV:
1522 OptimizeAutoreleaseRVCall(F, Inst, Class);
1526 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
1527 if (IsAutorelease(Class) && Inst->use_empty()) {
1528 CallInst *Call = cast<CallInst>(Inst);
1529 const Value *Arg = Call->getArgOperand(0);
1530 Arg = FindSingleUseIdentifiedObject(Arg);
1535 // Create the declaration lazily.
1536 LLVMContext &C = Inst->getContext();
1538 CallInst::Create(getReleaseCallee(F.getParent()),
1539 Call->getArgOperand(0), "", Call);
1540 NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
1542 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1543 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1544 << *NewCall << "\n");
1546 EraseInstruction(Call);
1552 // For functions which can never be passed stack arguments, add
1554 if (IsAlwaysTail(Class)) {
1556 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1557 "passed stack args: " << *Inst << "\n");
1558 cast<CallInst>(Inst)->setTailCall();
1561 // Ensure that functions that can never have a "tail" keyword due to the
1562 // semantics of ARC truly do not do so.
1563 if (IsNeverTail(Class)) {
1565 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
1567 cast<CallInst>(Inst)->setTailCall(false);
1570 // Set nounwind as needed.
1571 if (IsNoThrow(Class)) {
1573 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1575 cast<CallInst>(Inst)->setDoesNotThrow();
1578 if (!IsNoopOnNull(Class)) {
1579 UsedInThisFunction |= 1 << Class;
1583 const Value *Arg = GetObjCArg(Inst);
1585 // ARC calls with null are no-ops. Delete them.
1586 if (IsNullOrUndef(Arg)) {
1589 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1591 EraseInstruction(Inst);
1595 // Keep track of which of retain, release, autorelease, and retain_block
1596 // are actually present in this function.
1597 UsedInThisFunction |= 1 << Class;
1599 // If Arg is a PHI, and one or more incoming values to the
1600 // PHI are null, and the call is control-equivalent to the PHI, and there
1601 // are no relevant side effects between the PHI and the call, the call
1602 // could be pushed up to just those paths with non-null incoming values.
1603 // For now, don't bother splitting critical edges for this.
1604 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1605 Worklist.push_back(std::make_pair(Inst, Arg));
1607 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1611 const PHINode *PN = dyn_cast<PHINode>(Arg);
1614 // Determine if the PHI has any null operands, or any incoming
1616 bool HasNull = false;
1617 bool HasCriticalEdges = false;
1618 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1620 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1621 if (IsNullOrUndef(Incoming))
1623 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1624 .getNumSuccessors() != 1) {
1625 HasCriticalEdges = true;
1629 // If we have null operands and no critical edges, optimize.
1630 if (!HasCriticalEdges && HasNull) {
1631 SmallPtrSet<Instruction *, 4> DependingInstructions;
1632 SmallPtrSet<const BasicBlock *, 4> Visited;
1634 // Check that there is nothing that cares about the reference
1635 // count between the call and the phi.
1638 case IC_RetainBlock:
1639 // These can always be moved up.
1642 // These can't be moved across things that care about the retain
1644 FindDependencies(NeedsPositiveRetainCount, Arg,
1645 Inst->getParent(), Inst,
1646 DependingInstructions, Visited, PA);
1648 case IC_Autorelease:
1649 // These can't be moved across autorelease pool scope boundaries.
1650 FindDependencies(AutoreleasePoolBoundary, Arg,
1651 Inst->getParent(), Inst,
1652 DependingInstructions, Visited, PA);
1655 case IC_AutoreleaseRV:
1656 // Don't move these; the RV optimization depends on the autoreleaseRV
1657 // being tail called, and the retainRV being immediately after a call
1658 // (which might still happen if we get lucky with codegen layout, but
1659 // it's not worth taking the chance).
1662 llvm_unreachable("Invalid dependence flavor");
1665 if (DependingInstructions.size() == 1 &&
1666 *DependingInstructions.begin() == PN) {
1669 // Clone the call into each predecessor that has a non-null value.
1670 CallInst *CInst = cast<CallInst>(Inst);
1671 Type *ParamTy = CInst->getArgOperand(0)->getType();
1672 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1674 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1675 if (!IsNullOrUndef(Incoming)) {
1676 CallInst *Clone = cast<CallInst>(CInst->clone());
1677 Value *Op = PN->getIncomingValue(i);
1678 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1679 if (Op->getType() != ParamTy)
1680 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1681 Clone->setArgOperand(0, Op);
1682 Clone->insertBefore(InsertPos);
1684 DEBUG(dbgs() << "Cloning "
1686 "And inserting clone at " << *InsertPos << "\n");
1687 Worklist.push_back(std::make_pair(Clone, Incoming));
1690 // Erase the original call.
1691 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
1692 EraseInstruction(CInst);
1696 } while (!Worklist.empty());
1700 /// If we have a top down pointer in the S_Use state, make sure that there are
1701 /// no CFG hazards by checking the states of various bottom up pointers.
1702 static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1703 const bool SuccSRRIKnownSafe,
1705 bool &SomeSuccHasSame,
1706 bool &AllSuccsHaveSame,
1707 bool &NotAllSeqEqualButKnownSafe,
1708 bool &ShouldContinue) {
1710 case S_CanRelease: {
1711 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
1712 S.ClearSequenceProgress();
1715 S.RRI.CFGHazardAfflicted = true;
1716 ShouldContinue = true;
1720 SomeSuccHasSame = true;
1724 case S_MovableRelease:
1725 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1726 AllSuccsHaveSame = false;
1728 NotAllSeqEqualButKnownSafe = true;
1731 llvm_unreachable("bottom-up pointer in retain state!");
1733 llvm_unreachable("This should have been handled earlier.");
1737 /// If we have a Top Down pointer in the S_CanRelease state, make sure that
1738 /// there are no CFG hazards by checking the states of various bottom up
1740 static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1741 const bool SuccSRRIKnownSafe,
1743 bool &SomeSuccHasSame,
1744 bool &AllSuccsHaveSame,
1745 bool &NotAllSeqEqualButKnownSafe) {
1748 SomeSuccHasSame = true;
1752 case S_MovableRelease:
1754 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1755 AllSuccsHaveSame = false;
1757 NotAllSeqEqualButKnownSafe = true;
1760 llvm_unreachable("bottom-up pointer in retain state!");
1762 llvm_unreachable("This should have been handled earlier.");
1766 /// Check for critical edges, loop boundaries, irreducible control flow, or
1767 /// other CFG structures where moving code across the edge would result in it
1768 /// being executed more.
1770 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1771 DenseMap<const BasicBlock *, BBState> &BBStates,
1772 BBState &MyStates) const {
1773 // If any top-down local-use or possible-dec has a succ which is earlier in
1774 // the sequence, forget it.
1775 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
1776 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1777 PtrState &S = I->second;
1778 const Sequence Seq = I->second.GetSeq();
1780 // We only care about S_Retain, S_CanRelease, and S_Use.
1784 // Make sure that if extra top down states are added in the future that this
1785 // code is updated to handle it.
1786 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1787 "Unknown top down sequence state.");
1789 const Value *Arg = I->first;
1790 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1791 bool SomeSuccHasSame = false;
1792 bool AllSuccsHaveSame = true;
1793 bool NotAllSeqEqualButKnownSafe = false;
1795 succ_const_iterator SI(TI), SE(TI, false);
1797 for (; SI != SE; ++SI) {
1798 // If VisitBottomUp has pointer information for this successor, take
1799 // what we know about it.
1800 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1802 assert(BBI != BBStates.end());
1803 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1804 const Sequence SuccSSeq = SuccS.GetSeq();
1806 // If bottom up, the pointer is in an S_None state, clear the sequence
1807 // progress since the sequence in the bottom up state finished
1808 // suggesting a mismatch in between retains/releases. This is true for
1809 // all three cases that we are handling here: S_Retain, S_Use, and
1811 if (SuccSSeq == S_None) {
1812 S.ClearSequenceProgress();
1816 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1818 const bool SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
1820 // *NOTE* We do not use Seq from above here since we are allowing for
1821 // S.GetSeq() to change while we are visiting basic blocks.
1822 switch(S.GetSeq()) {
1824 bool ShouldContinue = false;
1825 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1826 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
1832 case S_CanRelease: {
1833 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1834 SomeSuccHasSame, AllSuccsHaveSame,
1835 NotAllSeqEqualButKnownSafe);
1842 case S_MovableRelease:
1847 // If the state at the other end of any of the successor edges
1848 // matches the current state, require all edges to match. This
1849 // guards against loops in the middle of a sequence.
1850 if (SomeSuccHasSame && !AllSuccsHaveSame) {
1851 S.ClearSequenceProgress();
1852 } else if (NotAllSeqEqualButKnownSafe) {
1853 // If we would have cleared the state foregoing the fact that we are known
1854 // safe, stop code motion. This is because whether or not it is safe to
1855 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1856 // are allowed to perform code motion.
1857 S.RRI.CFGHazardAfflicted = true;
1863 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
1865 MapVector<Value *, RRInfo> &Retains,
1866 BBState &MyStates) {
1867 bool NestingDetected = false;
1868 InstructionClass Class = GetInstructionClass(Inst);
1869 const Value *Arg = 0;
1871 DEBUG(dbgs() << "Class: " << Class << "\n");
1875 Arg = GetObjCArg(Inst);
1877 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1879 // If we see two releases in a row on the same pointer. If so, make
1880 // a note, and we'll cicle back to revisit it after we've
1881 // hopefully eliminated the second release, which may allow us to
1882 // eliminate the first release too.
1883 // Theoretically we could implement removal of nested retain+release
1884 // pairs by making PtrState hold a stack of states, but this is
1885 // simple and avoids adding overhead for the non-nested case.
1886 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
1887 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
1888 NestingDetected = true;
1891 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
1892 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1893 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1894 S.ResetSequenceProgress(NewSeq);
1895 S.RRI.ReleaseMetadata = ReleaseMetadata;
1896 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
1897 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1898 S.RRI.Calls.insert(Inst);
1899 S.SetKnownPositiveRefCount();
1902 case IC_RetainBlock:
1903 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1904 // objc_retainBlocks to objc_retains. Thus at this point any
1905 // objc_retainBlocks that we see are not optimizable.
1909 Arg = GetObjCArg(Inst);
1911 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1912 S.SetKnownPositiveRefCount();
1914 Sequence OldSeq = S.GetSeq();
1918 case S_MovableRelease:
1920 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1921 // imprecise release, clear our reverse insertion points.
1922 if (OldSeq != S_Use || S.RRI.IsTrackingImpreciseReleases())
1923 S.RRI.ReverseInsertPts.clear();
1926 // Don't do retain+release tracking for IC_RetainRV, because it's
1927 // better to let it remain as the first instruction after a call.
1928 if (Class != IC_RetainRV)
1929 Retains[Inst] = S.RRI;
1930 S.ClearSequenceProgress();
1935 llvm_unreachable("bottom-up pointer in retain state!");
1937 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
1938 // A retain moving bottom up can be a use.
1941 case IC_AutoreleasepoolPop:
1942 // Conservatively, clear MyStates for all known pointers.
1943 MyStates.clearBottomUpPointers();
1944 return NestingDetected;
1945 case IC_AutoreleasepoolPush:
1947 // These are irrelevant.
1948 return NestingDetected;
1950 // If we have a store into an alloca of a pointer we are tracking, the
1951 // pointer has multiple owners implying that we must be more conservative.
1953 // This comes up in the context of a pointer being ``KnownSafe''. In the
1954 // presense of a block being initialized, the frontend will emit the
1955 // objc_retain on the original pointer and the release on the pointer loaded
1956 // from the alloca. The optimizer will through the provenance analysis
1957 // realize that the two are related, but since we only require KnownSafe in
1958 // one direction, will match the inner retain on the original pointer with
1959 // the guard release on the original pointer. This is fixed by ensuring that
1960 // in the presense of allocas we only unconditionally remove pointers if
1961 // both our retain and our release are KnownSafe.
1962 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1963 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
1964 BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
1965 StripPointerCastsAndObjCCalls(SI->getValueOperand()));
1966 if (I != MyStates.bottom_up_ptr_end())
1967 MultiOwnersSet.insert(I->first);
1975 // Consider any other possible effects of this instruction on each
1976 // pointer being tracked.
1977 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1978 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1979 const Value *Ptr = MI->first;
1981 continue; // Handled above.
1982 PtrState &S = MI->second;
1983 Sequence Seq = S.GetSeq();
1985 // Check for possible releases.
1986 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
1987 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1989 S.ClearKnownPositiveRefCount();
1992 S.SetSeq(S_CanRelease);
1993 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
1997 case S_MovableRelease:
2002 llvm_unreachable("bottom-up pointer in retain state!");
2006 // Check for possible direct uses.
2009 case S_MovableRelease:
2010 if (CanUse(Inst, Ptr, PA, Class)) {
2011 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2013 assert(S.RRI.ReverseInsertPts.empty());
2014 // If this is an invoke instruction, we're scanning it as part of
2015 // one of its successor blocks, since we can't insert code after it
2016 // in its own block, and we don't want to split critical edges.
2017 if (isa<InvokeInst>(Inst))
2018 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2020 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2022 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2023 } else if (Seq == S_Release && IsUser(Class)) {
2024 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
2026 // Non-movable releases depend on any possible objc pointer use.
2028 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
2029 assert(S.RRI.ReverseInsertPts.empty());
2030 // As above; handle invoke specially.
2031 if (isa<InvokeInst>(Inst))
2032 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2034 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2038 if (CanUse(Inst, Ptr, PA, Class)) {
2039 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
2042 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2050 llvm_unreachable("bottom-up pointer in retain state!");
2054 return NestingDetected;
2058 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2059 DenseMap<const BasicBlock *, BBState> &BBStates,
2060 MapVector<Value *, RRInfo> &Retains) {
2062 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
2064 bool NestingDetected = false;
2065 BBState &MyStates = BBStates[BB];
2067 // Merge the states from each successor to compute the initial state
2068 // for the current block.
2069 BBState::edge_iterator SI(MyStates.succ_begin()),
2070 SE(MyStates.succ_end());
2072 const BasicBlock *Succ = *SI;
2073 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2074 assert(I != BBStates.end());
2075 MyStates.InitFromSucc(I->second);
2077 for (; SI != SE; ++SI) {
2079 I = BBStates.find(Succ);
2080 assert(I != BBStates.end());
2081 MyStates.MergeSucc(I->second);
2085 // If ARC Annotations are enabled, output the current state of pointers at the
2086 // bottom of the basic block.
2087 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
2089 // Visit all the instructions, bottom-up.
2090 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2091 Instruction *Inst = llvm::prior(I);
2093 // Invoke instructions are visited as part of their successors (below).
2094 if (isa<InvokeInst>(Inst))
2097 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
2099 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2102 // If there's a predecessor with an invoke, visit the invoke as if it were
2103 // part of this block, since we can't insert code after an invoke in its own
2104 // block, and we don't want to split critical edges.
2105 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2106 PE(MyStates.pred_end()); PI != PE; ++PI) {
2107 BasicBlock *Pred = *PI;
2108 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2109 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
2112 // If ARC Annotations are enabled, output the current state of pointers at the
2113 // top of the basic block.
2114 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
2116 return NestingDetected;
2120 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2121 DenseMap<Value *, RRInfo> &Releases,
2122 BBState &MyStates) {
2123 bool NestingDetected = false;
2124 InstructionClass Class = GetInstructionClass(Inst);
2125 const Value *Arg = 0;
2128 case IC_RetainBlock:
2129 // In OptimizeIndividualCalls, we have strength reduced all optimizable
2130 // objc_retainBlocks to objc_retains. Thus at this point any
2131 // objc_retainBlocks that we see are not optimizable.
2135 Arg = GetObjCArg(Inst);
2137 PtrState &S = MyStates.getPtrTopDownState(Arg);
2139 // Don't do retain+release tracking for IC_RetainRV, because it's
2140 // better to let it remain as the first instruction after a call.
2141 if (Class != IC_RetainRV) {
2142 // If we see two retains in a row on the same pointer. If so, make
2143 // a note, and we'll cicle back to revisit it after we've
2144 // hopefully eliminated the second retain, which may allow us to
2145 // eliminate the first retain too.
2146 // Theoretically we could implement removal of nested retain+release
2147 // pairs by making PtrState hold a stack of states, but this is
2148 // simple and avoids adding overhead for the non-nested case.
2149 if (S.GetSeq() == S_Retain)
2150 NestingDetected = true;
2152 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
2153 S.ResetSequenceProgress(S_Retain);
2154 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
2155 S.RRI.Calls.insert(Inst);
2158 S.SetKnownPositiveRefCount();
2160 // A retain can be a potential use; procede to the generic checking
2165 Arg = GetObjCArg(Inst);
2167 PtrState &S = MyStates.getPtrTopDownState(Arg);
2168 S.ClearKnownPositiveRefCount();
2170 Sequence OldSeq = S.GetSeq();
2172 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2177 if (OldSeq == S_Retain || ReleaseMetadata != 0)
2178 S.RRI.ReverseInsertPts.clear();
2181 S.RRI.ReleaseMetadata = ReleaseMetadata;
2182 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2183 Releases[Inst] = S.RRI;
2184 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
2185 S.ClearSequenceProgress();
2191 case S_MovableRelease:
2192 llvm_unreachable("top-down pointer in release state!");
2196 case IC_AutoreleasepoolPop:
2197 // Conservatively, clear MyStates for all known pointers.
2198 MyStates.clearTopDownPointers();
2199 return NestingDetected;
2200 case IC_AutoreleasepoolPush:
2202 // These are irrelevant.
2203 return NestingDetected;
2208 // Consider any other possible effects of this instruction on each
2209 // pointer being tracked.
2210 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2211 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2212 const Value *Ptr = MI->first;
2214 continue; // Handled above.
2215 PtrState &S = MI->second;
2216 Sequence Seq = S.GetSeq();
2218 // Check for possible releases.
2219 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2220 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
2222 S.ClearKnownPositiveRefCount();
2225 S.SetSeq(S_CanRelease);
2226 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
2227 assert(S.RRI.ReverseInsertPts.empty());
2228 S.RRI.ReverseInsertPts.insert(Inst);
2230 // One call can't cause a transition from S_Retain to S_CanRelease
2231 // and S_CanRelease to S_Use. If we've made the first transition,
2240 case S_MovableRelease:
2241 llvm_unreachable("top-down pointer in release state!");
2245 // Check for possible direct uses.
2248 if (CanUse(Inst, Ptr, PA, Class)) {
2249 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2252 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2261 case S_MovableRelease:
2262 llvm_unreachable("top-down pointer in release state!");
2266 return NestingDetected;
2270 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2271 DenseMap<const BasicBlock *, BBState> &BBStates,
2272 DenseMap<Value *, RRInfo> &Releases) {
2273 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
2274 bool NestingDetected = false;
2275 BBState &MyStates = BBStates[BB];
2277 // Merge the states from each predecessor to compute the initial state
2278 // for the current block.
2279 BBState::edge_iterator PI(MyStates.pred_begin()),
2280 PE(MyStates.pred_end());
2282 const BasicBlock *Pred = *PI;
2283 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2284 assert(I != BBStates.end());
2285 MyStates.InitFromPred(I->second);
2287 for (; PI != PE; ++PI) {
2289 I = BBStates.find(Pred);
2290 assert(I != BBStates.end());
2291 MyStates.MergePred(I->second);
2295 // If ARC Annotations are enabled, output the current state of pointers at the
2296 // top of the basic block.
2297 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
2299 // Visit all the instructions, top-down.
2300 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2301 Instruction *Inst = I;
2303 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
2305 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
2308 // If ARC Annotations are enabled, output the current state of pointers at the
2309 // bottom of the basic block.
2310 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
2312 #ifdef ARC_ANNOTATIONS
2313 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
2315 CheckForCFGHazards(BB, BBStates, MyStates);
2316 return NestingDetected;
2320 ComputePostOrders(Function &F,
2321 SmallVectorImpl<BasicBlock *> &PostOrder,
2322 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2323 unsigned NoObjCARCExceptionsMDKind,
2324 DenseMap<const BasicBlock *, BBState> &BBStates) {
2325 /// The visited set, for doing DFS walks.
2326 SmallPtrSet<BasicBlock *, 16> Visited;
2328 // Do DFS, computing the PostOrder.
2329 SmallPtrSet<BasicBlock *, 16> OnStack;
2330 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2332 // Functions always have exactly one entry block, and we don't have
2333 // any other block that we treat like an entry block.
2334 BasicBlock *EntryBB = &F.getEntryBlock();
2335 BBState &MyStates = BBStates[EntryBB];
2336 MyStates.SetAsEntry();
2337 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2338 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
2339 Visited.insert(EntryBB);
2340 OnStack.insert(EntryBB);
2343 BasicBlock *CurrBB = SuccStack.back().first;
2344 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2345 succ_iterator SE(TI, false);
2347 while (SuccStack.back().second != SE) {
2348 BasicBlock *SuccBB = *SuccStack.back().second++;
2349 if (Visited.insert(SuccBB)) {
2350 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2351 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
2352 BBStates[CurrBB].addSucc(SuccBB);
2353 BBState &SuccStates = BBStates[SuccBB];
2354 SuccStates.addPred(CurrBB);
2355 OnStack.insert(SuccBB);
2359 if (!OnStack.count(SuccBB)) {
2360 BBStates[CurrBB].addSucc(SuccBB);
2361 BBStates[SuccBB].addPred(CurrBB);
2364 OnStack.erase(CurrBB);
2365 PostOrder.push_back(CurrBB);
2366 SuccStack.pop_back();
2367 } while (!SuccStack.empty());
2371 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2372 // Functions may have many exits, and there also blocks which we treat
2373 // as exits due to ignored edges.
2374 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2375 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2376 BasicBlock *ExitBB = I;
2377 BBState &MyStates = BBStates[ExitBB];
2378 if (!MyStates.isExit())
2381 MyStates.SetAsExit();
2383 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
2384 Visited.insert(ExitBB);
2385 while (!PredStack.empty()) {
2386 reverse_dfs_next_succ:
2387 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2388 while (PredStack.back().second != PE) {
2389 BasicBlock *BB = *PredStack.back().second++;
2390 if (Visited.insert(BB)) {
2391 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
2392 goto reverse_dfs_next_succ;
2395 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2400 // Visit the function both top-down and bottom-up.
2402 ObjCARCOpt::Visit(Function &F,
2403 DenseMap<const BasicBlock *, BBState> &BBStates,
2404 MapVector<Value *, RRInfo> &Retains,
2405 DenseMap<Value *, RRInfo> &Releases) {
2407 // Use reverse-postorder traversals, because we magically know that loops
2408 // will be well behaved, i.e. they won't repeatedly call retain on a single
2409 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2410 // class here because we want the reverse-CFG postorder to consider each
2411 // function exit point, and we want to ignore selected cycle edges.
2412 SmallVector<BasicBlock *, 16> PostOrder;
2413 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2414 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2415 NoObjCARCExceptionsMDKind,
2418 // Use reverse-postorder on the reverse CFG for bottom-up.
2419 bool BottomUpNestingDetected = false;
2420 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2421 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2423 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
2425 // Use reverse-postorder for top-down.
2426 bool TopDownNestingDetected = false;
2427 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2428 PostOrder.rbegin(), E = PostOrder.rend();
2430 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
2432 return TopDownNestingDetected && BottomUpNestingDetected;
2435 /// Move the calls in RetainsToMove and ReleasesToMove.
2436 void ObjCARCOpt::MoveCalls(Value *Arg,
2437 RRInfo &RetainsToMove,
2438 RRInfo &ReleasesToMove,
2439 MapVector<Value *, RRInfo> &Retains,
2440 DenseMap<Value *, RRInfo> &Releases,
2441 SmallVectorImpl<Instruction *> &DeadInsts,
2443 Type *ArgTy = Arg->getType();
2444 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2446 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
2448 // Insert the new retain and release calls.
2449 for (SmallPtrSet<Instruction *, 2>::const_iterator
2450 PI = ReleasesToMove.ReverseInsertPts.begin(),
2451 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2452 Instruction *InsertPt = *PI;
2453 Value *MyArg = ArgTy == ParamTy ? Arg :
2454 new BitCastInst(Arg, ParamTy, "", InsertPt);
2456 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
2457 Call->setDoesNotThrow();
2458 Call->setTailCall();
2460 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
2461 "At insertion point: " << *InsertPt << "\n");
2463 for (SmallPtrSet<Instruction *, 2>::const_iterator
2464 PI = RetainsToMove.ReverseInsertPts.begin(),
2465 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2466 Instruction *InsertPt = *PI;
2467 Value *MyArg = ArgTy == ParamTy ? Arg :
2468 new BitCastInst(Arg, ParamTy, "", InsertPt);
2469 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2471 // Attach a clang.imprecise_release metadata tag, if appropriate.
2472 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2473 Call->setMetadata(ImpreciseReleaseMDKind, M);
2474 Call->setDoesNotThrow();
2475 if (ReleasesToMove.IsTailCallRelease)
2476 Call->setTailCall();
2478 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2479 "At insertion point: " << *InsertPt << "\n");
2482 // Delete the original retain and release calls.
2483 for (SmallPtrSet<Instruction *, 2>::const_iterator
2484 AI = RetainsToMove.Calls.begin(),
2485 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2486 Instruction *OrigRetain = *AI;
2487 Retains.blot(OrigRetain);
2488 DeadInsts.push_back(OrigRetain);
2489 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
2491 for (SmallPtrSet<Instruction *, 2>::const_iterator
2492 AI = ReleasesToMove.Calls.begin(),
2493 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2494 Instruction *OrigRelease = *AI;
2495 Releases.erase(OrigRelease);
2496 DeadInsts.push_back(OrigRelease);
2497 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
2503 ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2505 MapVector<Value *, RRInfo> &Retains,
2506 DenseMap<Value *, RRInfo> &Releases,
2508 SmallVector<Instruction *, 4> &NewRetains,
2509 SmallVector<Instruction *, 4> &NewReleases,
2510 SmallVector<Instruction *, 8> &DeadInsts,
2511 RRInfo &RetainsToMove,
2512 RRInfo &ReleasesToMove,
2515 bool &AnyPairsCompletelyEliminated) {
2516 // If a pair happens in a region where it is known that the reference count
2517 // is already incremented, we can similarly ignore possible decrements unless
2518 // we are dealing with a retainable object with multiple provenance sources.
2519 bool KnownSafeTD = true, KnownSafeBU = true;
2520 bool MultipleOwners = false;
2521 bool CFGHazardAfflicted = false;
2523 // Connect the dots between the top-down-collected RetainsToMove and
2524 // bottom-up-collected ReleasesToMove to form sets of related calls.
2525 // This is an iterative process so that we connect multiple releases
2526 // to multiple retains if needed.
2527 unsigned OldDelta = 0;
2528 unsigned NewDelta = 0;
2529 unsigned OldCount = 0;
2530 unsigned NewCount = 0;
2531 bool FirstRelease = true;
2533 for (SmallVectorImpl<Instruction *>::const_iterator
2534 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2535 Instruction *NewRetain = *NI;
2536 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2537 assert(It != Retains.end());
2538 const RRInfo &NewRetainRRI = It->second;
2539 KnownSafeTD &= NewRetainRRI.KnownSafe;
2541 MultipleOwners || MultiOwnersSet.count(GetObjCArg(NewRetain));
2542 for (SmallPtrSet<Instruction *, 2>::const_iterator
2543 LI = NewRetainRRI.Calls.begin(),
2544 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2545 Instruction *NewRetainRelease = *LI;
2546 DenseMap<Value *, RRInfo>::const_iterator Jt =
2547 Releases.find(NewRetainRelease);
2548 if (Jt == Releases.end())
2550 const RRInfo &NewRetainReleaseRRI = Jt->second;
2551 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2552 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2554 // If we overflow when we compute the path count, don't remove/move
2556 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
2558 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2560 OldDelta -= PathCount;
2562 // Merge the ReleaseMetadata and IsTailCallRelease values.
2564 ReleasesToMove.ReleaseMetadata =
2565 NewRetainReleaseRRI.ReleaseMetadata;
2566 ReleasesToMove.IsTailCallRelease =
2567 NewRetainReleaseRRI.IsTailCallRelease;
2568 FirstRelease = false;
2570 if (ReleasesToMove.ReleaseMetadata !=
2571 NewRetainReleaseRRI.ReleaseMetadata)
2572 ReleasesToMove.ReleaseMetadata = 0;
2573 if (ReleasesToMove.IsTailCallRelease !=
2574 NewRetainReleaseRRI.IsTailCallRelease)
2575 ReleasesToMove.IsTailCallRelease = false;
2578 // Collect the optimal insertion points.
2580 for (SmallPtrSet<Instruction *, 2>::const_iterator
2581 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2582 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2584 Instruction *RIP = *RI;
2585 if (ReleasesToMove.ReverseInsertPts.insert(RIP)) {
2586 // If we overflow when we compute the path count, don't
2587 // remove/move anything.
2588 const BBState &RIPBBState = BBStates[RIP->getParent()];
2589 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2591 NewDelta -= PathCount;
2594 NewReleases.push_back(NewRetainRelease);
2599 if (NewReleases.empty()) break;
2601 // Back the other way.
2602 for (SmallVectorImpl<Instruction *>::const_iterator
2603 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2604 Instruction *NewRelease = *NI;
2605 DenseMap<Value *, RRInfo>::const_iterator It =
2606 Releases.find(NewRelease);
2607 assert(It != Releases.end());
2608 const RRInfo &NewReleaseRRI = It->second;
2609 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2610 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
2611 for (SmallPtrSet<Instruction *, 2>::const_iterator
2612 LI = NewReleaseRRI.Calls.begin(),
2613 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2614 Instruction *NewReleaseRetain = *LI;
2615 MapVector<Value *, RRInfo>::const_iterator Jt =
2616 Retains.find(NewReleaseRetain);
2617 if (Jt == Retains.end())
2619 const RRInfo &NewReleaseRetainRRI = Jt->second;
2620 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2621 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2623 // If we overflow when we compute the path count, don't remove/move
2625 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
2627 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2629 OldDelta += PathCount;
2630 OldCount += PathCount;
2632 // Collect the optimal insertion points.
2634 for (SmallPtrSet<Instruction *, 2>::const_iterator
2635 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2636 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2638 Instruction *RIP = *RI;
2639 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2640 // If we overflow when we compute the path count, don't
2641 // remove/move anything.
2642 const BBState &RIPBBState = BBStates[RIP->getParent()];
2643 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2645 NewDelta += PathCount;
2646 NewCount += PathCount;
2649 NewRetains.push_back(NewReleaseRetain);
2653 NewReleases.clear();
2654 if (NewRetains.empty()) break;
2657 // If the pointer is known incremented in 1 direction and we do not have
2658 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2659 // to be known safe in both directions.
2660 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2661 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2662 if (UnconditionallySafe) {
2663 RetainsToMove.ReverseInsertPts.clear();
2664 ReleasesToMove.ReverseInsertPts.clear();
2667 // Determine whether the new insertion points we computed preserve the
2668 // balance of retain and release calls through the program.
2669 // TODO: If the fully aggressive solution isn't valid, try to find a
2670 // less aggressive solution which is.
2674 // At this point, we are not going to remove any RR pairs, but we still are
2675 // able to move RR pairs. If one of our pointers is afflicted with
2676 // CFGHazards, we cannot perform such code motion so exit early.
2677 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
2678 ReleasesToMove.ReverseInsertPts.size();
2679 if (CFGHazardAfflicted && WillPerformCodeMotion)
2683 // Determine whether the original call points are balanced in the retain and
2684 // release calls through the program. If not, conservatively don't touch
2686 // TODO: It's theoretically possible to do code motion in this case, as
2687 // long as the existing imbalances are maintained.
2691 #ifdef ARC_ANNOTATIONS
2692 // Do not move calls if ARC annotations are requested.
2693 if (EnableARCAnnotations)
2695 #endif // ARC_ANNOTATIONS
2698 assert(OldCount != 0 && "Unreachable code?");
2699 NumRRs += OldCount - NewCount;
2700 // Set to true if we completely removed any RR pairs.
2701 AnyPairsCompletelyEliminated = NewCount == 0;
2703 // We can move calls!
2707 /// Identify pairings between the retains and releases, and delete and/or move
2710 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2712 MapVector<Value *, RRInfo> &Retains,
2713 DenseMap<Value *, RRInfo> &Releases,
2715 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2717 bool AnyPairsCompletelyEliminated = false;
2718 RRInfo RetainsToMove;
2719 RRInfo ReleasesToMove;
2720 SmallVector<Instruction *, 4> NewRetains;
2721 SmallVector<Instruction *, 4> NewReleases;
2722 SmallVector<Instruction *, 8> DeadInsts;
2724 // Visit each retain.
2725 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2726 E = Retains.end(); I != E; ++I) {
2727 Value *V = I->first;
2728 if (!V) continue; // blotted
2730 Instruction *Retain = cast<Instruction>(V);
2732 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
2734 Value *Arg = GetObjCArg(Retain);
2736 // If the object being released is in static or stack storage, we know it's
2737 // not being managed by ObjC reference counting, so we can delete pairs
2738 // regardless of what possible decrements or uses lie between them.
2739 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
2741 // A constant pointer can't be pointing to an object on the heap. It may
2742 // be reference-counted, but it won't be deleted.
2743 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2744 if (const GlobalVariable *GV =
2745 dyn_cast<GlobalVariable>(
2746 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2747 if (GV->isConstant())
2750 // Connect the dots between the top-down-collected RetainsToMove and
2751 // bottom-up-collected ReleasesToMove to form sets of related calls.
2752 NewRetains.push_back(Retain);
2753 bool PerformMoveCalls =
2754 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2755 NewReleases, DeadInsts, RetainsToMove,
2756 ReleasesToMove, Arg, KnownSafe,
2757 AnyPairsCompletelyEliminated);
2759 if (PerformMoveCalls) {
2760 // Ok, everything checks out and we're all set. Let's move/delete some
2762 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2763 Retains, Releases, DeadInsts, M);
2766 // Clean up state for next retain.
2767 NewReleases.clear();
2769 RetainsToMove.clear();
2770 ReleasesToMove.clear();
2773 // Now that we're done moving everything, we can delete the newly dead
2774 // instructions, as we no longer need them as insert points.
2775 while (!DeadInsts.empty())
2776 EraseInstruction(DeadInsts.pop_back_val());
2778 return AnyPairsCompletelyEliminated;
2781 /// Weak pointer optimizations.
2782 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2783 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
2785 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2786 // itself because it uses AliasAnalysis and we need to do provenance
2788 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2789 Instruction *Inst = &*I++;
2791 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
2793 InstructionClass Class = GetBasicInstructionClass(Inst);
2794 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2797 // Delete objc_loadWeak calls with no users.
2798 if (Class == IC_LoadWeak && Inst->use_empty()) {
2799 Inst->eraseFromParent();
2803 // TODO: For now, just look for an earlier available version of this value
2804 // within the same block. Theoretically, we could do memdep-style non-local
2805 // analysis too, but that would want caching. A better approach would be to
2806 // use the technique that EarlyCSE uses.
2807 inst_iterator Current = llvm::prior(I);
2808 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2809 for (BasicBlock::iterator B = CurrentBB->begin(),
2810 J = Current.getInstructionIterator();
2812 Instruction *EarlierInst = &*llvm::prior(J);
2813 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2814 switch (EarlierClass) {
2816 case IC_LoadWeakRetained: {
2817 // If this is loading from the same pointer, replace this load's value
2819 CallInst *Call = cast<CallInst>(Inst);
2820 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2821 Value *Arg = Call->getArgOperand(0);
2822 Value *EarlierArg = EarlierCall->getArgOperand(0);
2823 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2824 case AliasAnalysis::MustAlias:
2826 // If the load has a builtin retain, insert a plain retain for it.
2827 if (Class == IC_LoadWeakRetained) {
2829 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2833 // Zap the fully redundant load.
2834 Call->replaceAllUsesWith(EarlierCall);
2835 Call->eraseFromParent();
2837 case AliasAnalysis::MayAlias:
2838 case AliasAnalysis::PartialAlias:
2840 case AliasAnalysis::NoAlias:
2847 // If this is storing to the same pointer and has the same size etc.
2848 // replace this load's value with the stored value.
2849 CallInst *Call = cast<CallInst>(Inst);
2850 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2851 Value *Arg = Call->getArgOperand(0);
2852 Value *EarlierArg = EarlierCall->getArgOperand(0);
2853 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2854 case AliasAnalysis::MustAlias:
2856 // If the load has a builtin retain, insert a plain retain for it.
2857 if (Class == IC_LoadWeakRetained) {
2859 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2863 // Zap the fully redundant load.
2864 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2865 Call->eraseFromParent();
2867 case AliasAnalysis::MayAlias:
2868 case AliasAnalysis::PartialAlias:
2870 case AliasAnalysis::NoAlias:
2877 // TOOD: Grab the copied value.
2879 case IC_AutoreleasepoolPush:
2881 case IC_IntrinsicUser:
2883 // Weak pointers are only modified through the weak entry points
2884 // (and arbitrary calls, which could call the weak entry points).
2887 // Anything else could modify the weak pointer.
2894 // Then, for each destroyWeak with an alloca operand, check to see if
2895 // the alloca and all its users can be zapped.
2896 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2897 Instruction *Inst = &*I++;
2898 InstructionClass Class = GetBasicInstructionClass(Inst);
2899 if (Class != IC_DestroyWeak)
2902 CallInst *Call = cast<CallInst>(Inst);
2903 Value *Arg = Call->getArgOperand(0);
2904 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2905 for (Value::use_iterator UI = Alloca->use_begin(),
2906 UE = Alloca->use_end(); UI != UE; ++UI) {
2907 const Instruction *UserInst = cast<Instruction>(*UI);
2908 switch (GetBasicInstructionClass(UserInst)) {
2911 case IC_DestroyWeak:
2918 for (Value::use_iterator UI = Alloca->use_begin(),
2919 UE = Alloca->use_end(); UI != UE; ) {
2920 CallInst *UserInst = cast<CallInst>(*UI++);
2921 switch (GetBasicInstructionClass(UserInst)) {
2924 // These functions return their second argument.
2925 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2927 case IC_DestroyWeak:
2931 llvm_unreachable("alloca really is used!");
2933 UserInst->eraseFromParent();
2935 Alloca->eraseFromParent();
2941 /// Identify program paths which execute sequences of retains and releases which
2942 /// can be eliminated.
2943 bool ObjCARCOpt::OptimizeSequences(Function &F) {
2944 // Releases, Retains - These are used to store the results of the main flow
2945 // analysis. These use Value* as the key instead of Instruction* so that the
2946 // map stays valid when we get around to rewriting code and calls get
2947 // replaced by arguments.
2948 DenseMap<Value *, RRInfo> Releases;
2949 MapVector<Value *, RRInfo> Retains;
2951 // This is used during the traversal of the function to track the
2952 // states for each identified object at each block.
2953 DenseMap<const BasicBlock *, BBState> BBStates;
2955 // Analyze the CFG of the function, and all instructions.
2956 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2959 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2964 MultiOwnersSet.clear();
2966 return AnyPairsCompletelyEliminated && NestingDetected;
2969 /// Check if there is a dependent call earlier that does not have anything in
2970 /// between the Retain and the call that can affect the reference count of their
2971 /// shared pointer argument. Note that Retain need not be in BB.
2973 HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2974 SmallPtrSet<Instruction *, 4> &DepInsts,
2975 SmallPtrSet<const BasicBlock *, 4> &Visited,
2976 ProvenanceAnalysis &PA) {
2977 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2978 DepInsts, Visited, PA);
2979 if (DepInsts.size() != 1)
2983 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2985 // Check that the pointer is the return value of the call.
2986 if (!Call || Arg != Call)
2989 // Check that the call is a regular call.
2990 InstructionClass Class = GetBasicInstructionClass(Call);
2991 if (Class != IC_CallOrUser && Class != IC_Call)
2997 /// Find a dependent retain that precedes the given autorelease for which there
2998 /// is nothing in between the two instructions that can affect the ref count of
3001 FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
3002 Instruction *Autorelease,
3003 SmallPtrSet<Instruction *, 4> &DepInsts,
3004 SmallPtrSet<const BasicBlock *, 4> &Visited,
3005 ProvenanceAnalysis &PA) {
3006 FindDependencies(CanChangeRetainCount, Arg,
3007 BB, Autorelease, DepInsts, Visited, PA);
3008 if (DepInsts.size() != 1)
3012 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3014 // Check that we found a retain with the same argument.
3016 !IsRetain(GetBasicInstructionClass(Retain)) ||
3017 GetObjCArg(Retain) != Arg) {
3024 /// Look for an ``autorelease'' instruction dependent on Arg such that there are
3025 /// no instructions dependent on Arg that need a positive ref count in between
3026 /// the autorelease and the ret.
3028 FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
3030 SmallPtrSet<Instruction *, 4> &DepInsts,
3031 SmallPtrSet<const BasicBlock *, 4> &V,
3032 ProvenanceAnalysis &PA) {
3033 FindDependencies(NeedsPositiveRetainCount, Arg,
3034 BB, Ret, DepInsts, V, PA);
3035 if (DepInsts.size() != 1)
3038 CallInst *Autorelease =
3039 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3042 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3043 if (!IsAutorelease(AutoreleaseClass))
3045 if (GetObjCArg(Autorelease) != Arg)
3051 /// Look for this pattern:
3053 /// %call = call i8* @something(...)
3054 /// %2 = call i8* @objc_retain(i8* %call)
3055 /// %3 = call i8* @objc_autorelease(i8* %2)
3058 /// And delete the retain and autorelease.
3059 void ObjCARCOpt::OptimizeReturns(Function &F) {
3060 if (!F.getReturnType()->isPointerTy())
3063 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
3065 SmallPtrSet<Instruction *, 4> DependingInstructions;
3066 SmallPtrSet<const BasicBlock *, 4> Visited;
3067 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3068 BasicBlock *BB = FI;
3069 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3071 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
3076 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3078 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
3079 // dependent on Arg such that there are no instructions dependent on Arg
3080 // that need a positive ref count in between the autorelease and Ret.
3081 CallInst *Autorelease =
3082 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
3083 DependingInstructions, Visited,
3085 DependingInstructions.clear();
3092 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
3093 DependingInstructions, Visited, PA);
3094 DependingInstructions.clear();
3100 // Check that there is nothing that can affect the reference count
3101 // between the retain and the call. Note that Retain need not be in BB.
3102 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
3103 DependingInstructions,
3105 DependingInstructions.clear();
3108 if (!HasSafePathToCall)
3111 // If so, we can zap the retain and autorelease.
3114 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
3115 << *Autorelease << "\n");
3116 EraseInstruction(Retain);
3117 EraseInstruction(Autorelease);
3123 ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
3124 llvm::Statistic &NumRetains =
3125 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
3126 llvm::Statistic &NumReleases =
3127 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
3129 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3130 Instruction *Inst = &*I++;
3131 switch (GetBasicInstructionClass(Inst)) {
3145 bool ObjCARCOpt::doInitialization(Module &M) {
3149 // If nothing in the Module uses ARC, don't do anything.
3150 Run = ModuleHasARC(M);
3154 // Identify the imprecise release metadata kind.
3155 ImpreciseReleaseMDKind =
3156 M.getContext().getMDKindID("clang.imprecise_release");
3157 CopyOnEscapeMDKind =
3158 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3159 NoObjCARCExceptionsMDKind =
3160 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3161 #ifdef ARC_ANNOTATIONS
3162 ARCAnnotationBottomUpMDKind =
3163 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3164 ARCAnnotationTopDownMDKind =
3165 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3166 ARCAnnotationProvenanceSourceMDKind =
3167 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3168 #endif // ARC_ANNOTATIONS
3170 // Intuitively, objc_retain and others are nocapture, however in practice
3171 // they are not, because they return their argument value. And objc_release
3172 // calls finalizers which can have arbitrary side effects.
3174 // These are initialized lazily.
3175 AutoreleaseRVCallee = 0;
3178 RetainBlockCallee = 0;
3179 AutoreleaseCallee = 0;
3184 bool ObjCARCOpt::runOnFunction(Function &F) {
3188 // If nothing in the Module uses ARC, don't do anything.
3194 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3197 PA.setAA(&getAnalysis<AliasAnalysis>());
3200 if (AreStatisticsEnabled()) {
3201 GatherStatistics(F, false);
3205 // This pass performs several distinct transformations. As a compile-time aid
3206 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3207 // library functions aren't declared.
3209 // Preliminary optimizations. This also computes UsedInThisFunction.
3210 OptimizeIndividualCalls(F);
3212 // Optimizations for weak pointers.
3213 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3214 (1 << IC_LoadWeakRetained) |
3215 (1 << IC_StoreWeak) |
3216 (1 << IC_InitWeak) |
3217 (1 << IC_CopyWeak) |
3218 (1 << IC_MoveWeak) |
3219 (1 << IC_DestroyWeak)))
3220 OptimizeWeakCalls(F);
3222 // Optimizations for retain+release pairs.
3223 if (UsedInThisFunction & ((1 << IC_Retain) |
3224 (1 << IC_RetainRV) |
3225 (1 << IC_RetainBlock)))
3226 if (UsedInThisFunction & (1 << IC_Release))
3227 // Run OptimizeSequences until it either stops making changes or
3228 // no retain+release pair nesting is detected.
3229 while (OptimizeSequences(F)) {}
3231 // Optimizations if objc_autorelease is used.
3232 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3233 (1 << IC_AutoreleaseRV)))
3236 // Gather statistics after optimization.
3238 if (AreStatisticsEnabled()) {
3239 GatherStatistics(F, true);
3243 DEBUG(dbgs() << "\n");
3248 void ObjCARCOpt::releaseMemory() {