1 //===- ObjCARCOpts.cpp - ObjC ARC Optimization ----------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 /// This file defines ObjC ARC optimizations. ARC stands for Automatic
11 /// Reference Counting and is a system for managing reference counts for objects
14 /// The optimizations performed include elimination of redundant, partially
15 /// redundant, and inconsequential reference count operations, elimination of
16 /// redundant weak pointer operations, and numerous minor simplifications.
18 /// WARNING: This file knows about certain library functions. It recognizes them
19 /// by name, and hardwires knowledge of their semantics.
21 /// WARNING: This file knows about how certain Objective-C library functions are
22 /// used. Naive LLVM IR transformations which would otherwise be
23 /// behavior-preserving may break these assumptions.
25 //===----------------------------------------------------------------------===//
27 #define DEBUG_TYPE "objc-arc-opts"
29 #include "DependencyAnalysis.h"
30 #include "ObjCARCAliasAnalysis.h"
31 #include "ProvenanceAnalysis.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/DenseSet.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/IR/IRBuilder.h"
38 #include "llvm/IR/LLVMContext.h"
39 #include "llvm/Support/CFG.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/raw_ostream.h"
44 using namespace llvm::objcarc;
46 /// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
50 /// \brief An associative container with fast insertion-order (deterministic)
51 /// iteration over its elements. Plus the special blot operation.
52 template<class KeyT, class ValueT>
54 /// Map keys to indices in Vector.
55 typedef DenseMap<KeyT, size_t> MapTy;
58 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
63 typedef typename VectorTy::iterator iterator;
64 typedef typename VectorTy::const_iterator const_iterator;
65 iterator begin() { return Vector.begin(); }
66 iterator end() { return Vector.end(); }
67 const_iterator begin() const { return Vector.begin(); }
68 const_iterator end() const { return Vector.end(); }
72 assert(Vector.size() >= Map.size()); // May differ due to blotting.
73 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
75 assert(I->second < Vector.size());
76 assert(Vector[I->second].first == I->first);
78 for (typename VectorTy::const_iterator I = Vector.begin(),
79 E = Vector.end(); I != E; ++I)
81 (Map.count(I->first) &&
82 Map[I->first] == size_t(I - Vector.begin())));
86 ValueT &operator[](const KeyT &Arg) {
87 std::pair<typename MapTy::iterator, bool> Pair =
88 Map.insert(std::make_pair(Arg, size_t(0)));
90 size_t Num = Vector.size();
91 Pair.first->second = Num;
92 Vector.push_back(std::make_pair(Arg, ValueT()));
93 return Vector[Num].second;
95 return Vector[Pair.first->second].second;
98 std::pair<iterator, bool>
99 insert(const std::pair<KeyT, ValueT> &InsertPair) {
100 std::pair<typename MapTy::iterator, bool> Pair =
101 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
103 size_t Num = Vector.size();
104 Pair.first->second = Num;
105 Vector.push_back(InsertPair);
106 return std::make_pair(Vector.begin() + Num, true);
108 return std::make_pair(Vector.begin() + Pair.first->second, false);
111 iterator find(const KeyT &Key) {
112 typename MapTy::iterator It = Map.find(Key);
113 if (It == Map.end()) return Vector.end();
114 return Vector.begin() + It->second;
117 const_iterator find(const KeyT &Key) const {
118 typename MapTy::const_iterator It = Map.find(Key);
119 if (It == Map.end()) return Vector.end();
120 return Vector.begin() + It->second;
123 /// This is similar to erase, but instead of removing the element from the
124 /// vector, it just zeros out the key in the vector. This leaves iterators
125 /// intact, but clients must be prepared for zeroed-out keys when iterating.
126 void blot(const KeyT &Key) {
127 typename MapTy::iterator It = Map.find(Key);
128 if (It == Map.end()) return;
129 Vector[It->second].first = KeyT();
142 /// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
145 /// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
146 /// as it finds a value with multiple uses.
147 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
148 if (Arg->hasOneUse()) {
149 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
150 return FindSingleUseIdentifiedObject(BC->getOperand(0));
151 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
152 if (GEP->hasAllZeroIndices())
153 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
154 if (IsForwarding(GetBasicInstructionClass(Arg)))
155 return FindSingleUseIdentifiedObject(
156 cast<CallInst>(Arg)->getArgOperand(0));
157 if (!IsObjCIdentifiedObject(Arg))
162 // If we found an identifiable object but it has multiple uses, but they are
163 // trivial uses, we can still consider this to be a single-use value.
164 if (IsObjCIdentifiedObject(Arg)) {
165 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
168 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
178 /// \brief Test whether the given retainable object pointer escapes.
180 /// This differs from regular escape analysis in that a use as an
181 /// argument to a call is not considered an escape.
183 static bool DoesRetainableObjPtrEscape(const User *Ptr) {
184 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Target: " << *Ptr << "\n");
186 // Walk the def-use chains.
187 SmallVector<const Value *, 4> Worklist;
188 Worklist.push_back(Ptr);
189 // If Ptr has any operands add them as well.
190 for (User::const_op_iterator I = Ptr->op_begin(), E = Ptr->op_end(); I != E;
192 Worklist.push_back(*I);
195 // Ensure we do not visit any value twice.
196 SmallPtrSet<const Value *, 8> VisitedSet;
199 const Value *V = Worklist.pop_back_val();
201 DEBUG(dbgs() << "Visiting: " << *V << "\n");
203 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
205 const User *UUser = *UI;
207 DEBUG(dbgs() << "User: " << *UUser << "\n");
209 // Special - Use by a call (callee or argument) is not considered
211 switch (GetBasicInstructionClass(UUser)) {
216 case IC_AutoreleaseRV: {
217 DEBUG(dbgs() << "User copies pointer arguments. Pointer Escapes!\n");
218 // These special functions make copies of their pointer arguments.
221 case IC_IntrinsicUser:
222 // Use by the use intrinsic is not an escape.
226 // Use by an instruction which copies the value is an escape if the
227 // result is an escape.
228 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
229 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
231 if (VisitedSet.insert(UUser)) {
232 DEBUG(dbgs() << "User copies value. Ptr escapes if result escapes."
233 " Adding to list.\n");
234 Worklist.push_back(UUser);
236 DEBUG(dbgs() << "Already visited node.\n");
240 // Use by a load is not an escape.
241 if (isa<LoadInst>(UUser))
243 // Use by a store is not an escape if the use is the address.
244 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
245 if (V != SI->getValueOperand())
249 // Regular calls and other stuff are not considered escapes.
252 // Otherwise, conservatively assume an escape.
253 DEBUG(dbgs() << "Assuming ptr escapes.\n");
256 } while (!Worklist.empty());
259 DEBUG(dbgs() << "Ptr does not escape.\n");
263 /// This is a wrapper around getUnderlyingObjCPtr along the lines of
264 /// GetUnderlyingObjects except that it returns early when it sees the first
266 static inline bool AreAnyUnderlyingObjectsAnAlloca(const Value *V) {
267 SmallPtrSet<const Value *, 4> Visited;
268 SmallVector<const Value *, 4> Worklist;
269 Worklist.push_back(V);
271 const Value *P = Worklist.pop_back_val();
272 P = GetUnderlyingObjCPtr(P);
274 if (isa<AllocaInst>(P))
277 if (!Visited.insert(P))
280 if (const SelectInst *SI = dyn_cast<const SelectInst>(P)) {
281 Worklist.push_back(SI->getTrueValue());
282 Worklist.push_back(SI->getFalseValue());
286 if (const PHINode *PN = dyn_cast<const PHINode>(P)) {
287 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
288 Worklist.push_back(PN->getIncomingValue(i));
291 } while (!Worklist.empty());
299 /// \defgroup ARCOpt ARC Optimization.
302 // TODO: On code like this:
305 // stuff_that_cannot_release()
306 // objc_autorelease(%x)
307 // stuff_that_cannot_release()
309 // stuff_that_cannot_release()
310 // objc_autorelease(%x)
312 // The second retain and autorelease can be deleted.
314 // TODO: It should be possible to delete
315 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
316 // pairs if nothing is actually autoreleased between them. Also, autorelease
317 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
318 // after inlining) can be turned into plain release calls.
320 // TODO: Critical-edge splitting. If the optimial insertion point is
321 // a critical edge, the current algorithm has to fail, because it doesn't
322 // know how to split edges. It should be possible to make the optimizer
323 // think in terms of edges, rather than blocks, and then split critical
326 // TODO: OptimizeSequences could generalized to be Interprocedural.
328 // TODO: Recognize that a bunch of other objc runtime calls have
329 // non-escaping arguments and non-releasing arguments, and may be
330 // non-autoreleasing.
332 // TODO: Sink autorelease calls as far as possible. Unfortunately we
333 // usually can't sink them past other calls, which would be the main
334 // case where it would be useful.
336 // TODO: The pointer returned from objc_loadWeakRetained is retained.
338 // TODO: Delete release+retain pairs (rare).
340 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
341 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
342 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
343 STATISTIC(NumRets, "Number of return value forwarding "
344 "retain+autoreleases eliminated");
345 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
346 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
348 STATISTIC(NumRetainsBeforeOpt,
349 "Number of retains before optimization");
350 STATISTIC(NumReleasesBeforeOpt,
351 "Number of releases before optimization");
352 STATISTIC(NumRetainsAfterOpt,
353 "Number of retains after optimization");
354 STATISTIC(NumReleasesAfterOpt,
355 "Number of releases after optimization");
361 /// \brief A sequence of states that a pointer may go through in which an
362 /// objc_retain and objc_release are actually needed.
365 S_Retain, ///< objc_retain(x).
366 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement.
367 S_Use, ///< any use of x.
368 S_Stop, ///< like S_Release, but code motion is stopped.
369 S_Release, ///< objc_release(x).
370 S_MovableRelease ///< objc_release(x), !clang.imprecise_release.
373 raw_ostream &operator<<(raw_ostream &OS, const Sequence S)
374 LLVM_ATTRIBUTE_UNUSED;
375 raw_ostream &operator<<(raw_ostream &OS, const Sequence S) {
378 return OS << "S_None";
380 return OS << "S_Retain";
382 return OS << "S_CanRelease";
384 return OS << "S_Use";
386 return OS << "S_Release";
387 case S_MovableRelease:
388 return OS << "S_MovableRelease";
390 return OS << "S_Stop";
392 llvm_unreachable("Unknown sequence type.");
396 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
400 if (A == S_None || B == S_None)
403 if (A > B) std::swap(A, B);
405 // Choose the side which is further along in the sequence.
406 if ((A == S_Retain || A == S_CanRelease) &&
407 (B == S_CanRelease || B == S_Use))
410 // Choose the side which is further along in the sequence.
411 if ((A == S_Use || A == S_CanRelease) &&
412 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
414 // If both sides are releases, choose the more conservative one.
415 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
417 if (A == S_Release && B == S_MovableRelease)
425 /// \brief Unidirectional information about either a
426 /// retain-decrement-use-release sequence or release-use-decrement-retain
427 /// reverse sequence.
429 /// After an objc_retain, the reference count of the referenced
430 /// object is known to be positive. Similarly, before an objc_release, the
431 /// reference count of the referenced object is known to be positive. If
432 /// there are retain-release pairs in code regions where the retain count
433 /// is known to be positive, they can be eliminated, regardless of any side
434 /// effects between them.
436 /// Also, a retain+release pair nested within another retain+release
437 /// pair all on the known same pointer value can be eliminated, regardless
438 /// of any intervening side effects.
440 /// KnownSafe is true when either of these conditions is satisfied.
443 /// True of the objc_release calls are all marked with the "tail" keyword.
444 bool IsTailCallRelease;
446 /// If the Calls are objc_release calls and they all have a
447 /// clang.imprecise_release tag, this is the metadata tag.
448 MDNode *ReleaseMetadata;
450 /// For a top-down sequence, the set of objc_retains or
451 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
452 SmallPtrSet<Instruction *, 2> Calls;
454 /// The set of optimal insert positions for moving calls in the opposite
456 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
458 /// If this is true, we cannot perform code motion but can still remove
459 /// retain/release pairs.
460 bool CFGHazardAfflicted;
463 KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(0),
464 CFGHazardAfflicted(false) {}
468 /// Conservatively merge the two RRInfo. Returns true if a partial merge has
469 /// occured, false otherwise.
470 bool Merge(const RRInfo &Other);
472 bool IsTrackingImpreciseReleases() {
473 return ReleaseMetadata != 0;
478 void RRInfo::clear() {
480 IsTailCallRelease = false;
483 ReverseInsertPts.clear();
484 CFGHazardAfflicted = false;
487 bool RRInfo::Merge(const RRInfo &Other) {
488 // Conservatively merge the ReleaseMetadata information.
489 if (ReleaseMetadata != Other.ReleaseMetadata)
492 // Conservatively merge the boolean state.
493 KnownSafe &= Other.KnownSafe;
494 IsTailCallRelease &= Other.IsTailCallRelease;
495 CFGHazardAfflicted |= Other.CFGHazardAfflicted;
497 // Merge the call sets.
498 Calls.insert(Other.Calls.begin(), Other.Calls.end());
500 // Merge the insert point sets. If there are any differences,
501 // that makes this a partial merge.
502 bool Partial = ReverseInsertPts.size() != Other.ReverseInsertPts.size();
503 for (SmallPtrSet<Instruction *, 2>::const_iterator
504 I = Other.ReverseInsertPts.begin(),
505 E = Other.ReverseInsertPts.end(); I != E; ++I)
506 Partial |= ReverseInsertPts.insert(*I);
511 /// \brief This class summarizes several per-pointer runtime properties which
512 /// are propogated through the flow graph.
514 /// True if the reference count is known to be incremented.
515 bool KnownPositiveRefCount;
517 /// True if we've seen an opportunity for partial RR elimination, such as
518 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
521 /// The current position in the sequence.
525 /// Unidirectional information about the current sequence.
527 /// TODO: Encapsulate this better.
530 PtrState() : KnownPositiveRefCount(false), Partial(false),
533 void SetKnownPositiveRefCount() {
534 DEBUG(dbgs() << "Setting Known Positive.\n");
535 KnownPositiveRefCount = true;
538 void ClearKnownPositiveRefCount() {
539 DEBUG(dbgs() << "Clearing Known Positive.\n");
540 KnownPositiveRefCount = false;
543 bool HasKnownPositiveRefCount() const {
544 return KnownPositiveRefCount;
547 void SetSeq(Sequence NewSeq) {
548 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
552 Sequence GetSeq() const {
556 void ClearSequenceProgress() {
557 ResetSequenceProgress(S_None);
560 void ResetSequenceProgress(Sequence NewSeq) {
561 DEBUG(dbgs() << "Resetting sequence progress.\n");
567 void Merge(const PtrState &Other, bool TopDown);
572 PtrState::Merge(const PtrState &Other, bool TopDown) {
573 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
574 KnownPositiveRefCount &= Other.KnownPositiveRefCount;
576 // If we're not in a sequence (anymore), drop all associated state.
580 } else if (Partial || Other.Partial) {
581 // If we're doing a merge on a path that's previously seen a partial
582 // merge, conservatively drop the sequence, to avoid doing partial
583 // RR elimination. If the branch predicates for the two merge differ,
584 // mixing them is unsafe.
585 ClearSequenceProgress();
587 // Otherwise merge the other PtrState's RRInfo into our RRInfo. At this
588 // point, we know that currently we are not partial. Stash whether or not
589 // the merge operation caused us to undergo a partial merging of reverse
591 Partial = RRI.Merge(Other.RRI);
596 /// \brief Per-BasicBlock state.
598 /// The number of unique control paths from the entry which can reach this
600 unsigned TopDownPathCount;
602 /// The number of unique control paths to exits from this block.
603 unsigned BottomUpPathCount;
605 /// A type for PerPtrTopDown and PerPtrBottomUp.
606 typedef MapVector<const Value *, PtrState> MapTy;
608 /// The top-down traversal uses this to record information known about a
609 /// pointer at the bottom of each block.
612 /// The bottom-up traversal uses this to record information known about a
613 /// pointer at the top of each block.
614 MapTy PerPtrBottomUp;
616 /// Effective predecessors of the current block ignoring ignorable edges and
617 /// ignored backedges.
618 SmallVector<BasicBlock *, 2> Preds;
619 /// Effective successors of the current block ignoring ignorable edges and
620 /// ignored backedges.
621 SmallVector<BasicBlock *, 2> Succs;
624 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
626 typedef MapTy::iterator ptr_iterator;
627 typedef MapTy::const_iterator ptr_const_iterator;
629 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
630 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
631 ptr_const_iterator top_down_ptr_begin() const {
632 return PerPtrTopDown.begin();
634 ptr_const_iterator top_down_ptr_end() const {
635 return PerPtrTopDown.end();
638 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
639 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
640 ptr_const_iterator bottom_up_ptr_begin() const {
641 return PerPtrBottomUp.begin();
643 ptr_const_iterator bottom_up_ptr_end() const {
644 return PerPtrBottomUp.end();
647 /// Mark this block as being an entry block, which has one path from the
648 /// entry by definition.
649 void SetAsEntry() { TopDownPathCount = 1; }
651 /// Mark this block as being an exit block, which has one path to an exit by
653 void SetAsExit() { BottomUpPathCount = 1; }
655 /// Attempt to find the PtrState object describing the top down state for
656 /// pointer Arg. Return a new initialized PtrState describing the top down
657 /// state for Arg if we do not find one.
658 PtrState &getPtrTopDownState(const Value *Arg) {
659 return PerPtrTopDown[Arg];
662 /// Attempt to find the PtrState object describing the bottom up state for
663 /// pointer Arg. Return a new initialized PtrState describing the bottom up
664 /// state for Arg if we do not find one.
665 PtrState &getPtrBottomUpState(const Value *Arg) {
666 return PerPtrBottomUp[Arg];
669 /// Attempt to find the PtrState object describing the bottom up state for
671 ptr_iterator findPtrBottomUpState(const Value *Arg) {
672 return PerPtrBottomUp.find(Arg);
675 void clearBottomUpPointers() {
676 PerPtrBottomUp.clear();
679 void clearTopDownPointers() {
680 PerPtrTopDown.clear();
683 void InitFromPred(const BBState &Other);
684 void InitFromSucc(const BBState &Other);
685 void MergePred(const BBState &Other);
686 void MergeSucc(const BBState &Other);
688 /// Compute the number of possible unique paths from an entry to an exit
689 /// which pass through this block. This is only valid after both the
690 /// top-down and bottom-up traversals are complete.
692 /// Returns true if overflow occured. Returns false if overflow did not
694 bool GetAllPathCountWithOverflow(unsigned &PathCount) const {
695 assert(TopDownPathCount != 0);
696 assert(BottomUpPathCount != 0);
697 unsigned long long Product =
698 (unsigned long long)TopDownPathCount*BottomUpPathCount;
700 // Overflow occured if any of the upper bits of Product are set.
701 return Product >> 32;
704 // Specialized CFG utilities.
705 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
706 edge_iterator pred_begin() { return Preds.begin(); }
707 edge_iterator pred_end() { return Preds.end(); }
708 edge_iterator succ_begin() { return Succs.begin(); }
709 edge_iterator succ_end() { return Succs.end(); }
711 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
712 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
714 bool isExit() const { return Succs.empty(); }
718 void BBState::InitFromPred(const BBState &Other) {
719 PerPtrTopDown = Other.PerPtrTopDown;
720 TopDownPathCount = Other.TopDownPathCount;
723 void BBState::InitFromSucc(const BBState &Other) {
724 PerPtrBottomUp = Other.PerPtrBottomUp;
725 BottomUpPathCount = Other.BottomUpPathCount;
728 /// The top-down traversal uses this to merge information about predecessors to
729 /// form the initial state for a new block.
730 void BBState::MergePred(const BBState &Other) {
731 // Other.TopDownPathCount can be 0, in which case it is either dead or a
732 // loop backedge. Loop backedges are special.
733 TopDownPathCount += Other.TopDownPathCount;
735 // Check for overflow. If we have overflow, fall back to conservative
737 if (TopDownPathCount < Other.TopDownPathCount) {
738 clearTopDownPointers();
742 // For each entry in the other set, if our set has an entry with the same key,
743 // merge the entries. Otherwise, copy the entry and merge it with an empty
745 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
746 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
747 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
748 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
752 // For each entry in our set, if the other set doesn't have an entry with the
753 // same key, force it to merge with an empty entry.
754 for (ptr_iterator MI = top_down_ptr_begin(),
755 ME = top_down_ptr_end(); MI != ME; ++MI)
756 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
757 MI->second.Merge(PtrState(), /*TopDown=*/true);
760 /// The bottom-up traversal uses this to merge information about successors to
761 /// form the initial state for a new block.
762 void BBState::MergeSucc(const BBState &Other) {
763 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
764 // loop backedge. Loop backedges are special.
765 BottomUpPathCount += Other.BottomUpPathCount;
767 // Check for overflow. If we have overflow, fall back to conservative
769 if (BottomUpPathCount < Other.BottomUpPathCount) {
770 clearBottomUpPointers();
774 // For each entry in the other set, if our set has an entry with the
775 // same key, merge the entries. Otherwise, copy the entry and merge
776 // it with an empty entry.
777 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
778 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
779 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
780 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
784 // For each entry in our set, if the other set doesn't have an entry
785 // with the same key, force it to merge with an empty entry.
786 for (ptr_iterator MI = bottom_up_ptr_begin(),
787 ME = bottom_up_ptr_end(); MI != ME; ++MI)
788 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
789 MI->second.Merge(PtrState(), /*TopDown=*/false);
792 // Only enable ARC Annotations if we are building a debug version of
795 #define ARC_ANNOTATIONS
798 // Define some macros along the lines of DEBUG and some helper functions to make
799 // it cleaner to create annotations in the source code and to no-op when not
800 // building in debug mode.
801 #ifdef ARC_ANNOTATIONS
803 #include "llvm/Support/CommandLine.h"
805 /// Enable/disable ARC sequence annotations.
807 EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
808 cl::desc("Enable emission of arc data flow analysis "
811 DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
812 cl::desc("Disable check for cfg hazards when "
814 static cl::opt<std::string>
815 ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
817 cl::desc("filter out all data flow annotations "
818 "but those that apply to the given "
819 "target llvm identifier."));
821 /// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
822 /// instruction so that we can track backwards when post processing via the llvm
823 /// arc annotation processor tool. If the function is an
824 static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
828 // If pointer is a result of an instruction and it does not have a source
829 // MDNode it, attach a new MDNode onto it. If pointer is a result of
830 // an instruction and does have a source MDNode attached to it, return a
831 // reference to said Node. Otherwise just return 0.
832 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
834 if (!(Node = Inst->getMetadata(NodeId))) {
835 // We do not have any node. Generate and attatch the hash MDString to the
838 // We just use an MDString to ensure that this metadata gets written out
839 // of line at the module level and to provide a very simple format
840 // encoding the information herein. Both of these makes it simpler to
841 // parse the annotations by a simple external program.
843 raw_string_ostream os(Str);
844 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
845 << Inst->getName() << ")";
847 Hash = MDString::get(Inst->getContext(), os.str());
848 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
850 // We have a node. Grab its hash and return it.
851 assert(Node->getNumOperands() == 1 &&
852 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
853 Hash = cast<MDString>(Node->getOperand(0));
855 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
857 raw_string_ostream os(str);
858 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
860 Hash = MDString::get(Arg->getContext(), os.str());
866 static std::string SequenceToString(Sequence A) {
868 raw_string_ostream os(str);
873 /// Helper function to change a Sequence into a String object using our overload
874 /// for raw_ostream so we only have printing code in one location.
875 static MDString *SequenceToMDString(LLVMContext &Context,
877 return MDString::get(Context, SequenceToString(A));
880 /// A simple function to generate a MDNode which describes the change in state
881 /// for Value *Ptr caused by Instruction *Inst.
882 static void AppendMDNodeToInstForPtr(unsigned NodeId,
885 MDString *PtrSourceMDNodeID,
889 Value *tmp[3] = {PtrSourceMDNodeID,
890 SequenceToMDString(Inst->getContext(),
892 SequenceToMDString(Inst->getContext(),
894 Node = MDNode::get(Inst->getContext(),
895 ArrayRef<Value*>(tmp, 3));
897 Inst->setMetadata(NodeId, Node);
900 /// Add to the beginning of the basic block llvm.ptr.annotations which show the
901 /// state of a pointer at the entrance to a basic block.
902 static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
903 Value *Ptr, Sequence Seq) {
904 // If we have a target identifier, make sure that we match it before
906 if(!ARCAnnotationTargetIdentifier.empty() &&
907 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
910 Module *M = BB->getParent()->getParent();
911 LLVMContext &C = M->getContext();
912 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
913 Type *I8XX = PointerType::getUnqual(I8X);
914 Type *Params[] = {I8XX, I8XX};
915 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
916 ArrayRef<Type*>(Params, 2),
918 Constant *Callee = M->getOrInsertFunction(Name, FTy);
920 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
923 StringRef Tmp = Ptr->getName();
924 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
925 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
927 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
928 cast<Constant>(ActualPtrName), Tmp);
932 std::string SeqStr = SequenceToString(Seq);
933 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
934 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
936 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
937 cast<Constant>(ActualPtrName), SeqStr);
940 Builder.CreateCall2(Callee, PtrName, S);
943 /// Add to the end of the basic block llvm.ptr.annotations which show the state
944 /// of the pointer at the bottom of the basic block.
945 static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
946 Value *Ptr, Sequence Seq) {
947 // If we have a target identifier, make sure that we match it before emitting
949 if(!ARCAnnotationTargetIdentifier.empty() &&
950 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
953 Module *M = BB->getParent()->getParent();
954 LLVMContext &C = M->getContext();
955 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
956 Type *I8XX = PointerType::getUnqual(I8X);
957 Type *Params[] = {I8XX, I8XX};
958 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
959 ArrayRef<Type*>(Params, 2),
961 Constant *Callee = M->getOrInsertFunction(Name, FTy);
963 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
966 StringRef Tmp = Ptr->getName();
967 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
968 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
970 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
971 cast<Constant>(ActualPtrName), Tmp);
975 std::string SeqStr = SequenceToString(Seq);
976 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
977 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
979 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
980 cast<Constant>(ActualPtrName), SeqStr);
982 Builder.CreateCall2(Callee, PtrName, S);
985 /// Adds a source annotation to pointer and a state change annotation to Inst
986 /// referencing the source annotation and the old/new state of pointer.
987 static void GenerateARCAnnotation(unsigned InstMDId,
993 if (EnableARCAnnotations) {
994 // If we have a target identifier, make sure that we match it before
995 // emitting an annotation.
996 if(!ARCAnnotationTargetIdentifier.empty() &&
997 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
1000 // First generate the source annotation on our pointer. This will return an
1001 // MDString* if Ptr actually comes from an instruction implying we can put
1002 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
1003 // then we know that our pointer is from an Argument so we put a reference
1004 // to the argument number.
1006 // The point of this is to make it easy for the
1007 // llvm-arc-annotation-processor tool to cross reference where the source
1008 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
1009 // information via debug info for backends to use (since why would anyone
1010 // need such a thing from LLVM IR besides in non standard cases
1012 MDString *SourcePtrMDNode =
1013 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
1014 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
1019 // The actual interface for accessing the above functionality is defined via
1020 // some simple macros which are defined below. We do this so that the user does
1021 // not need to pass in what metadata id is needed resulting in cleaner code and
1022 // additionally since it provides an easy way to conditionally no-op all
1023 // annotation support in a non-debug build.
1025 /// Use this macro to annotate a sequence state change when processing
1026 /// instructions bottom up,
1027 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
1028 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
1029 ARCAnnotationProvenanceSourceMDKind, (inst), \
1030 const_cast<Value*>(ptr), (old), (new))
1031 /// Use this macro to annotate a sequence state change when processing
1032 /// instructions top down.
1033 #define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
1034 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
1035 ARCAnnotationProvenanceSourceMDKind, (inst), \
1036 const_cast<Value*>(ptr), (old), (new))
1038 #define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
1040 if (EnableARCAnnotations) { \
1041 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
1042 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
1043 Value *Ptr = const_cast<Value*>(I->first); \
1044 Sequence Seq = I->second.GetSeq(); \
1045 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
1050 #define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
1051 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
1052 Entrance, bottom_up)
1053 #define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
1054 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
1055 Terminator, bottom_up)
1056 #define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
1057 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
1059 #define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
1060 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
1061 Terminator, top_down)
1063 #else // !ARC_ANNOTATION
1064 // If annotations are off, noop.
1065 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
1066 #define ANNOTATE_TOPDOWN(inst, ptr, old, new)
1067 #define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
1068 #define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
1069 #define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
1070 #define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
1071 #endif // !ARC_ANNOTATION
1074 /// \brief The main ARC optimization pass.
1075 class ObjCARCOpt : public FunctionPass {
1077 ProvenanceAnalysis PA;
1079 // This is used to track if a pointer is stored into an alloca.
1080 DenseSet<const Value *> MultiOwnersSet;
1082 /// A flag indicating whether this optimization pass should run.
1085 /// Declarations for ObjC runtime functions, for use in creating calls to
1086 /// them. These are initialized lazily to avoid cluttering up the Module
1087 /// with unused declarations.
1089 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1090 Constant *AutoreleaseRVCallee;
1091 /// Declaration for ObjC runtime function objc_release.
1092 Constant *ReleaseCallee;
1093 /// Declaration for ObjC runtime function objc_retain.
1094 Constant *RetainCallee;
1095 /// Declaration for ObjC runtime function objc_retainBlock.
1096 Constant *RetainBlockCallee;
1097 /// Declaration for ObjC runtime function objc_autorelease.
1098 Constant *AutoreleaseCallee;
1100 /// Flags which determine whether each of the interesting runtine functions
1101 /// is in fact used in the current function.
1102 unsigned UsedInThisFunction;
1104 /// The Metadata Kind for clang.imprecise_release metadata.
1105 unsigned ImpreciseReleaseMDKind;
1107 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
1108 unsigned CopyOnEscapeMDKind;
1110 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
1111 unsigned NoObjCARCExceptionsMDKind;
1113 #ifdef ARC_ANNOTATIONS
1114 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1115 unsigned ARCAnnotationBottomUpMDKind;
1116 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1117 unsigned ARCAnnotationTopDownMDKind;
1118 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1119 unsigned ARCAnnotationProvenanceSourceMDKind;
1120 #endif // ARC_ANNOATIONS
1122 Constant *getAutoreleaseRVCallee(Module *M);
1123 Constant *getReleaseCallee(Module *M);
1124 Constant *getRetainCallee(Module *M);
1125 Constant *getRetainBlockCallee(Module *M);
1126 Constant *getAutoreleaseCallee(Module *M);
1128 bool IsRetainBlockOptimizable(const Instruction *Inst);
1130 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1131 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1132 InstructionClass &Class);
1133 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1134 InstructionClass &Class);
1135 void OptimizeIndividualCalls(Function &F);
1137 void CheckForCFGHazards(const BasicBlock *BB,
1138 DenseMap<const BasicBlock *, BBState> &BBStates,
1139 BBState &MyStates) const;
1140 bool VisitInstructionBottomUp(Instruction *Inst,
1142 MapVector<Value *, RRInfo> &Retains,
1144 bool VisitBottomUp(BasicBlock *BB,
1145 DenseMap<const BasicBlock *, BBState> &BBStates,
1146 MapVector<Value *, RRInfo> &Retains);
1147 bool VisitInstructionTopDown(Instruction *Inst,
1148 DenseMap<Value *, RRInfo> &Releases,
1150 bool VisitTopDown(BasicBlock *BB,
1151 DenseMap<const BasicBlock *, BBState> &BBStates,
1152 DenseMap<Value *, RRInfo> &Releases);
1153 bool Visit(Function &F,
1154 DenseMap<const BasicBlock *, BBState> &BBStates,
1155 MapVector<Value *, RRInfo> &Retains,
1156 DenseMap<Value *, RRInfo> &Releases);
1158 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1159 MapVector<Value *, RRInfo> &Retains,
1160 DenseMap<Value *, RRInfo> &Releases,
1161 SmallVectorImpl<Instruction *> &DeadInsts,
1164 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1165 MapVector<Value *, RRInfo> &Retains,
1166 DenseMap<Value *, RRInfo> &Releases,
1168 SmallVector<Instruction *, 4> &NewRetains,
1169 SmallVector<Instruction *, 4> &NewReleases,
1170 SmallVector<Instruction *, 8> &DeadInsts,
1171 RRInfo &RetainsToMove,
1172 RRInfo &ReleasesToMove,
1175 bool &AnyPairsCompletelyEliminated);
1177 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1178 MapVector<Value *, RRInfo> &Retains,
1179 DenseMap<Value *, RRInfo> &Releases,
1182 void OptimizeWeakCalls(Function &F);
1184 bool OptimizeSequences(Function &F);
1186 void OptimizeReturns(Function &F);
1189 void GatherStatistics(Function &F, bool AfterOptimization = false);
1192 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1193 virtual bool doInitialization(Module &M);
1194 virtual bool runOnFunction(Function &F);
1195 virtual void releaseMemory();
1199 ObjCARCOpt() : FunctionPass(ID) {
1200 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1205 char ObjCARCOpt::ID = 0;
1206 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1207 "objc-arc", "ObjC ARC optimization", false, false)
1208 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1209 INITIALIZE_PASS_END(ObjCARCOpt,
1210 "objc-arc", "ObjC ARC optimization", false, false)
1212 Pass *llvm::createObjCARCOptPass() {
1213 return new ObjCARCOpt();
1216 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1217 AU.addRequired<ObjCARCAliasAnalysis>();
1218 AU.addRequired<AliasAnalysis>();
1219 // ARC optimization doesn't currently split critical edges.
1220 AU.setPreservesCFG();
1223 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1224 // Without the magic metadata tag, we have to assume this might be an
1225 // objc_retainBlock call inserted to convert a block pointer to an id,
1226 // in which case it really is needed.
1227 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1230 // If the pointer "escapes" (not including being used in a call),
1231 // the copy may be needed.
1232 if (DoesRetainableObjPtrEscape(Inst))
1235 // Otherwise, it's not needed.
1239 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1240 if (!AutoreleaseRVCallee) {
1241 LLVMContext &C = M->getContext();
1242 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1243 Type *Params[] = { I8X };
1244 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1245 AttributeSet Attribute =
1246 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1247 Attribute::NoUnwind);
1248 AutoreleaseRVCallee =
1249 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1252 return AutoreleaseRVCallee;
1255 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1256 if (!ReleaseCallee) {
1257 LLVMContext &C = M->getContext();
1258 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1259 AttributeSet Attribute =
1260 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1261 Attribute::NoUnwind);
1263 M->getOrInsertFunction(
1265 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1268 return ReleaseCallee;
1271 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1272 if (!RetainCallee) {
1273 LLVMContext &C = M->getContext();
1274 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1275 AttributeSet Attribute =
1276 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1277 Attribute::NoUnwind);
1279 M->getOrInsertFunction(
1281 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1284 return RetainCallee;
1287 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1288 if (!RetainBlockCallee) {
1289 LLVMContext &C = M->getContext();
1290 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1291 // objc_retainBlock is not nounwind because it calls user copy constructors
1292 // which could theoretically throw.
1294 M->getOrInsertFunction(
1296 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1299 return RetainBlockCallee;
1302 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1303 if (!AutoreleaseCallee) {
1304 LLVMContext &C = M->getContext();
1305 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1306 AttributeSet Attribute =
1307 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1308 Attribute::NoUnwind);
1310 M->getOrInsertFunction(
1312 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1315 return AutoreleaseCallee;
1318 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1319 /// not a return value. Or, if it can be paired with an
1320 /// objc_autoreleaseReturnValue, delete the pair and return true.
1322 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1323 // Check for the argument being from an immediately preceding call or invoke.
1324 const Value *Arg = GetObjCArg(RetainRV);
1325 ImmutableCallSite CS(Arg);
1326 if (const Instruction *Call = CS.getInstruction()) {
1327 if (Call->getParent() == RetainRV->getParent()) {
1328 BasicBlock::const_iterator I = Call;
1330 while (IsNoopInstruction(I)) ++I;
1331 if (&*I == RetainRV)
1333 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
1334 BasicBlock *RetainRVParent = RetainRV->getParent();
1335 if (II->getNormalDest() == RetainRVParent) {
1336 BasicBlock::const_iterator I = RetainRVParent->begin();
1337 while (IsNoopInstruction(I)) ++I;
1338 if (&*I == RetainRV)
1344 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1345 // pointer. In this case, we can delete the pair.
1346 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1348 do --I; while (I != Begin && IsNoopInstruction(I));
1349 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1350 GetObjCArg(I) == Arg) {
1354 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1355 << "Erasing " << *RetainRV << "\n");
1357 EraseInstruction(I);
1358 EraseInstruction(RetainRV);
1363 // Turn it to a plain objc_retain.
1367 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
1368 "objc_retain since the operand is not a return value.\n"
1369 "Old = " << *RetainRV << "\n");
1371 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
1373 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
1378 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1379 /// used as a return value.
1381 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1382 InstructionClass &Class) {
1383 // Check for a return of the pointer value.
1384 const Value *Ptr = GetObjCArg(AutoreleaseRV);
1385 SmallVector<const Value *, 2> Users;
1386 Users.push_back(Ptr);
1388 Ptr = Users.pop_back_val();
1389 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1391 const User *I = *UI;
1392 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1394 if (isa<BitCastInst>(I))
1397 } while (!Users.empty());
1402 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
1403 "objc_autorelease since its operand is not used as a return "
1405 "Old = " << *AutoreleaseRV << "\n");
1407 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1409 setCalledFunction(getAutoreleaseCallee(F.getParent()));
1410 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
1411 Class = IC_Autorelease;
1413 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
1417 // \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1420 // Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1421 // does not escape (following the rules of block escaping), strength reduce the
1422 // objc_retainBlock to an objc_retain.
1424 // TODO: If an objc_retainBlock call is dominated period by a previous
1425 // objc_retainBlock call, strength reduce the objc_retainBlock to an
1428 ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1429 InstructionClass &Class) {
1430 assert(GetBasicInstructionClass(Inst) == Class);
1431 assert(IC_RetainBlock == Class);
1433 // If we can not optimize Inst, return false.
1434 if (!IsRetainBlockOptimizable(Inst))
1440 DEBUG(dbgs() << "Strength reduced retainBlock => retain.\n");
1441 DEBUG(dbgs() << "Old: " << *Inst << "\n");
1442 CallInst *RetainBlock = cast<CallInst>(Inst);
1443 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1444 // Remove copy_on_escape metadata.
1445 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1447 DEBUG(dbgs() << "New: " << *Inst << "\n");
1451 /// Visit each call, one at a time, and make simplifications without doing any
1452 /// additional analysis.
1453 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1454 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
1455 // Reset all the flags in preparation for recomputing them.
1456 UsedInThisFunction = 0;
1458 // Visit all objc_* calls in F.
1459 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1460 Instruction *Inst = &*I++;
1462 InstructionClass Class = GetBasicInstructionClass(Inst);
1464 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
1469 // Delete no-op casts. These function calls have special semantics, but
1470 // the semantics are entirely implemented via lowering in the front-end,
1471 // so by the time they reach the optimizer, they are just no-op calls
1472 // which return their argument.
1474 // There are gray areas here, as the ability to cast reference-counted
1475 // pointers to raw void* and back allows code to break ARC assumptions,
1476 // however these are currently considered to be unimportant.
1480 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
1481 EraseInstruction(Inst);
1484 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1487 case IC_LoadWeakRetained:
1489 case IC_DestroyWeak: {
1490 CallInst *CI = cast<CallInst>(Inst);
1491 if (IsNullOrUndef(CI->getArgOperand(0))) {
1493 Type *Ty = CI->getArgOperand(0)->getType();
1494 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1495 Constant::getNullValue(Ty),
1497 llvm::Value *NewValue = UndefValue::get(CI->getType());
1498 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1499 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1500 CI->replaceAllUsesWith(NewValue);
1501 CI->eraseFromParent();
1508 CallInst *CI = cast<CallInst>(Inst);
1509 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1510 IsNullOrUndef(CI->getArgOperand(1))) {
1512 Type *Ty = CI->getArgOperand(0)->getType();
1513 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1514 Constant::getNullValue(Ty),
1517 llvm::Value *NewValue = UndefValue::get(CI->getType());
1518 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1519 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1521 CI->replaceAllUsesWith(NewValue);
1522 CI->eraseFromParent();
1527 case IC_RetainBlock:
1528 // If we strength reduce an objc_retainBlock to an objc_retain, continue
1529 // onto the objc_retain peephole optimizations. Otherwise break.
1530 OptimizeRetainBlockCall(F, Inst, Class);
1533 if (OptimizeRetainRVCall(F, Inst))
1536 case IC_AutoreleaseRV:
1537 OptimizeAutoreleaseRVCall(F, Inst, Class);
1541 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
1542 if (IsAutorelease(Class) && Inst->use_empty()) {
1543 CallInst *Call = cast<CallInst>(Inst);
1544 const Value *Arg = Call->getArgOperand(0);
1545 Arg = FindSingleUseIdentifiedObject(Arg);
1550 // Create the declaration lazily.
1551 LLVMContext &C = Inst->getContext();
1553 CallInst::Create(getReleaseCallee(F.getParent()),
1554 Call->getArgOperand(0), "", Call);
1555 NewCall->setMetadata(ImpreciseReleaseMDKind, MDNode::get(C, None));
1557 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1558 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1559 << *NewCall << "\n");
1561 EraseInstruction(Call);
1567 // For functions which can never be passed stack arguments, add
1569 if (IsAlwaysTail(Class)) {
1571 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1572 "passed stack args: " << *Inst << "\n");
1573 cast<CallInst>(Inst)->setTailCall();
1576 // Ensure that functions that can never have a "tail" keyword due to the
1577 // semantics of ARC truly do not do so.
1578 if (IsNeverTail(Class)) {
1580 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
1582 cast<CallInst>(Inst)->setTailCall(false);
1585 // Set nounwind as needed.
1586 if (IsNoThrow(Class)) {
1588 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1590 cast<CallInst>(Inst)->setDoesNotThrow();
1593 if (!IsNoopOnNull(Class)) {
1594 UsedInThisFunction |= 1 << Class;
1598 const Value *Arg = GetObjCArg(Inst);
1600 // ARC calls with null are no-ops. Delete them.
1601 if (IsNullOrUndef(Arg)) {
1604 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1606 EraseInstruction(Inst);
1610 // Keep track of which of retain, release, autorelease, and retain_block
1611 // are actually present in this function.
1612 UsedInThisFunction |= 1 << Class;
1614 // If Arg is a PHI, and one or more incoming values to the
1615 // PHI are null, and the call is control-equivalent to the PHI, and there
1616 // are no relevant side effects between the PHI and the call, the call
1617 // could be pushed up to just those paths with non-null incoming values.
1618 // For now, don't bother splitting critical edges for this.
1619 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1620 Worklist.push_back(std::make_pair(Inst, Arg));
1622 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1626 const PHINode *PN = dyn_cast<PHINode>(Arg);
1629 // Determine if the PHI has any null operands, or any incoming
1631 bool HasNull = false;
1632 bool HasCriticalEdges = false;
1633 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1635 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1636 if (IsNullOrUndef(Incoming))
1638 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1639 .getNumSuccessors() != 1) {
1640 HasCriticalEdges = true;
1644 // If we have null operands and no critical edges, optimize.
1645 if (!HasCriticalEdges && HasNull) {
1646 SmallPtrSet<Instruction *, 4> DependingInstructions;
1647 SmallPtrSet<const BasicBlock *, 4> Visited;
1649 // Check that there is nothing that cares about the reference
1650 // count between the call and the phi.
1653 case IC_RetainBlock:
1654 // These can always be moved up.
1657 // These can't be moved across things that care about the retain
1659 FindDependencies(NeedsPositiveRetainCount, Arg,
1660 Inst->getParent(), Inst,
1661 DependingInstructions, Visited, PA);
1663 case IC_Autorelease:
1664 // These can't be moved across autorelease pool scope boundaries.
1665 FindDependencies(AutoreleasePoolBoundary, Arg,
1666 Inst->getParent(), Inst,
1667 DependingInstructions, Visited, PA);
1670 case IC_AutoreleaseRV:
1671 // Don't move these; the RV optimization depends on the autoreleaseRV
1672 // being tail called, and the retainRV being immediately after a call
1673 // (which might still happen if we get lucky with codegen layout, but
1674 // it's not worth taking the chance).
1677 llvm_unreachable("Invalid dependence flavor");
1680 if (DependingInstructions.size() == 1 &&
1681 *DependingInstructions.begin() == PN) {
1684 // Clone the call into each predecessor that has a non-null value.
1685 CallInst *CInst = cast<CallInst>(Inst);
1686 Type *ParamTy = CInst->getArgOperand(0)->getType();
1687 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1689 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1690 if (!IsNullOrUndef(Incoming)) {
1691 CallInst *Clone = cast<CallInst>(CInst->clone());
1692 Value *Op = PN->getIncomingValue(i);
1693 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1694 if (Op->getType() != ParamTy)
1695 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1696 Clone->setArgOperand(0, Op);
1697 Clone->insertBefore(InsertPos);
1699 DEBUG(dbgs() << "Cloning "
1701 "And inserting clone at " << *InsertPos << "\n");
1702 Worklist.push_back(std::make_pair(Clone, Incoming));
1705 // Erase the original call.
1706 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
1707 EraseInstruction(CInst);
1711 } while (!Worklist.empty());
1715 /// If we have a top down pointer in the S_Use state, make sure that there are
1716 /// no CFG hazards by checking the states of various bottom up pointers.
1717 static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1718 const bool SuccSRRIKnownSafe,
1720 bool &SomeSuccHasSame,
1721 bool &AllSuccsHaveSame,
1722 bool &NotAllSeqEqualButKnownSafe,
1723 bool &ShouldContinue) {
1725 case S_CanRelease: {
1726 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
1727 S.ClearSequenceProgress();
1730 S.RRI.CFGHazardAfflicted = true;
1731 ShouldContinue = true;
1735 SomeSuccHasSame = true;
1739 case S_MovableRelease:
1740 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1741 AllSuccsHaveSame = false;
1743 NotAllSeqEqualButKnownSafe = true;
1746 llvm_unreachable("bottom-up pointer in retain state!");
1748 llvm_unreachable("This should have been handled earlier.");
1752 /// If we have a Top Down pointer in the S_CanRelease state, make sure that
1753 /// there are no CFG hazards by checking the states of various bottom up
1755 static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1756 const bool SuccSRRIKnownSafe,
1758 bool &SomeSuccHasSame,
1759 bool &AllSuccsHaveSame,
1760 bool &NotAllSeqEqualButKnownSafe) {
1763 SomeSuccHasSame = true;
1767 case S_MovableRelease:
1769 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1770 AllSuccsHaveSame = false;
1772 NotAllSeqEqualButKnownSafe = true;
1775 llvm_unreachable("bottom-up pointer in retain state!");
1777 llvm_unreachable("This should have been handled earlier.");
1781 /// Check for critical edges, loop boundaries, irreducible control flow, or
1782 /// other CFG structures where moving code across the edge would result in it
1783 /// being executed more.
1785 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1786 DenseMap<const BasicBlock *, BBState> &BBStates,
1787 BBState &MyStates) const {
1788 // If any top-down local-use or possible-dec has a succ which is earlier in
1789 // the sequence, forget it.
1790 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
1791 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1792 PtrState &S = I->second;
1793 const Sequence Seq = I->second.GetSeq();
1795 // We only care about S_Retain, S_CanRelease, and S_Use.
1799 // Make sure that if extra top down states are added in the future that this
1800 // code is updated to handle it.
1801 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1802 "Unknown top down sequence state.");
1804 const Value *Arg = I->first;
1805 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1806 bool SomeSuccHasSame = false;
1807 bool AllSuccsHaveSame = true;
1808 bool NotAllSeqEqualButKnownSafe = false;
1810 succ_const_iterator SI(TI), SE(TI, false);
1812 for (; SI != SE; ++SI) {
1813 // If VisitBottomUp has pointer information for this successor, take
1814 // what we know about it.
1815 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1817 assert(BBI != BBStates.end());
1818 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1819 const Sequence SuccSSeq = SuccS.GetSeq();
1821 // If bottom up, the pointer is in an S_None state, clear the sequence
1822 // progress since the sequence in the bottom up state finished
1823 // suggesting a mismatch in between retains/releases. This is true for
1824 // all three cases that we are handling here: S_Retain, S_Use, and
1826 if (SuccSSeq == S_None) {
1827 S.ClearSequenceProgress();
1831 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1833 const bool SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
1835 // *NOTE* We do not use Seq from above here since we are allowing for
1836 // S.GetSeq() to change while we are visiting basic blocks.
1837 switch(S.GetSeq()) {
1839 bool ShouldContinue = false;
1840 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S, SomeSuccHasSame,
1841 AllSuccsHaveSame, NotAllSeqEqualButKnownSafe,
1847 case S_CanRelease: {
1848 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1849 SomeSuccHasSame, AllSuccsHaveSame,
1850 NotAllSeqEqualButKnownSafe);
1857 case S_MovableRelease:
1862 // If the state at the other end of any of the successor edges
1863 // matches the current state, require all edges to match. This
1864 // guards against loops in the middle of a sequence.
1865 if (SomeSuccHasSame && !AllSuccsHaveSame) {
1866 S.ClearSequenceProgress();
1867 } else if (NotAllSeqEqualButKnownSafe) {
1868 // If we would have cleared the state foregoing the fact that we are known
1869 // safe, stop code motion. This is because whether or not it is safe to
1870 // remove RR pairs via KnownSafe is an orthogonal concept to whether we
1871 // are allowed to perform code motion.
1872 S.RRI.CFGHazardAfflicted = true;
1878 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
1880 MapVector<Value *, RRInfo> &Retains,
1881 BBState &MyStates) {
1882 bool NestingDetected = false;
1883 InstructionClass Class = GetInstructionClass(Inst);
1884 const Value *Arg = 0;
1886 DEBUG(dbgs() << "Class: " << Class << "\n");
1890 Arg = GetObjCArg(Inst);
1892 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1894 // If we see two releases in a row on the same pointer. If so, make
1895 // a note, and we'll cicle back to revisit it after we've
1896 // hopefully eliminated the second release, which may allow us to
1897 // eliminate the first release too.
1898 // Theoretically we could implement removal of nested retain+release
1899 // pairs by making PtrState hold a stack of states, but this is
1900 // simple and avoids adding overhead for the non-nested case.
1901 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
1902 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
1903 NestingDetected = true;
1906 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
1907 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1908 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1909 S.ResetSequenceProgress(NewSeq);
1910 S.RRI.ReleaseMetadata = ReleaseMetadata;
1911 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
1912 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1913 S.RRI.Calls.insert(Inst);
1914 S.SetKnownPositiveRefCount();
1917 case IC_RetainBlock:
1918 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1919 // objc_retainBlocks to objc_retains. Thus at this point any
1920 // objc_retainBlocks that we see are not optimizable.
1924 Arg = GetObjCArg(Inst);
1926 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1927 S.SetKnownPositiveRefCount();
1929 Sequence OldSeq = S.GetSeq();
1933 case S_MovableRelease:
1935 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1936 // imprecise release, clear our reverse insertion points.
1937 if (OldSeq != S_Use || S.RRI.IsTrackingImpreciseReleases())
1938 S.RRI.ReverseInsertPts.clear();
1941 // Don't do retain+release tracking for IC_RetainRV, because it's
1942 // better to let it remain as the first instruction after a call.
1943 if (Class != IC_RetainRV)
1944 Retains[Inst] = S.RRI;
1945 S.ClearSequenceProgress();
1950 llvm_unreachable("bottom-up pointer in retain state!");
1952 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
1953 // A retain moving bottom up can be a use.
1956 case IC_AutoreleasepoolPop:
1957 // Conservatively, clear MyStates for all known pointers.
1958 MyStates.clearBottomUpPointers();
1959 return NestingDetected;
1960 case IC_AutoreleasepoolPush:
1962 // These are irrelevant.
1963 return NestingDetected;
1965 // If we have a store into an alloca of a pointer we are tracking, the
1966 // pointer has multiple owners implying that we must be more conservative.
1968 // This comes up in the context of a pointer being ``KnownSafe''. In the
1969 // presense of a block being initialized, the frontend will emit the
1970 // objc_retain on the original pointer and the release on the pointer loaded
1971 // from the alloca. The optimizer will through the provenance analysis
1972 // realize that the two are related, but since we only require KnownSafe in
1973 // one direction, will match the inner retain on the original pointer with
1974 // the guard release on the original pointer. This is fixed by ensuring that
1975 // in the presense of allocas we only unconditionally remove pointers if
1976 // both our retain and our release are KnownSafe.
1977 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1978 if (AreAnyUnderlyingObjectsAnAlloca(SI->getPointerOperand())) {
1979 BBState::ptr_iterator I = MyStates.findPtrBottomUpState(
1980 StripPointerCastsAndObjCCalls(SI->getValueOperand()));
1981 if (I != MyStates.bottom_up_ptr_end())
1982 MultiOwnersSet.insert(I->first);
1990 // Consider any other possible effects of this instruction on each
1991 // pointer being tracked.
1992 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1993 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1994 const Value *Ptr = MI->first;
1996 continue; // Handled above.
1997 PtrState &S = MI->second;
1998 Sequence Seq = S.GetSeq();
2000 // Check for possible releases.
2001 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2002 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
2004 S.ClearKnownPositiveRefCount();
2007 S.SetSeq(S_CanRelease);
2008 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
2012 case S_MovableRelease:
2017 llvm_unreachable("bottom-up pointer in retain state!");
2021 // Check for possible direct uses.
2024 case S_MovableRelease:
2025 if (CanUse(Inst, Ptr, PA, Class)) {
2026 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2028 assert(S.RRI.ReverseInsertPts.empty());
2029 // If this is an invoke instruction, we're scanning it as part of
2030 // one of its successor blocks, since we can't insert code after it
2031 // in its own block, and we don't want to split critical edges.
2032 if (isa<InvokeInst>(Inst))
2033 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2035 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2037 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2038 } else if (Seq == S_Release && IsUser(Class)) {
2039 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
2041 // Non-movable releases depend on any possible objc pointer use.
2043 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
2044 assert(S.RRI.ReverseInsertPts.empty());
2045 // As above; handle invoke specially.
2046 if (isa<InvokeInst>(Inst))
2047 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2049 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2053 if (CanUse(Inst, Ptr, PA, Class)) {
2054 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
2057 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
2065 llvm_unreachable("bottom-up pointer in retain state!");
2069 return NestingDetected;
2073 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2074 DenseMap<const BasicBlock *, BBState> &BBStates,
2075 MapVector<Value *, RRInfo> &Retains) {
2077 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
2079 bool NestingDetected = false;
2080 BBState &MyStates = BBStates[BB];
2082 // Merge the states from each successor to compute the initial state
2083 // for the current block.
2084 BBState::edge_iterator SI(MyStates.succ_begin()),
2085 SE(MyStates.succ_end());
2087 const BasicBlock *Succ = *SI;
2088 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2089 assert(I != BBStates.end());
2090 MyStates.InitFromSucc(I->second);
2092 for (; SI != SE; ++SI) {
2094 I = BBStates.find(Succ);
2095 assert(I != BBStates.end());
2096 MyStates.MergeSucc(I->second);
2100 // If ARC Annotations are enabled, output the current state of pointers at the
2101 // bottom of the basic block.
2102 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
2104 // Visit all the instructions, bottom-up.
2105 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2106 Instruction *Inst = llvm::prior(I);
2108 // Invoke instructions are visited as part of their successors (below).
2109 if (isa<InvokeInst>(Inst))
2112 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
2114 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2117 // If there's a predecessor with an invoke, visit the invoke as if it were
2118 // part of this block, since we can't insert code after an invoke in its own
2119 // block, and we don't want to split critical edges.
2120 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2121 PE(MyStates.pred_end()); PI != PE; ++PI) {
2122 BasicBlock *Pred = *PI;
2123 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2124 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
2127 // If ARC Annotations are enabled, output the current state of pointers at the
2128 // top of the basic block.
2129 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
2131 return NestingDetected;
2135 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2136 DenseMap<Value *, RRInfo> &Releases,
2137 BBState &MyStates) {
2138 bool NestingDetected = false;
2139 InstructionClass Class = GetInstructionClass(Inst);
2140 const Value *Arg = 0;
2143 case IC_RetainBlock:
2144 // In OptimizeIndividualCalls, we have strength reduced all optimizable
2145 // objc_retainBlocks to objc_retains. Thus at this point any
2146 // objc_retainBlocks that we see are not optimizable.
2150 Arg = GetObjCArg(Inst);
2152 PtrState &S = MyStates.getPtrTopDownState(Arg);
2154 // Don't do retain+release tracking for IC_RetainRV, because it's
2155 // better to let it remain as the first instruction after a call.
2156 if (Class != IC_RetainRV) {
2157 // If we see two retains in a row on the same pointer. If so, make
2158 // a note, and we'll cicle back to revisit it after we've
2159 // hopefully eliminated the second retain, which may allow us to
2160 // eliminate the first retain too.
2161 // Theoretically we could implement removal of nested retain+release
2162 // pairs by making PtrState hold a stack of states, but this is
2163 // simple and avoids adding overhead for the non-nested case.
2164 if (S.GetSeq() == S_Retain)
2165 NestingDetected = true;
2167 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
2168 S.ResetSequenceProgress(S_Retain);
2169 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
2170 S.RRI.Calls.insert(Inst);
2173 S.SetKnownPositiveRefCount();
2175 // A retain can be a potential use; procede to the generic checking
2180 Arg = GetObjCArg(Inst);
2182 PtrState &S = MyStates.getPtrTopDownState(Arg);
2183 S.ClearKnownPositiveRefCount();
2185 Sequence OldSeq = S.GetSeq();
2187 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2192 if (OldSeq == S_Retain || ReleaseMetadata != 0)
2193 S.RRI.ReverseInsertPts.clear();
2196 S.RRI.ReleaseMetadata = ReleaseMetadata;
2197 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2198 Releases[Inst] = S.RRI;
2199 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
2200 S.ClearSequenceProgress();
2206 case S_MovableRelease:
2207 llvm_unreachable("top-down pointer in release state!");
2211 case IC_AutoreleasepoolPop:
2212 // Conservatively, clear MyStates for all known pointers.
2213 MyStates.clearTopDownPointers();
2214 return NestingDetected;
2215 case IC_AutoreleasepoolPush:
2217 // These are irrelevant.
2218 return NestingDetected;
2223 // Consider any other possible effects of this instruction on each
2224 // pointer being tracked.
2225 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2226 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2227 const Value *Ptr = MI->first;
2229 continue; // Handled above.
2230 PtrState &S = MI->second;
2231 Sequence Seq = S.GetSeq();
2233 // Check for possible releases.
2234 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2235 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
2237 S.ClearKnownPositiveRefCount();
2240 S.SetSeq(S_CanRelease);
2241 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
2242 assert(S.RRI.ReverseInsertPts.empty());
2243 S.RRI.ReverseInsertPts.insert(Inst);
2245 // One call can't cause a transition from S_Retain to S_CanRelease
2246 // and S_CanRelease to S_Use. If we've made the first transition,
2255 case S_MovableRelease:
2256 llvm_unreachable("top-down pointer in release state!");
2260 // Check for possible direct uses.
2263 if (CanUse(Inst, Ptr, PA, Class)) {
2264 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2267 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2276 case S_MovableRelease:
2277 llvm_unreachable("top-down pointer in release state!");
2281 return NestingDetected;
2285 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2286 DenseMap<const BasicBlock *, BBState> &BBStates,
2287 DenseMap<Value *, RRInfo> &Releases) {
2288 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
2289 bool NestingDetected = false;
2290 BBState &MyStates = BBStates[BB];
2292 // Merge the states from each predecessor to compute the initial state
2293 // for the current block.
2294 BBState::edge_iterator PI(MyStates.pred_begin()),
2295 PE(MyStates.pred_end());
2297 const BasicBlock *Pred = *PI;
2298 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2299 assert(I != BBStates.end());
2300 MyStates.InitFromPred(I->second);
2302 for (; PI != PE; ++PI) {
2304 I = BBStates.find(Pred);
2305 assert(I != BBStates.end());
2306 MyStates.MergePred(I->second);
2310 // If ARC Annotations are enabled, output the current state of pointers at the
2311 // top of the basic block.
2312 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
2314 // Visit all the instructions, top-down.
2315 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2316 Instruction *Inst = I;
2318 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
2320 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
2323 // If ARC Annotations are enabled, output the current state of pointers at the
2324 // bottom of the basic block.
2325 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
2327 #ifdef ARC_ANNOTATIONS
2328 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
2330 CheckForCFGHazards(BB, BBStates, MyStates);
2331 return NestingDetected;
2335 ComputePostOrders(Function &F,
2336 SmallVectorImpl<BasicBlock *> &PostOrder,
2337 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2338 unsigned NoObjCARCExceptionsMDKind,
2339 DenseMap<const BasicBlock *, BBState> &BBStates) {
2340 /// The visited set, for doing DFS walks.
2341 SmallPtrSet<BasicBlock *, 16> Visited;
2343 // Do DFS, computing the PostOrder.
2344 SmallPtrSet<BasicBlock *, 16> OnStack;
2345 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2347 // Functions always have exactly one entry block, and we don't have
2348 // any other block that we treat like an entry block.
2349 BasicBlock *EntryBB = &F.getEntryBlock();
2350 BBState &MyStates = BBStates[EntryBB];
2351 MyStates.SetAsEntry();
2352 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2353 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
2354 Visited.insert(EntryBB);
2355 OnStack.insert(EntryBB);
2358 BasicBlock *CurrBB = SuccStack.back().first;
2359 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2360 succ_iterator SE(TI, false);
2362 while (SuccStack.back().second != SE) {
2363 BasicBlock *SuccBB = *SuccStack.back().second++;
2364 if (Visited.insert(SuccBB)) {
2365 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2366 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
2367 BBStates[CurrBB].addSucc(SuccBB);
2368 BBState &SuccStates = BBStates[SuccBB];
2369 SuccStates.addPred(CurrBB);
2370 OnStack.insert(SuccBB);
2374 if (!OnStack.count(SuccBB)) {
2375 BBStates[CurrBB].addSucc(SuccBB);
2376 BBStates[SuccBB].addPred(CurrBB);
2379 OnStack.erase(CurrBB);
2380 PostOrder.push_back(CurrBB);
2381 SuccStack.pop_back();
2382 } while (!SuccStack.empty());
2386 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2387 // Functions may have many exits, and there also blocks which we treat
2388 // as exits due to ignored edges.
2389 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2390 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2391 BasicBlock *ExitBB = I;
2392 BBState &MyStates = BBStates[ExitBB];
2393 if (!MyStates.isExit())
2396 MyStates.SetAsExit();
2398 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
2399 Visited.insert(ExitBB);
2400 while (!PredStack.empty()) {
2401 reverse_dfs_next_succ:
2402 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2403 while (PredStack.back().second != PE) {
2404 BasicBlock *BB = *PredStack.back().second++;
2405 if (Visited.insert(BB)) {
2406 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
2407 goto reverse_dfs_next_succ;
2410 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2415 // Visit the function both top-down and bottom-up.
2417 ObjCARCOpt::Visit(Function &F,
2418 DenseMap<const BasicBlock *, BBState> &BBStates,
2419 MapVector<Value *, RRInfo> &Retains,
2420 DenseMap<Value *, RRInfo> &Releases) {
2422 // Use reverse-postorder traversals, because we magically know that loops
2423 // will be well behaved, i.e. they won't repeatedly call retain on a single
2424 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2425 // class here because we want the reverse-CFG postorder to consider each
2426 // function exit point, and we want to ignore selected cycle edges.
2427 SmallVector<BasicBlock *, 16> PostOrder;
2428 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2429 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2430 NoObjCARCExceptionsMDKind,
2433 // Use reverse-postorder on the reverse CFG for bottom-up.
2434 bool BottomUpNestingDetected = false;
2435 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2436 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2438 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
2440 // Use reverse-postorder for top-down.
2441 bool TopDownNestingDetected = false;
2442 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2443 PostOrder.rbegin(), E = PostOrder.rend();
2445 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
2447 return TopDownNestingDetected && BottomUpNestingDetected;
2450 /// Move the calls in RetainsToMove and ReleasesToMove.
2451 void ObjCARCOpt::MoveCalls(Value *Arg,
2452 RRInfo &RetainsToMove,
2453 RRInfo &ReleasesToMove,
2454 MapVector<Value *, RRInfo> &Retains,
2455 DenseMap<Value *, RRInfo> &Releases,
2456 SmallVectorImpl<Instruction *> &DeadInsts,
2458 Type *ArgTy = Arg->getType();
2459 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2461 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
2463 // Insert the new retain and release calls.
2464 for (SmallPtrSet<Instruction *, 2>::const_iterator
2465 PI = ReleasesToMove.ReverseInsertPts.begin(),
2466 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2467 Instruction *InsertPt = *PI;
2468 Value *MyArg = ArgTy == ParamTy ? Arg :
2469 new BitCastInst(Arg, ParamTy, "", InsertPt);
2471 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
2472 Call->setDoesNotThrow();
2473 Call->setTailCall();
2475 DEBUG(dbgs() << "Inserting new Retain: " << *Call << "\n"
2476 "At insertion point: " << *InsertPt << "\n");
2478 for (SmallPtrSet<Instruction *, 2>::const_iterator
2479 PI = RetainsToMove.ReverseInsertPts.begin(),
2480 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2481 Instruction *InsertPt = *PI;
2482 Value *MyArg = ArgTy == ParamTy ? Arg :
2483 new BitCastInst(Arg, ParamTy, "", InsertPt);
2484 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2486 // Attach a clang.imprecise_release metadata tag, if appropriate.
2487 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2488 Call->setMetadata(ImpreciseReleaseMDKind, M);
2489 Call->setDoesNotThrow();
2490 if (ReleasesToMove.IsTailCallRelease)
2491 Call->setTailCall();
2493 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2494 "At insertion point: " << *InsertPt << "\n");
2497 // Delete the original retain and release calls.
2498 for (SmallPtrSet<Instruction *, 2>::const_iterator
2499 AI = RetainsToMove.Calls.begin(),
2500 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2501 Instruction *OrigRetain = *AI;
2502 Retains.blot(OrigRetain);
2503 DeadInsts.push_back(OrigRetain);
2504 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
2506 for (SmallPtrSet<Instruction *, 2>::const_iterator
2507 AI = ReleasesToMove.Calls.begin(),
2508 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2509 Instruction *OrigRelease = *AI;
2510 Releases.erase(OrigRelease);
2511 DeadInsts.push_back(OrigRelease);
2512 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
2518 ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2520 MapVector<Value *, RRInfo> &Retains,
2521 DenseMap<Value *, RRInfo> &Releases,
2523 SmallVector<Instruction *, 4> &NewRetains,
2524 SmallVector<Instruction *, 4> &NewReleases,
2525 SmallVector<Instruction *, 8> &DeadInsts,
2526 RRInfo &RetainsToMove,
2527 RRInfo &ReleasesToMove,
2530 bool &AnyPairsCompletelyEliminated) {
2531 // If a pair happens in a region where it is known that the reference count
2532 // is already incremented, we can similarly ignore possible decrements unless
2533 // we are dealing with a retainable object with multiple provenance sources.
2534 bool KnownSafeTD = true, KnownSafeBU = true;
2535 bool MultipleOwners = false;
2536 bool CFGHazardAfflicted = false;
2538 // Connect the dots between the top-down-collected RetainsToMove and
2539 // bottom-up-collected ReleasesToMove to form sets of related calls.
2540 // This is an iterative process so that we connect multiple releases
2541 // to multiple retains if needed.
2542 unsigned OldDelta = 0;
2543 unsigned NewDelta = 0;
2544 unsigned OldCount = 0;
2545 unsigned NewCount = 0;
2546 bool FirstRelease = true;
2548 for (SmallVectorImpl<Instruction *>::const_iterator
2549 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2550 Instruction *NewRetain = *NI;
2551 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2552 assert(It != Retains.end());
2553 const RRInfo &NewRetainRRI = It->second;
2554 KnownSafeTD &= NewRetainRRI.KnownSafe;
2556 MultipleOwners || MultiOwnersSet.count(GetObjCArg(NewRetain));
2557 for (SmallPtrSet<Instruction *, 2>::const_iterator
2558 LI = NewRetainRRI.Calls.begin(),
2559 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2560 Instruction *NewRetainRelease = *LI;
2561 DenseMap<Value *, RRInfo>::const_iterator Jt =
2562 Releases.find(NewRetainRelease);
2563 if (Jt == Releases.end())
2565 const RRInfo &NewRetainReleaseRRI = Jt->second;
2566 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2567 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2569 // If we overflow when we compute the path count, don't remove/move
2571 const BBState &NRRBBState = BBStates[NewRetainRelease->getParent()];
2573 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2575 OldDelta -= PathCount;
2577 // Merge the ReleaseMetadata and IsTailCallRelease values.
2579 ReleasesToMove.ReleaseMetadata =
2580 NewRetainReleaseRRI.ReleaseMetadata;
2581 ReleasesToMove.IsTailCallRelease =
2582 NewRetainReleaseRRI.IsTailCallRelease;
2583 FirstRelease = false;
2585 if (ReleasesToMove.ReleaseMetadata !=
2586 NewRetainReleaseRRI.ReleaseMetadata)
2587 ReleasesToMove.ReleaseMetadata = 0;
2588 if (ReleasesToMove.IsTailCallRelease !=
2589 NewRetainReleaseRRI.IsTailCallRelease)
2590 ReleasesToMove.IsTailCallRelease = false;
2593 // Collect the optimal insertion points.
2595 for (SmallPtrSet<Instruction *, 2>::const_iterator
2596 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2597 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2599 Instruction *RIP = *RI;
2600 if (ReleasesToMove.ReverseInsertPts.insert(RIP)) {
2601 // If we overflow when we compute the path count, don't
2602 // remove/move anything.
2603 const BBState &RIPBBState = BBStates[RIP->getParent()];
2604 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2606 NewDelta -= PathCount;
2609 NewReleases.push_back(NewRetainRelease);
2614 if (NewReleases.empty()) break;
2616 // Back the other way.
2617 for (SmallVectorImpl<Instruction *>::const_iterator
2618 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2619 Instruction *NewRelease = *NI;
2620 DenseMap<Value *, RRInfo>::const_iterator It =
2621 Releases.find(NewRelease);
2622 assert(It != Releases.end());
2623 const RRInfo &NewReleaseRRI = It->second;
2624 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2625 CFGHazardAfflicted |= NewReleaseRRI.CFGHazardAfflicted;
2626 for (SmallPtrSet<Instruction *, 2>::const_iterator
2627 LI = NewReleaseRRI.Calls.begin(),
2628 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2629 Instruction *NewReleaseRetain = *LI;
2630 MapVector<Value *, RRInfo>::const_iterator Jt =
2631 Retains.find(NewReleaseRetain);
2632 if (Jt == Retains.end())
2634 const RRInfo &NewReleaseRetainRRI = Jt->second;
2635 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2636 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2638 // If we overflow when we compute the path count, don't remove/move
2640 const BBState &NRRBBState = BBStates[NewReleaseRetain->getParent()];
2642 if (NRRBBState.GetAllPathCountWithOverflow(PathCount))
2644 OldDelta += PathCount;
2645 OldCount += PathCount;
2647 // Collect the optimal insertion points.
2649 for (SmallPtrSet<Instruction *, 2>::const_iterator
2650 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2651 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2653 Instruction *RIP = *RI;
2654 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2655 // If we overflow when we compute the path count, don't
2656 // remove/move anything.
2657 const BBState &RIPBBState = BBStates[RIP->getParent()];
2658 if (RIPBBState.GetAllPathCountWithOverflow(PathCount))
2660 NewDelta += PathCount;
2661 NewCount += PathCount;
2664 NewRetains.push_back(NewReleaseRetain);
2668 NewReleases.clear();
2669 if (NewRetains.empty()) break;
2672 // If the pointer is known incremented in 1 direction and we do not have
2673 // MultipleOwners, we can safely remove the retain/releases. Otherwise we need
2674 // to be known safe in both directions.
2675 bool UnconditionallySafe = (KnownSafeTD && KnownSafeBU) ||
2676 ((KnownSafeTD || KnownSafeBU) && !MultipleOwners);
2677 if (UnconditionallySafe) {
2678 RetainsToMove.ReverseInsertPts.clear();
2679 ReleasesToMove.ReverseInsertPts.clear();
2682 // Determine whether the new insertion points we computed preserve the
2683 // balance of retain and release calls through the program.
2684 // TODO: If the fully aggressive solution isn't valid, try to find a
2685 // less aggressive solution which is.
2689 // At this point, we are not going to remove any RR pairs, but we still are
2690 // able to move RR pairs. If one of our pointers is afflicted with
2691 // CFGHazards, we cannot perform such code motion so exit early.
2692 const bool WillPerformCodeMotion = RetainsToMove.ReverseInsertPts.size() ||
2693 ReleasesToMove.ReverseInsertPts.size();
2694 if (CFGHazardAfflicted && WillPerformCodeMotion)
2698 // Determine whether the original call points are balanced in the retain and
2699 // release calls through the program. If not, conservatively don't touch
2701 // TODO: It's theoretically possible to do code motion in this case, as
2702 // long as the existing imbalances are maintained.
2706 #ifdef ARC_ANNOTATIONS
2707 // Do not move calls if ARC annotations are requested.
2708 if (EnableARCAnnotations)
2710 #endif // ARC_ANNOTATIONS
2713 assert(OldCount != 0 && "Unreachable code?");
2714 NumRRs += OldCount - NewCount;
2715 // Set to true if we completely removed any RR pairs.
2716 AnyPairsCompletelyEliminated = NewCount == 0;
2718 // We can move calls!
2722 /// Identify pairings between the retains and releases, and delete and/or move
2725 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2727 MapVector<Value *, RRInfo> &Retains,
2728 DenseMap<Value *, RRInfo> &Releases,
2730 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2732 bool AnyPairsCompletelyEliminated = false;
2733 RRInfo RetainsToMove;
2734 RRInfo ReleasesToMove;
2735 SmallVector<Instruction *, 4> NewRetains;
2736 SmallVector<Instruction *, 4> NewReleases;
2737 SmallVector<Instruction *, 8> DeadInsts;
2739 // Visit each retain.
2740 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2741 E = Retains.end(); I != E; ++I) {
2742 Value *V = I->first;
2743 if (!V) continue; // blotted
2745 Instruction *Retain = cast<Instruction>(V);
2747 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
2749 Value *Arg = GetObjCArg(Retain);
2751 // If the object being released is in static or stack storage, we know it's
2752 // not being managed by ObjC reference counting, so we can delete pairs
2753 // regardless of what possible decrements or uses lie between them.
2754 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
2756 // A constant pointer can't be pointing to an object on the heap. It may
2757 // be reference-counted, but it won't be deleted.
2758 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2759 if (const GlobalVariable *GV =
2760 dyn_cast<GlobalVariable>(
2761 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2762 if (GV->isConstant())
2765 // Connect the dots between the top-down-collected RetainsToMove and
2766 // bottom-up-collected ReleasesToMove to form sets of related calls.
2767 NewRetains.push_back(Retain);
2768 bool PerformMoveCalls =
2769 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2770 NewReleases, DeadInsts, RetainsToMove,
2771 ReleasesToMove, Arg, KnownSafe,
2772 AnyPairsCompletelyEliminated);
2774 if (PerformMoveCalls) {
2775 // Ok, everything checks out and we're all set. Let's move/delete some
2777 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2778 Retains, Releases, DeadInsts, M);
2781 // Clean up state for next retain.
2782 NewReleases.clear();
2784 RetainsToMove.clear();
2785 ReleasesToMove.clear();
2788 // Now that we're done moving everything, we can delete the newly dead
2789 // instructions, as we no longer need them as insert points.
2790 while (!DeadInsts.empty())
2791 EraseInstruction(DeadInsts.pop_back_val());
2793 return AnyPairsCompletelyEliminated;
2796 /// Weak pointer optimizations.
2797 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2798 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
2800 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2801 // itself because it uses AliasAnalysis and we need to do provenance
2803 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2804 Instruction *Inst = &*I++;
2806 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
2808 InstructionClass Class = GetBasicInstructionClass(Inst);
2809 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2812 // Delete objc_loadWeak calls with no users.
2813 if (Class == IC_LoadWeak && Inst->use_empty()) {
2814 Inst->eraseFromParent();
2818 // TODO: For now, just look for an earlier available version of this value
2819 // within the same block. Theoretically, we could do memdep-style non-local
2820 // analysis too, but that would want caching. A better approach would be to
2821 // use the technique that EarlyCSE uses.
2822 inst_iterator Current = llvm::prior(I);
2823 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2824 for (BasicBlock::iterator B = CurrentBB->begin(),
2825 J = Current.getInstructionIterator();
2827 Instruction *EarlierInst = &*llvm::prior(J);
2828 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2829 switch (EarlierClass) {
2831 case IC_LoadWeakRetained: {
2832 // If this is loading from the same pointer, replace this load's value
2834 CallInst *Call = cast<CallInst>(Inst);
2835 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2836 Value *Arg = Call->getArgOperand(0);
2837 Value *EarlierArg = EarlierCall->getArgOperand(0);
2838 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2839 case AliasAnalysis::MustAlias:
2841 // If the load has a builtin retain, insert a plain retain for it.
2842 if (Class == IC_LoadWeakRetained) {
2844 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2848 // Zap the fully redundant load.
2849 Call->replaceAllUsesWith(EarlierCall);
2850 Call->eraseFromParent();
2852 case AliasAnalysis::MayAlias:
2853 case AliasAnalysis::PartialAlias:
2855 case AliasAnalysis::NoAlias:
2862 // If this is storing to the same pointer and has the same size etc.
2863 // replace this load's value with the stored value.
2864 CallInst *Call = cast<CallInst>(Inst);
2865 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2866 Value *Arg = Call->getArgOperand(0);
2867 Value *EarlierArg = EarlierCall->getArgOperand(0);
2868 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2869 case AliasAnalysis::MustAlias:
2871 // If the load has a builtin retain, insert a plain retain for it.
2872 if (Class == IC_LoadWeakRetained) {
2874 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2878 // Zap the fully redundant load.
2879 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2880 Call->eraseFromParent();
2882 case AliasAnalysis::MayAlias:
2883 case AliasAnalysis::PartialAlias:
2885 case AliasAnalysis::NoAlias:
2892 // TOOD: Grab the copied value.
2894 case IC_AutoreleasepoolPush:
2896 case IC_IntrinsicUser:
2898 // Weak pointers are only modified through the weak entry points
2899 // (and arbitrary calls, which could call the weak entry points).
2902 // Anything else could modify the weak pointer.
2909 // Then, for each destroyWeak with an alloca operand, check to see if
2910 // the alloca and all its users can be zapped.
2911 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2912 Instruction *Inst = &*I++;
2913 InstructionClass Class = GetBasicInstructionClass(Inst);
2914 if (Class != IC_DestroyWeak)
2917 CallInst *Call = cast<CallInst>(Inst);
2918 Value *Arg = Call->getArgOperand(0);
2919 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2920 for (Value::use_iterator UI = Alloca->use_begin(),
2921 UE = Alloca->use_end(); UI != UE; ++UI) {
2922 const Instruction *UserInst = cast<Instruction>(*UI);
2923 switch (GetBasicInstructionClass(UserInst)) {
2926 case IC_DestroyWeak:
2933 for (Value::use_iterator UI = Alloca->use_begin(),
2934 UE = Alloca->use_end(); UI != UE; ) {
2935 CallInst *UserInst = cast<CallInst>(*UI++);
2936 switch (GetBasicInstructionClass(UserInst)) {
2939 // These functions return their second argument.
2940 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2942 case IC_DestroyWeak:
2946 llvm_unreachable("alloca really is used!");
2948 UserInst->eraseFromParent();
2950 Alloca->eraseFromParent();
2956 /// Identify program paths which execute sequences of retains and releases which
2957 /// can be eliminated.
2958 bool ObjCARCOpt::OptimizeSequences(Function &F) {
2959 // Releases, Retains - These are used to store the results of the main flow
2960 // analysis. These use Value* as the key instead of Instruction* so that the
2961 // map stays valid when we get around to rewriting code and calls get
2962 // replaced by arguments.
2963 DenseMap<Value *, RRInfo> Releases;
2964 MapVector<Value *, RRInfo> Retains;
2966 // This is used during the traversal of the function to track the
2967 // states for each identified object at each block.
2968 DenseMap<const BasicBlock *, BBState> BBStates;
2970 // Analyze the CFG of the function, and all instructions.
2971 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2974 bool AnyPairsCompletelyEliminated = PerformCodePlacement(BBStates, Retains,
2979 MultiOwnersSet.clear();
2981 return AnyPairsCompletelyEliminated && NestingDetected;
2984 /// Check if there is a dependent call earlier that does not have anything in
2985 /// between the Retain and the call that can affect the reference count of their
2986 /// shared pointer argument. Note that Retain need not be in BB.
2988 HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2989 SmallPtrSet<Instruction *, 4> &DepInsts,
2990 SmallPtrSet<const BasicBlock *, 4> &Visited,
2991 ProvenanceAnalysis &PA) {
2992 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2993 DepInsts, Visited, PA);
2994 if (DepInsts.size() != 1)
2998 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3000 // Check that the pointer is the return value of the call.
3001 if (!Call || Arg != Call)
3004 // Check that the call is a regular call.
3005 InstructionClass Class = GetBasicInstructionClass(Call);
3006 if (Class != IC_CallOrUser && Class != IC_Call)
3012 /// Find a dependent retain that precedes the given autorelease for which there
3013 /// is nothing in between the two instructions that can affect the ref count of
3016 FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
3017 Instruction *Autorelease,
3018 SmallPtrSet<Instruction *, 4> &DepInsts,
3019 SmallPtrSet<const BasicBlock *, 4> &Visited,
3020 ProvenanceAnalysis &PA) {
3021 FindDependencies(CanChangeRetainCount, Arg,
3022 BB, Autorelease, DepInsts, Visited, PA);
3023 if (DepInsts.size() != 1)
3027 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3029 // Check that we found a retain with the same argument.
3031 !IsRetain(GetBasicInstructionClass(Retain)) ||
3032 GetObjCArg(Retain) != Arg) {
3039 /// Look for an ``autorelease'' instruction dependent on Arg such that there are
3040 /// no instructions dependent on Arg that need a positive ref count in between
3041 /// the autorelease and the ret.
3043 FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
3045 SmallPtrSet<Instruction *, 4> &DepInsts,
3046 SmallPtrSet<const BasicBlock *, 4> &V,
3047 ProvenanceAnalysis &PA) {
3048 FindDependencies(NeedsPositiveRetainCount, Arg,
3049 BB, Ret, DepInsts, V, PA);
3050 if (DepInsts.size() != 1)
3053 CallInst *Autorelease =
3054 dyn_cast_or_null<CallInst>(*DepInsts.begin());
3057 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3058 if (!IsAutorelease(AutoreleaseClass))
3060 if (GetObjCArg(Autorelease) != Arg)
3066 /// Look for this pattern:
3068 /// %call = call i8* @something(...)
3069 /// %2 = call i8* @objc_retain(i8* %call)
3070 /// %3 = call i8* @objc_autorelease(i8* %2)
3073 /// And delete the retain and autorelease.
3074 void ObjCARCOpt::OptimizeReturns(Function &F) {
3075 if (!F.getReturnType()->isPointerTy())
3078 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
3080 SmallPtrSet<Instruction *, 4> DependingInstructions;
3081 SmallPtrSet<const BasicBlock *, 4> Visited;
3082 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3083 BasicBlock *BB = FI;
3084 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3086 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
3091 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3093 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
3094 // dependent on Arg such that there are no instructions dependent on Arg
3095 // that need a positive ref count in between the autorelease and Ret.
3096 CallInst *Autorelease =
3097 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
3098 DependingInstructions, Visited,
3100 DependingInstructions.clear();
3107 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
3108 DependingInstructions, Visited, PA);
3109 DependingInstructions.clear();
3115 // Check that there is nothing that can affect the reference count
3116 // between the retain and the call. Note that Retain need not be in BB.
3117 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
3118 DependingInstructions,
3120 DependingInstructions.clear();
3123 if (!HasSafePathToCall)
3126 // If so, we can zap the retain and autorelease.
3129 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
3130 << *Autorelease << "\n");
3131 EraseInstruction(Retain);
3132 EraseInstruction(Autorelease);
3138 ObjCARCOpt::GatherStatistics(Function &F, bool AfterOptimization) {
3139 llvm::Statistic &NumRetains =
3140 AfterOptimization? NumRetainsAfterOpt : NumRetainsBeforeOpt;
3141 llvm::Statistic &NumReleases =
3142 AfterOptimization? NumReleasesAfterOpt : NumReleasesBeforeOpt;
3144 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3145 Instruction *Inst = &*I++;
3146 switch (GetBasicInstructionClass(Inst)) {
3160 bool ObjCARCOpt::doInitialization(Module &M) {
3164 // If nothing in the Module uses ARC, don't do anything.
3165 Run = ModuleHasARC(M);
3169 // Identify the imprecise release metadata kind.
3170 ImpreciseReleaseMDKind =
3171 M.getContext().getMDKindID("clang.imprecise_release");
3172 CopyOnEscapeMDKind =
3173 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3174 NoObjCARCExceptionsMDKind =
3175 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3176 #ifdef ARC_ANNOTATIONS
3177 ARCAnnotationBottomUpMDKind =
3178 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3179 ARCAnnotationTopDownMDKind =
3180 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3181 ARCAnnotationProvenanceSourceMDKind =
3182 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3183 #endif // ARC_ANNOTATIONS
3185 // Intuitively, objc_retain and others are nocapture, however in practice
3186 // they are not, because they return their argument value. And objc_release
3187 // calls finalizers which can have arbitrary side effects.
3189 // These are initialized lazily.
3190 AutoreleaseRVCallee = 0;
3193 RetainBlockCallee = 0;
3194 AutoreleaseCallee = 0;
3199 bool ObjCARCOpt::runOnFunction(Function &F) {
3203 // If nothing in the Module uses ARC, don't do anything.
3209 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3212 PA.setAA(&getAnalysis<AliasAnalysis>());
3215 if (AreStatisticsEnabled()) {
3216 GatherStatistics(F, false);
3220 // This pass performs several distinct transformations. As a compile-time aid
3221 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3222 // library functions aren't declared.
3224 // Preliminary optimizations. This also computes UsedInThisFunction.
3225 OptimizeIndividualCalls(F);
3227 // Optimizations for weak pointers.
3228 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3229 (1 << IC_LoadWeakRetained) |
3230 (1 << IC_StoreWeak) |
3231 (1 << IC_InitWeak) |
3232 (1 << IC_CopyWeak) |
3233 (1 << IC_MoveWeak) |
3234 (1 << IC_DestroyWeak)))
3235 OptimizeWeakCalls(F);
3237 // Optimizations for retain+release pairs.
3238 if (UsedInThisFunction & ((1 << IC_Retain) |
3239 (1 << IC_RetainRV) |
3240 (1 << IC_RetainBlock)))
3241 if (UsedInThisFunction & (1 << IC_Release))
3242 // Run OptimizeSequences until it either stops making changes or
3243 // no retain+release pair nesting is detected.
3244 while (OptimizeSequences(F)) {}
3246 // Optimizations if objc_autorelease is used.
3247 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3248 (1 << IC_AutoreleaseRV)))
3251 // Gather statistics after optimization.
3253 if (AreStatisticsEnabled()) {
3254 GatherStatistics(F, true);
3258 DEBUG(dbgs() << "\n");
3263 void ObjCARCOpt::releaseMemory() {