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/STLExtras.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/IR/IRBuilder.h"
37 #include "llvm/IR/LLVMContext.h"
38 #include "llvm/Support/CFG.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/raw_ostream.h"
43 using namespace llvm::objcarc;
45 /// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
49 /// \brief An associative container with fast insertion-order (deterministic)
50 /// iteration over its elements. Plus the special blot operation.
51 template<class KeyT, class ValueT>
53 /// Map keys to indices in Vector.
54 typedef DenseMap<KeyT, size_t> MapTy;
57 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
62 typedef typename VectorTy::iterator iterator;
63 typedef typename VectorTy::const_iterator const_iterator;
64 iterator begin() { return Vector.begin(); }
65 iterator end() { return Vector.end(); }
66 const_iterator begin() const { return Vector.begin(); }
67 const_iterator end() const { return Vector.end(); }
71 assert(Vector.size() >= Map.size()); // May differ due to blotting.
72 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
74 assert(I->second < Vector.size());
75 assert(Vector[I->second].first == I->first);
77 for (typename VectorTy::const_iterator I = Vector.begin(),
78 E = Vector.end(); I != E; ++I)
80 (Map.count(I->first) &&
81 Map[I->first] == size_t(I - Vector.begin())));
85 ValueT &operator[](const KeyT &Arg) {
86 std::pair<typename MapTy::iterator, bool> Pair =
87 Map.insert(std::make_pair(Arg, size_t(0)));
89 size_t Num = Vector.size();
90 Pair.first->second = Num;
91 Vector.push_back(std::make_pair(Arg, ValueT()));
92 return Vector[Num].second;
94 return Vector[Pair.first->second].second;
97 std::pair<iterator, bool>
98 insert(const std::pair<KeyT, ValueT> &InsertPair) {
99 std::pair<typename MapTy::iterator, bool> Pair =
100 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
102 size_t Num = Vector.size();
103 Pair.first->second = Num;
104 Vector.push_back(InsertPair);
105 return std::make_pair(Vector.begin() + Num, true);
107 return std::make_pair(Vector.begin() + Pair.first->second, false);
110 const_iterator find(const KeyT &Key) const {
111 typename MapTy::const_iterator It = Map.find(Key);
112 if (It == Map.end()) return Vector.end();
113 return Vector.begin() + It->second;
116 /// This is similar to erase, but instead of removing the element from the
117 /// vector, it just zeros out the key in the vector. This leaves iterators
118 /// intact, but clients must be prepared for zeroed-out keys when iterating.
119 void blot(const KeyT &Key) {
120 typename MapTy::iterator It = Map.find(Key);
121 if (It == Map.end()) return;
122 Vector[It->second].first = KeyT();
135 /// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
138 /// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
139 /// as it finds a value with multiple uses.
140 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
141 if (Arg->hasOneUse()) {
142 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
143 return FindSingleUseIdentifiedObject(BC->getOperand(0));
144 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
145 if (GEP->hasAllZeroIndices())
146 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
147 if (IsForwarding(GetBasicInstructionClass(Arg)))
148 return FindSingleUseIdentifiedObject(
149 cast<CallInst>(Arg)->getArgOperand(0));
150 if (!IsObjCIdentifiedObject(Arg))
155 // If we found an identifiable object but it has multiple uses, but they are
156 // trivial uses, we can still consider this to be a single-use value.
157 if (IsObjCIdentifiedObject(Arg)) {
158 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
161 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
171 /// \brief Test whether the given retainable object pointer escapes.
173 /// This differs from regular escape analysis in that a use as an
174 /// argument to a call is not considered an escape.
176 static bool DoesRetainableObjPtrEscape(const User *Ptr) {
177 DEBUG(dbgs() << "DoesRetainableObjPtrEscape: Target: " << *Ptr << "\n");
179 // Walk the def-use chains.
180 SmallVector<const Value *, 4> Worklist;
181 Worklist.push_back(Ptr);
182 // If Ptr has any operands add them as well.
183 for (User::const_op_iterator I = Ptr->op_begin(), E = Ptr->op_end(); I != E;
185 Worklist.push_back(*I);
188 // Ensure we do not visit any value twice.
189 SmallPtrSet<const Value *, 8> VisitedSet;
192 const Value *V = Worklist.pop_back_val();
194 DEBUG(dbgs() << "Visiting: " << *V << "\n");
196 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
198 const User *UUser = *UI;
200 DEBUG(dbgs() << "User: " << *UUser << "\n");
202 // Special - Use by a call (callee or argument) is not considered
204 switch (GetBasicInstructionClass(UUser)) {
209 case IC_AutoreleaseRV: {
210 DEBUG(dbgs() << "User copies pointer arguments. Pointer Escapes!\n");
211 // These special functions make copies of their pointer arguments.
214 case IC_IntrinsicUser:
215 // Use by the use intrinsic is not an escape.
219 // Use by an instruction which copies the value is an escape if the
220 // result is an escape.
221 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
222 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
224 if (VisitedSet.insert(UUser)) {
225 DEBUG(dbgs() << "User copies value. Ptr escapes if result escapes."
226 " Adding to list.\n");
227 Worklist.push_back(UUser);
229 DEBUG(dbgs() << "Already visited node.\n");
233 // Use by a load is not an escape.
234 if (isa<LoadInst>(UUser))
236 // Use by a store is not an escape if the use is the address.
237 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
238 if (V != SI->getValueOperand())
242 // Regular calls and other stuff are not considered escapes.
245 // Otherwise, conservatively assume an escape.
246 DEBUG(dbgs() << "Assuming ptr escapes.\n");
249 } while (!Worklist.empty());
252 DEBUG(dbgs() << "Ptr does not escape.\n");
258 /// \defgroup ARCOpt ARC Optimization.
261 // TODO: On code like this:
264 // stuff_that_cannot_release()
265 // objc_autorelease(%x)
266 // stuff_that_cannot_release()
268 // stuff_that_cannot_release()
269 // objc_autorelease(%x)
271 // The second retain and autorelease can be deleted.
273 // TODO: It should be possible to delete
274 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
275 // pairs if nothing is actually autoreleased between them. Also, autorelease
276 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
277 // after inlining) can be turned into plain release calls.
279 // TODO: Critical-edge splitting. If the optimial insertion point is
280 // a critical edge, the current algorithm has to fail, because it doesn't
281 // know how to split edges. It should be possible to make the optimizer
282 // think in terms of edges, rather than blocks, and then split critical
285 // TODO: OptimizeSequences could generalized to be Interprocedural.
287 // TODO: Recognize that a bunch of other objc runtime calls have
288 // non-escaping arguments and non-releasing arguments, and may be
289 // non-autoreleasing.
291 // TODO: Sink autorelease calls as far as possible. Unfortunately we
292 // usually can't sink them past other calls, which would be the main
293 // case where it would be useful.
295 // TODO: The pointer returned from objc_loadWeakRetained is retained.
297 // TODO: Delete release+retain pairs (rare).
299 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
300 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
301 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
302 STATISTIC(NumRets, "Number of return value forwarding "
303 "retain+autoreleaes eliminated");
304 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
305 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
310 /// \brief A sequence of states that a pointer may go through in which an
311 /// objc_retain and objc_release are actually needed.
314 S_Retain, ///< objc_retain(x).
315 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement.
316 S_Use, ///< any use of x.
317 S_Stop, ///< like S_Release, but code motion is stopped.
318 S_Release, ///< objc_release(x).
319 S_MovableRelease ///< objc_release(x), !clang.imprecise_release.
322 raw_ostream &operator<<(raw_ostream &OS, const Sequence S)
323 LLVM_ATTRIBUTE_UNUSED;
324 raw_ostream &operator<<(raw_ostream &OS, const Sequence S) {
327 return OS << "S_None";
329 return OS << "S_Retain";
331 return OS << "S_CanRelease";
333 return OS << "S_Use";
335 return OS << "S_Release";
336 case S_MovableRelease:
337 return OS << "S_MovableRelease";
339 return OS << "S_Stop";
341 llvm_unreachable("Unknown sequence type.");
345 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
349 if (A == S_None || B == S_None)
352 if (A > B) std::swap(A, B);
354 // Choose the side which is further along in the sequence.
355 if ((A == S_Retain || A == S_CanRelease) &&
356 (B == S_CanRelease || B == S_Use))
359 // Choose the side which is further along in the sequence.
360 if ((A == S_Use || A == S_CanRelease) &&
361 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
363 // If both sides are releases, choose the more conservative one.
364 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
366 if (A == S_Release && B == S_MovableRelease)
374 /// \brief Unidirectional information about either a
375 /// retain-decrement-use-release sequence or release-use-decrement-retain
376 /// reverese sequence.
378 /// After an objc_retain, the reference count of the referenced
379 /// object is known to be positive. Similarly, before an objc_release, the
380 /// reference count of the referenced object is known to be positive. If
381 /// there are retain-release pairs in code regions where the retain count
382 /// is known to be positive, they can be eliminated, regardless of any side
383 /// effects between them.
385 /// Also, a retain+release pair nested within another retain+release
386 /// pair all on the known same pointer value can be eliminated, regardless
387 /// of any intervening side effects.
389 /// KnownSafe is true when either of these conditions is satisfied.
392 /// True of the objc_release calls are all marked with the "tail" keyword.
393 bool IsTailCallRelease;
395 /// If the Calls are objc_release calls and they all have a
396 /// clang.imprecise_release tag, this is the metadata tag.
397 MDNode *ReleaseMetadata;
399 /// For a top-down sequence, the set of objc_retains or
400 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
401 SmallPtrSet<Instruction *, 2> Calls;
403 /// The set of optimal insert positions for moving calls in the opposite
405 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
408 KnownSafe(false), IsTailCallRelease(false), ReleaseMetadata(0) {}
414 void RRInfo::clear() {
416 IsTailCallRelease = false;
419 ReverseInsertPts.clear();
423 /// \brief This class summarizes several per-pointer runtime properties which
424 /// are propogated through the flow graph.
426 /// True if the reference count is known to be incremented.
427 bool KnownPositiveRefCount;
429 /// True of we've seen an opportunity for partial RR elimination, such as
430 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
433 /// The current position in the sequence.
437 /// Unidirectional information about the current sequence.
439 /// TODO: Encapsulate this better.
442 PtrState() : KnownPositiveRefCount(false), Partial(false),
445 void SetKnownPositiveRefCount() {
446 KnownPositiveRefCount = true;
449 void ClearKnownPositiveRefCount() {
450 KnownPositiveRefCount = false;
453 bool HasKnownPositiveRefCount() const {
454 return KnownPositiveRefCount;
457 void SetSeq(Sequence NewSeq) {
458 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
462 Sequence GetSeq() const {
466 void ClearSequenceProgress() {
467 ResetSequenceProgress(S_None);
470 void ResetSequenceProgress(Sequence NewSeq) {
476 void Merge(const PtrState &Other, bool TopDown);
481 PtrState::Merge(const PtrState &Other, bool TopDown) {
482 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
483 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
485 // If we're not in a sequence (anymore), drop all associated state.
489 } else if (Partial || Other.Partial) {
490 // If we're doing a merge on a path that's previously seen a partial
491 // merge, conservatively drop the sequence, to avoid doing partial
492 // RR elimination. If the branch predicates for the two merge differ,
493 // mixing them is unsafe.
494 ClearSequenceProgress();
496 // Conservatively merge the ReleaseMetadata information.
497 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
498 RRI.ReleaseMetadata = 0;
500 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
501 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
502 Other.RRI.IsTailCallRelease;
503 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
505 // Merge the insert point sets. If there are any differences,
506 // that makes this a partial merge.
507 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
508 for (SmallPtrSet<Instruction *, 2>::const_iterator
509 I = Other.RRI.ReverseInsertPts.begin(),
510 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
511 Partial |= RRI.ReverseInsertPts.insert(*I);
516 /// \brief Per-BasicBlock state.
518 /// The number of unique control paths from the entry which can reach this
520 unsigned TopDownPathCount;
522 /// The number of unique control paths to exits from this block.
523 unsigned BottomUpPathCount;
525 /// A type for PerPtrTopDown and PerPtrBottomUp.
526 typedef MapVector<const Value *, PtrState> MapTy;
528 /// The top-down traversal uses this to record information known about a
529 /// pointer at the bottom of each block.
532 /// The bottom-up traversal uses this to record information known about a
533 /// pointer at the top of each block.
534 MapTy PerPtrBottomUp;
536 /// Effective predecessors of the current block ignoring ignorable edges and
537 /// ignored backedges.
538 SmallVector<BasicBlock *, 2> Preds;
539 /// Effective successors of the current block ignoring ignorable edges and
540 /// ignored backedges.
541 SmallVector<BasicBlock *, 2> Succs;
544 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
546 typedef MapTy::iterator ptr_iterator;
547 typedef MapTy::const_iterator ptr_const_iterator;
549 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
550 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
551 ptr_const_iterator top_down_ptr_begin() const {
552 return PerPtrTopDown.begin();
554 ptr_const_iterator top_down_ptr_end() const {
555 return PerPtrTopDown.end();
558 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
559 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
560 ptr_const_iterator bottom_up_ptr_begin() const {
561 return PerPtrBottomUp.begin();
563 ptr_const_iterator bottom_up_ptr_end() const {
564 return PerPtrBottomUp.end();
567 /// Mark this block as being an entry block, which has one path from the
568 /// entry by definition.
569 void SetAsEntry() { TopDownPathCount = 1; }
571 /// Mark this block as being an exit block, which has one path to an exit by
573 void SetAsExit() { BottomUpPathCount = 1; }
575 PtrState &getPtrTopDownState(const Value *Arg) {
576 return PerPtrTopDown[Arg];
579 PtrState &getPtrBottomUpState(const Value *Arg) {
580 return PerPtrBottomUp[Arg];
583 void clearBottomUpPointers() {
584 PerPtrBottomUp.clear();
587 void clearTopDownPointers() {
588 PerPtrTopDown.clear();
591 void InitFromPred(const BBState &Other);
592 void InitFromSucc(const BBState &Other);
593 void MergePred(const BBState &Other);
594 void MergeSucc(const BBState &Other);
596 /// Return the number of possible unique paths from an entry to an exit
597 /// which pass through this block. This is only valid after both the
598 /// top-down and bottom-up traversals are complete.
599 unsigned GetAllPathCount() const {
600 assert(TopDownPathCount != 0);
601 assert(BottomUpPathCount != 0);
602 return TopDownPathCount * BottomUpPathCount;
605 // Specialized CFG utilities.
606 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
607 edge_iterator pred_begin() { return Preds.begin(); }
608 edge_iterator pred_end() { return Preds.end(); }
609 edge_iterator succ_begin() { return Succs.begin(); }
610 edge_iterator succ_end() { return Succs.end(); }
612 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
613 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
615 bool isExit() const { return Succs.empty(); }
619 void BBState::InitFromPred(const BBState &Other) {
620 PerPtrTopDown = Other.PerPtrTopDown;
621 TopDownPathCount = Other.TopDownPathCount;
624 void BBState::InitFromSucc(const BBState &Other) {
625 PerPtrBottomUp = Other.PerPtrBottomUp;
626 BottomUpPathCount = Other.BottomUpPathCount;
629 /// The top-down traversal uses this to merge information about predecessors to
630 /// form the initial state for a new block.
631 void BBState::MergePred(const BBState &Other) {
632 // Other.TopDownPathCount can be 0, in which case it is either dead or a
633 // loop backedge. Loop backedges are special.
634 TopDownPathCount += Other.TopDownPathCount;
636 // Check for overflow. If we have overflow, fall back to conservative
638 if (TopDownPathCount < Other.TopDownPathCount) {
639 clearTopDownPointers();
643 // For each entry in the other set, if our set has an entry with the same key,
644 // merge the entries. Otherwise, copy the entry and merge it with an empty
646 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
647 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
648 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
649 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
653 // For each entry in our set, if the other set doesn't have an entry with the
654 // same key, force it to merge with an empty entry.
655 for (ptr_iterator MI = top_down_ptr_begin(),
656 ME = top_down_ptr_end(); MI != ME; ++MI)
657 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
658 MI->second.Merge(PtrState(), /*TopDown=*/true);
661 /// The bottom-up traversal uses this to merge information about successors to
662 /// form the initial state for a new block.
663 void BBState::MergeSucc(const BBState &Other) {
664 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
665 // loop backedge. Loop backedges are special.
666 BottomUpPathCount += Other.BottomUpPathCount;
668 // Check for overflow. If we have overflow, fall back to conservative
670 if (BottomUpPathCount < Other.BottomUpPathCount) {
671 clearBottomUpPointers();
675 // For each entry in the other set, if our set has an entry with the
676 // same key, merge the entries. Otherwise, copy the entry and merge
677 // it with an empty entry.
678 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
679 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
680 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
681 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
685 // For each entry in our set, if the other set doesn't have an entry
686 // with the same key, force it to merge with an empty entry.
687 for (ptr_iterator MI = bottom_up_ptr_begin(),
688 ME = bottom_up_ptr_end(); MI != ME; ++MI)
689 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
690 MI->second.Merge(PtrState(), /*TopDown=*/false);
693 // Only enable ARC Annotations if we are building a debug version of
696 #define ARC_ANNOTATIONS
699 // Define some macros along the lines of DEBUG and some helper functions to make
700 // it cleaner to create annotations in the source code and to no-op when not
701 // building in debug mode.
702 #ifdef ARC_ANNOTATIONS
704 #include "llvm/Support/CommandLine.h"
706 /// Enable/disable ARC sequence annotations.
708 EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false));
710 /// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
711 /// instruction so that we can track backwards when post processing via the llvm
712 /// arc annotation processor tool. If the function is an
713 static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
717 // If pointer is a result of an instruction and it does not have a source
718 // MDNode it, attach a new MDNode onto it. If pointer is a result of
719 // an instruction and does have a source MDNode attached to it, return a
720 // reference to said Node. Otherwise just return 0.
721 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
723 if (!(Node = Inst->getMetadata(NodeId))) {
724 // We do not have any node. Generate and attatch the hash MDString to the
727 // We just use an MDString to ensure that this metadata gets written out
728 // of line at the module level and to provide a very simple format
729 // encoding the information herein. Both of these makes it simpler to
730 // parse the annotations by a simple external program.
732 raw_string_ostream os(Str);
733 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
734 << Inst->getName() << ")";
736 Hash = MDString::get(Inst->getContext(), os.str());
737 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
739 // We have a node. Grab its hash and return it.
740 assert(Node->getNumOperands() == 1 &&
741 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
742 Hash = cast<MDString>(Node->getOperand(0));
744 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
746 raw_string_ostream os(str);
747 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
749 Hash = MDString::get(Arg->getContext(), os.str());
755 static std::string SequenceToString(Sequence A) {
757 raw_string_ostream os(str);
762 /// Helper function to change a Sequence into a String object using our overload
763 /// for raw_ostream so we only have printing code in one location.
764 static MDString *SequenceToMDString(LLVMContext &Context,
766 return MDString::get(Context, SequenceToString(A));
769 /// A simple function to generate a MDNode which describes the change in state
770 /// for Value *Ptr caused by Instruction *Inst.
771 static void AppendMDNodeToInstForPtr(unsigned NodeId,
774 MDString *PtrSourceMDNodeID,
778 Value *tmp[3] = {PtrSourceMDNodeID,
779 SequenceToMDString(Inst->getContext(),
781 SequenceToMDString(Inst->getContext(),
783 Node = MDNode::get(Inst->getContext(),
784 ArrayRef<Value*>(tmp, 3));
786 Inst->setMetadata(NodeId, Node);
789 /// Add to the beginning of the basic block llvm.ptr.annotations which show the
790 /// state of a pointer at the entrance to a basic block.
791 static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
792 Value *Ptr, Sequence Seq) {
793 Module *M = BB->getParent()->getParent();
794 LLVMContext &C = M->getContext();
795 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
796 Type *I8XX = PointerType::getUnqual(I8X);
797 Type *Params[] = {I8XX, I8XX};
798 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
799 ArrayRef<Type*>(Params, 2),
801 Constant *Callee = M->getOrInsertFunction(Name, FTy);
803 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
806 StringRef Tmp = Ptr->getName();
807 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
808 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
810 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
811 cast<Constant>(ActualPtrName), Tmp);
815 std::string SeqStr = SequenceToString(Seq);
816 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
817 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
819 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
820 cast<Constant>(ActualPtrName), SeqStr);
823 Builder.CreateCall2(Callee, PtrName, S);
826 /// Add to the end of the basic block llvm.ptr.annotations which show the state
827 /// of the pointer at the bottom of the basic block.
828 static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
829 Value *Ptr, Sequence Seq) {
830 Module *M = BB->getParent()->getParent();
831 LLVMContext &C = M->getContext();
832 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
833 Type *I8XX = PointerType::getUnqual(I8X);
834 Type *Params[] = {I8XX, I8XX};
835 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
836 ArrayRef<Type*>(Params, 2),
838 Constant *Callee = M->getOrInsertFunction(Name, FTy);
840 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
843 StringRef Tmp = Ptr->getName();
844 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
845 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
847 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
848 cast<Constant>(ActualPtrName), Tmp);
852 std::string SeqStr = SequenceToString(Seq);
853 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
854 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
856 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
857 cast<Constant>(ActualPtrName), SeqStr);
859 Builder.CreateCall2(Callee, PtrName, S);
862 /// Adds a source annotation to pointer and a state change annotation to Inst
863 /// referencing the source annotation and the old/new state of pointer.
864 static void GenerateARCAnnotation(unsigned InstMDId,
870 if (EnableARCAnnotations) {
871 // First generate the source annotation on our pointer. This will return an
872 // MDString* if Ptr actually comes from an instruction implying we can put
873 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
874 // then we know that our pointer is from an Argument so we put a reference
875 // to the argument number.
877 // The point of this is to make it easy for the
878 // llvm-arc-annotation-processor tool to cross reference where the source
879 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
880 // information via debug info for backends to use (since why would anyone
881 // need such a thing from LLVM IR besides in non standard cases
883 MDString *SourcePtrMDNode =
884 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
885 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
890 // The actual interface for accessing the above functionality is defined via
891 // some simple macros which are defined below. We do this so that the user does
892 // not need to pass in what metadata id is needed resulting in cleaner code and
893 // additionally since it provides an easy way to conditionally no-op all
894 // annotation support in a non-debug build.
896 /// Use this macro to annotate a sequence state change when processing
897 /// instructions bottom up,
898 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
899 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
900 ARCAnnotationProvenanceSourceMDKind, (inst), \
901 const_cast<Value*>(ptr), (old), (new))
902 /// Use this macro to annotate a sequence state change when processing
903 /// instructions top down.
904 #define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
905 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
906 ARCAnnotationProvenanceSourceMDKind, (inst), \
907 const_cast<Value*>(ptr), (old), (new))
909 #define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
911 if (EnableARCAnnotations) { \
912 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
913 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
914 Value *Ptr = const_cast<Value*>(I->first); \
915 Sequence Seq = I->second.GetSeq(); \
916 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
921 #define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
922 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
924 #define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
925 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
926 Terminator, bottom_up)
927 #define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
928 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
930 #define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
931 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
932 Terminator, top_down)
934 #else // !ARC_ANNOTATION
935 // If annotations are off, noop.
936 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
937 #define ANNOTATE_TOPDOWN(inst, ptr, old, new)
938 #define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
939 #define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
940 #define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
941 #define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
942 #endif // !ARC_ANNOTATION
945 /// \brief The main ARC optimization pass.
946 class ObjCARCOpt : public FunctionPass {
948 ProvenanceAnalysis PA;
950 /// A flag indicating whether this optimization pass should run.
953 /// Declarations for ObjC runtime functions, for use in creating calls to
954 /// them. These are initialized lazily to avoid cluttering up the Module
955 /// with unused declarations.
957 /// Declaration for ObjC runtime function
958 /// objc_retainAutoreleasedReturnValue.
959 Constant *RetainRVCallee;
960 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
961 Constant *AutoreleaseRVCallee;
962 /// Declaration for ObjC runtime function objc_release.
963 Constant *ReleaseCallee;
964 /// Declaration for ObjC runtime function objc_retain.
965 Constant *RetainCallee;
966 /// Declaration for ObjC runtime function objc_retainBlock.
967 Constant *RetainBlockCallee;
968 /// Declaration for ObjC runtime function objc_autorelease.
969 Constant *AutoreleaseCallee;
971 /// Flags which determine whether each of the interesting runtine functions
972 /// is in fact used in the current function.
973 unsigned UsedInThisFunction;
975 /// The Metadata Kind for clang.imprecise_release metadata.
976 unsigned ImpreciseReleaseMDKind;
978 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
979 unsigned CopyOnEscapeMDKind;
981 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
982 unsigned NoObjCARCExceptionsMDKind;
984 #ifdef ARC_ANNOTATIONS
985 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
986 unsigned ARCAnnotationBottomUpMDKind;
987 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
988 unsigned ARCAnnotationTopDownMDKind;
989 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
990 unsigned ARCAnnotationProvenanceSourceMDKind;
991 #endif // ARC_ANNOATIONS
993 Constant *getRetainRVCallee(Module *M);
994 Constant *getAutoreleaseRVCallee(Module *M);
995 Constant *getReleaseCallee(Module *M);
996 Constant *getRetainCallee(Module *M);
997 Constant *getRetainBlockCallee(Module *M);
998 Constant *getAutoreleaseCallee(Module *M);
1000 bool IsRetainBlockOptimizable(const Instruction *Inst);
1002 void OptimizeRetainCall(Function &F, Instruction *Retain);
1003 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1004 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1005 InstructionClass &Class);
1006 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1007 InstructionClass &Class);
1008 void OptimizeIndividualCalls(Function &F);
1010 void CheckForCFGHazards(const BasicBlock *BB,
1011 DenseMap<const BasicBlock *, BBState> &BBStates,
1012 BBState &MyStates) const;
1013 bool VisitInstructionBottomUp(Instruction *Inst,
1015 MapVector<Value *, RRInfo> &Retains,
1017 bool VisitBottomUp(BasicBlock *BB,
1018 DenseMap<const BasicBlock *, BBState> &BBStates,
1019 MapVector<Value *, RRInfo> &Retains);
1020 bool VisitInstructionTopDown(Instruction *Inst,
1021 DenseMap<Value *, RRInfo> &Releases,
1023 bool VisitTopDown(BasicBlock *BB,
1024 DenseMap<const BasicBlock *, BBState> &BBStates,
1025 DenseMap<Value *, RRInfo> &Releases);
1026 bool Visit(Function &F,
1027 DenseMap<const BasicBlock *, BBState> &BBStates,
1028 MapVector<Value *, RRInfo> &Retains,
1029 DenseMap<Value *, RRInfo> &Releases);
1031 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1032 MapVector<Value *, RRInfo> &Retains,
1033 DenseMap<Value *, RRInfo> &Releases,
1034 SmallVectorImpl<Instruction *> &DeadInsts,
1037 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1038 MapVector<Value *, RRInfo> &Retains,
1039 DenseMap<Value *, RRInfo> &Releases,
1041 SmallVector<Instruction *, 4> &NewRetains,
1042 SmallVector<Instruction *, 4> &NewReleases,
1043 SmallVector<Instruction *, 8> &DeadInsts,
1044 RRInfo &RetainsToMove,
1045 RRInfo &ReleasesToMove,
1048 bool &AnyPairsCompletelyEliminated);
1050 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1051 MapVector<Value *, RRInfo> &Retains,
1052 DenseMap<Value *, RRInfo> &Releases,
1055 void OptimizeWeakCalls(Function &F);
1057 bool OptimizeSequences(Function &F);
1059 void OptimizeReturns(Function &F);
1061 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1062 virtual bool doInitialization(Module &M);
1063 virtual bool runOnFunction(Function &F);
1064 virtual void releaseMemory();
1068 ObjCARCOpt() : FunctionPass(ID) {
1069 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1074 char ObjCARCOpt::ID = 0;
1075 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1076 "objc-arc", "ObjC ARC optimization", false, false)
1077 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1078 INITIALIZE_PASS_END(ObjCARCOpt,
1079 "objc-arc", "ObjC ARC optimization", false, false)
1081 Pass *llvm::createObjCARCOptPass() {
1082 return new ObjCARCOpt();
1085 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1086 AU.addRequired<ObjCARCAliasAnalysis>();
1087 AU.addRequired<AliasAnalysis>();
1088 // ARC optimization doesn't currently split critical edges.
1089 AU.setPreservesCFG();
1092 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1093 // Without the magic metadata tag, we have to assume this might be an
1094 // objc_retainBlock call inserted to convert a block pointer to an id,
1095 // in which case it really is needed.
1096 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1099 // If the pointer "escapes" (not including being used in a call),
1100 // the copy may be needed.
1101 if (DoesRetainableObjPtrEscape(Inst))
1104 // Otherwise, it's not needed.
1108 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1109 if (!RetainRVCallee) {
1110 LLVMContext &C = M->getContext();
1111 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1112 Type *Params[] = { I8X };
1113 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1114 AttributeSet Attribute =
1115 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1116 Attribute::NoUnwind);
1118 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1121 return RetainRVCallee;
1124 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1125 if (!AutoreleaseRVCallee) {
1126 LLVMContext &C = M->getContext();
1127 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1128 Type *Params[] = { I8X };
1129 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1130 AttributeSet Attribute =
1131 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1132 Attribute::NoUnwind);
1133 AutoreleaseRVCallee =
1134 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1137 return AutoreleaseRVCallee;
1140 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1141 if (!ReleaseCallee) {
1142 LLVMContext &C = M->getContext();
1143 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1144 AttributeSet Attribute =
1145 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1146 Attribute::NoUnwind);
1148 M->getOrInsertFunction(
1150 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1153 return ReleaseCallee;
1156 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1157 if (!RetainCallee) {
1158 LLVMContext &C = M->getContext();
1159 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1160 AttributeSet Attribute =
1161 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1162 Attribute::NoUnwind);
1164 M->getOrInsertFunction(
1166 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1169 return RetainCallee;
1172 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1173 if (!RetainBlockCallee) {
1174 LLVMContext &C = M->getContext();
1175 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1176 // objc_retainBlock is not nounwind because it calls user copy constructors
1177 // which could theoretically throw.
1179 M->getOrInsertFunction(
1181 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1184 return RetainBlockCallee;
1187 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1188 if (!AutoreleaseCallee) {
1189 LLVMContext &C = M->getContext();
1190 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1191 AttributeSet Attribute =
1192 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1193 Attribute::NoUnwind);
1195 M->getOrInsertFunction(
1197 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1200 return AutoreleaseCallee;
1203 /// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
1206 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
1207 ImmutableCallSite CS(GetObjCArg(Retain));
1208 const Instruction *Call = CS.getInstruction();
1210 if (Call->getParent() != Retain->getParent()) return;
1212 // Check that the call is next to the retain.
1213 BasicBlock::const_iterator I = Call;
1215 while (IsNoopInstruction(I)) ++I;
1219 // Turn it to an objc_retainAutoreleasedReturnValue..
1223 DEBUG(dbgs() << "Transforming objc_retain => "
1224 "objc_retainAutoreleasedReturnValue since the operand is a "
1225 "return value.\nOld: "<< *Retain << "\n");
1227 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
1229 DEBUG(dbgs() << "New: " << *Retain << "\n");
1232 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1233 /// not a return value. Or, if it can be paired with an
1234 /// objc_autoreleaseReturnValue, delete the pair and return true.
1236 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1237 // Check for the argument being from an immediately preceding call or invoke.
1238 const Value *Arg = GetObjCArg(RetainRV);
1239 ImmutableCallSite CS(Arg);
1240 if (const Instruction *Call = CS.getInstruction()) {
1241 if (Call->getParent() == RetainRV->getParent()) {
1242 BasicBlock::const_iterator I = Call;
1244 while (IsNoopInstruction(I)) ++I;
1245 if (&*I == RetainRV)
1247 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
1248 BasicBlock *RetainRVParent = RetainRV->getParent();
1249 if (II->getNormalDest() == RetainRVParent) {
1250 BasicBlock::const_iterator I = RetainRVParent->begin();
1251 while (IsNoopInstruction(I)) ++I;
1252 if (&*I == RetainRV)
1258 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1259 // pointer. In this case, we can delete the pair.
1260 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1262 do --I; while (I != Begin && IsNoopInstruction(I));
1263 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1264 GetObjCArg(I) == Arg) {
1268 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1269 << "Erasing " << *RetainRV << "\n");
1271 EraseInstruction(I);
1272 EraseInstruction(RetainRV);
1277 // Turn it to a plain objc_retain.
1281 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
1282 "objc_retain since the operand is not a return value.\n"
1283 "Old = " << *RetainRV << "\n");
1285 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
1287 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
1292 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1293 /// used as a return value.
1295 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1296 InstructionClass &Class) {
1297 // Check for a return of the pointer value.
1298 const Value *Ptr = GetObjCArg(AutoreleaseRV);
1299 SmallVector<const Value *, 2> Users;
1300 Users.push_back(Ptr);
1302 Ptr = Users.pop_back_val();
1303 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1305 const User *I = *UI;
1306 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1308 if (isa<BitCastInst>(I))
1311 } while (!Users.empty());
1316 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
1317 "objc_autorelease since its operand is not used as a return "
1319 "Old = " << *AutoreleaseRV << "\n");
1321 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1323 setCalledFunction(getAutoreleaseCallee(F.getParent()));
1324 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
1325 Class = IC_Autorelease;
1327 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
1331 // \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1334 // Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1335 // does not escape (following the rules of block escaping), strength reduce the
1336 // objc_retainBlock to an objc_retain.
1338 // TODO: If an objc_retainBlock call is dominated period by a previous
1339 // objc_retainBlock call, strength reduce the objc_retainBlock to an
1342 ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1343 InstructionClass &Class) {
1344 assert(GetBasicInstructionClass(Inst) == Class);
1345 assert(IC_RetainBlock == Class);
1347 // If we can not optimize Inst, return false.
1348 if (!IsRetainBlockOptimizable(Inst))
1351 CallInst *RetainBlock = cast<CallInst>(Inst);
1352 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1353 // Remove copy_on_escape metadata.
1354 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1360 /// Visit each call, one at a time, and make simplifications without doing any
1361 /// additional analysis.
1362 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1363 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
1364 // Reset all the flags in preparation for recomputing them.
1365 UsedInThisFunction = 0;
1367 // Visit all objc_* calls in F.
1368 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1369 Instruction *Inst = &*I++;
1371 InstructionClass Class = GetBasicInstructionClass(Inst);
1373 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
1378 // Delete no-op casts. These function calls have special semantics, but
1379 // the semantics are entirely implemented via lowering in the front-end,
1380 // so by the time they reach the optimizer, they are just no-op calls
1381 // which return their argument.
1383 // There are gray areas here, as the ability to cast reference-counted
1384 // pointers to raw void* and back allows code to break ARC assumptions,
1385 // however these are currently considered to be unimportant.
1389 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
1390 EraseInstruction(Inst);
1393 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1396 case IC_LoadWeakRetained:
1398 case IC_DestroyWeak: {
1399 CallInst *CI = cast<CallInst>(Inst);
1400 if (IsNullOrUndef(CI->getArgOperand(0))) {
1402 Type *Ty = CI->getArgOperand(0)->getType();
1403 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1404 Constant::getNullValue(Ty),
1406 llvm::Value *NewValue = UndefValue::get(CI->getType());
1407 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1408 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1409 CI->replaceAllUsesWith(NewValue);
1410 CI->eraseFromParent();
1417 CallInst *CI = cast<CallInst>(Inst);
1418 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1419 IsNullOrUndef(CI->getArgOperand(1))) {
1421 Type *Ty = CI->getArgOperand(0)->getType();
1422 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1423 Constant::getNullValue(Ty),
1426 llvm::Value *NewValue = UndefValue::get(CI->getType());
1427 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1428 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1430 CI->replaceAllUsesWith(NewValue);
1431 CI->eraseFromParent();
1436 case IC_RetainBlock:
1437 // If we strength reduce an objc_retainBlock to amn objc_retain, continue
1438 // onto the objc_retain peephole optimizations. Otherwise break.
1439 if (!OptimizeRetainBlockCall(F, Inst, Class))
1443 OptimizeRetainCall(F, Inst);
1446 if (OptimizeRetainRVCall(F, Inst))
1449 case IC_AutoreleaseRV:
1450 OptimizeAutoreleaseRVCall(F, Inst, Class);
1454 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
1455 if (IsAutorelease(Class) && Inst->use_empty()) {
1456 CallInst *Call = cast<CallInst>(Inst);
1457 const Value *Arg = Call->getArgOperand(0);
1458 Arg = FindSingleUseIdentifiedObject(Arg);
1463 // Create the declaration lazily.
1464 LLVMContext &C = Inst->getContext();
1466 CallInst::Create(getReleaseCallee(F.getParent()),
1467 Call->getArgOperand(0), "", Call);
1468 NewCall->setMetadata(ImpreciseReleaseMDKind,
1469 MDNode::get(C, ArrayRef<Value *>()));
1471 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1472 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1473 << *NewCall << "\n");
1475 EraseInstruction(Call);
1481 // For functions which can never be passed stack arguments, add
1483 if (IsAlwaysTail(Class)) {
1485 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1486 "passed stack args: " << *Inst << "\n");
1487 cast<CallInst>(Inst)->setTailCall();
1490 // Ensure that functions that can never have a "tail" keyword due to the
1491 // semantics of ARC truly do not do so.
1492 if (IsNeverTail(Class)) {
1494 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
1496 cast<CallInst>(Inst)->setTailCall(false);
1499 // Set nounwind as needed.
1500 if (IsNoThrow(Class)) {
1502 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1504 cast<CallInst>(Inst)->setDoesNotThrow();
1507 if (!IsNoopOnNull(Class)) {
1508 UsedInThisFunction |= 1 << Class;
1512 const Value *Arg = GetObjCArg(Inst);
1514 // ARC calls with null are no-ops. Delete them.
1515 if (IsNullOrUndef(Arg)) {
1518 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1520 EraseInstruction(Inst);
1524 // Keep track of which of retain, release, autorelease, and retain_block
1525 // are actually present in this function.
1526 UsedInThisFunction |= 1 << Class;
1528 // If Arg is a PHI, and one or more incoming values to the
1529 // PHI are null, and the call is control-equivalent to the PHI, and there
1530 // are no relevant side effects between the PHI and the call, the call
1531 // could be pushed up to just those paths with non-null incoming values.
1532 // For now, don't bother splitting critical edges for this.
1533 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1534 Worklist.push_back(std::make_pair(Inst, Arg));
1536 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1540 const PHINode *PN = dyn_cast<PHINode>(Arg);
1543 // Determine if the PHI has any null operands, or any incoming
1545 bool HasNull = false;
1546 bool HasCriticalEdges = false;
1547 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1549 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1550 if (IsNullOrUndef(Incoming))
1552 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1553 .getNumSuccessors() != 1) {
1554 HasCriticalEdges = true;
1558 // If we have null operands and no critical edges, optimize.
1559 if (!HasCriticalEdges && HasNull) {
1560 SmallPtrSet<Instruction *, 4> DependingInstructions;
1561 SmallPtrSet<const BasicBlock *, 4> Visited;
1563 // Check that there is nothing that cares about the reference
1564 // count between the call and the phi.
1567 case IC_RetainBlock:
1568 // These can always be moved up.
1571 // These can't be moved across things that care about the retain
1573 FindDependencies(NeedsPositiveRetainCount, Arg,
1574 Inst->getParent(), Inst,
1575 DependingInstructions, Visited, PA);
1577 case IC_Autorelease:
1578 // These can't be moved across autorelease pool scope boundaries.
1579 FindDependencies(AutoreleasePoolBoundary, Arg,
1580 Inst->getParent(), Inst,
1581 DependingInstructions, Visited, PA);
1584 case IC_AutoreleaseRV:
1585 // Don't move these; the RV optimization depends on the autoreleaseRV
1586 // being tail called, and the retainRV being immediately after a call
1587 // (which might still happen if we get lucky with codegen layout, but
1588 // it's not worth taking the chance).
1591 llvm_unreachable("Invalid dependence flavor");
1594 if (DependingInstructions.size() == 1 &&
1595 *DependingInstructions.begin() == PN) {
1598 // Clone the call into each predecessor that has a non-null value.
1599 CallInst *CInst = cast<CallInst>(Inst);
1600 Type *ParamTy = CInst->getArgOperand(0)->getType();
1601 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1603 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1604 if (!IsNullOrUndef(Incoming)) {
1605 CallInst *Clone = cast<CallInst>(CInst->clone());
1606 Value *Op = PN->getIncomingValue(i);
1607 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1608 if (Op->getType() != ParamTy)
1609 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1610 Clone->setArgOperand(0, Op);
1611 Clone->insertBefore(InsertPos);
1613 DEBUG(dbgs() << "Cloning "
1615 "And inserting clone at " << *InsertPos << "\n");
1616 Worklist.push_back(std::make_pair(Clone, Incoming));
1619 // Erase the original call.
1620 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
1621 EraseInstruction(CInst);
1625 } while (!Worklist.empty());
1629 /// Check for critical edges, loop boundaries, irreducible control flow, or
1630 /// other CFG structures where moving code across the edge would result in it
1631 /// being executed more.
1633 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1634 DenseMap<const BasicBlock *, BBState> &BBStates,
1635 BBState &MyStates) const {
1636 // If any top-down local-use or possible-dec has a succ which is earlier in
1637 // the sequence, forget it.
1638 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
1639 E = MyStates.top_down_ptr_end(); I != E; ++I)
1640 switch (I->second.GetSeq()) {
1643 const Value *Arg = I->first;
1644 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1645 bool SomeSuccHasSame = false;
1646 bool AllSuccsHaveSame = true;
1647 PtrState &S = I->second;
1648 succ_const_iterator SI(TI), SE(TI, false);
1650 for (; SI != SE; ++SI) {
1651 Sequence SuccSSeq = S_None;
1652 bool SuccSRRIKnownSafe = false;
1653 // If VisitBottomUp has pointer information for this successor, take
1654 // what we know about it.
1655 DenseMap<const BasicBlock *, BBState>::iterator BBI =
1657 assert(BBI != BBStates.end());
1658 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1659 SuccSSeq = SuccS.GetSeq();
1660 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
1663 case S_CanRelease: {
1664 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
1665 S.ClearSequenceProgress();
1671 SomeSuccHasSame = true;
1675 case S_MovableRelease:
1676 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1677 AllSuccsHaveSame = false;
1680 llvm_unreachable("bottom-up pointer in retain state!");
1683 // If the state at the other end of any of the successor edges
1684 // matches the current state, require all edges to match. This
1685 // guards against loops in the middle of a sequence.
1686 if (SomeSuccHasSame && !AllSuccsHaveSame)
1687 S.ClearSequenceProgress();
1690 case S_CanRelease: {
1691 const Value *Arg = I->first;
1692 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1693 bool SomeSuccHasSame = false;
1694 bool AllSuccsHaveSame = true;
1695 PtrState &S = I->second;
1696 succ_const_iterator SI(TI), SE(TI, false);
1698 for (; SI != SE; ++SI) {
1699 Sequence SuccSSeq = S_None;
1700 bool SuccSRRIKnownSafe = false;
1701 // If VisitBottomUp has pointer information for this successor, take
1702 // what we know about it.
1703 DenseMap<const BasicBlock *, BBState>::iterator BBI =
1705 assert(BBI != BBStates.end());
1706 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1707 SuccSSeq = SuccS.GetSeq();
1708 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
1711 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
1712 S.ClearSequenceProgress();
1718 SomeSuccHasSame = true;
1722 case S_MovableRelease:
1724 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1725 AllSuccsHaveSame = false;
1728 llvm_unreachable("bottom-up pointer in retain state!");
1731 // If the state at the other end of any of the successor edges
1732 // matches the current state, require all edges to match. This
1733 // guards against loops in the middle of a sequence.
1734 if (SomeSuccHasSame && !AllSuccsHaveSame)
1735 S.ClearSequenceProgress();
1742 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
1744 MapVector<Value *, RRInfo> &Retains,
1745 BBState &MyStates) {
1746 bool NestingDetected = false;
1747 InstructionClass Class = GetInstructionClass(Inst);
1748 const Value *Arg = 0;
1752 Arg = GetObjCArg(Inst);
1754 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1756 // If we see two releases in a row on the same pointer. If so, make
1757 // a note, and we'll cicle back to revisit it after we've
1758 // hopefully eliminated the second release, which may allow us to
1759 // eliminate the first release too.
1760 // Theoretically we could implement removal of nested retain+release
1761 // pairs by making PtrState hold a stack of states, but this is
1762 // simple and avoids adding overhead for the non-nested case.
1763 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
1764 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
1765 NestingDetected = true;
1768 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
1769 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1770 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1771 S.ResetSequenceProgress(NewSeq);
1772 S.RRI.ReleaseMetadata = ReleaseMetadata;
1773 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
1774 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1775 S.RRI.Calls.insert(Inst);
1776 S.SetKnownPositiveRefCount();
1779 case IC_RetainBlock:
1780 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1781 // objc_retainBlocks to objc_retains. Thus at this point any
1782 // objc_retainBlocks that we see are not optimizable.
1786 Arg = GetObjCArg(Inst);
1788 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1789 S.SetKnownPositiveRefCount();
1791 Sequence OldSeq = S.GetSeq();
1795 case S_MovableRelease:
1797 S.RRI.ReverseInsertPts.clear();
1800 // Don't do retain+release tracking for IC_RetainRV, because it's
1801 // better to let it remain as the first instruction after a call.
1802 if (Class != IC_RetainRV)
1803 Retains[Inst] = S.RRI;
1804 S.ClearSequenceProgress();
1809 llvm_unreachable("bottom-up pointer in retain state!");
1811 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
1812 return NestingDetected;
1814 case IC_AutoreleasepoolPop:
1815 // Conservatively, clear MyStates for all known pointers.
1816 MyStates.clearBottomUpPointers();
1817 return NestingDetected;
1818 case IC_AutoreleasepoolPush:
1820 // These are irrelevant.
1821 return NestingDetected;
1826 // Consider any other possible effects of this instruction on each
1827 // pointer being tracked.
1828 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1829 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1830 const Value *Ptr = MI->first;
1832 continue; // Handled above.
1833 PtrState &S = MI->second;
1834 Sequence Seq = S.GetSeq();
1836 // Check for possible releases.
1837 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
1838 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1840 S.ClearKnownPositiveRefCount();
1843 S.SetSeq(S_CanRelease);
1844 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
1848 case S_MovableRelease:
1853 llvm_unreachable("bottom-up pointer in retain state!");
1857 // Check for possible direct uses.
1860 case S_MovableRelease:
1861 if (CanUse(Inst, Ptr, PA, Class)) {
1862 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1864 assert(S.RRI.ReverseInsertPts.empty());
1865 // If this is an invoke instruction, we're scanning it as part of
1866 // one of its successor blocks, since we can't insert code after it
1867 // in its own block, and we don't want to split critical edges.
1868 if (isa<InvokeInst>(Inst))
1869 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1871 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
1873 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
1874 } else if (Seq == S_Release && IsUser(Class)) {
1875 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
1877 // Non-movable releases depend on any possible objc pointer use.
1879 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
1880 assert(S.RRI.ReverseInsertPts.empty());
1881 // As above; handle invoke specially.
1882 if (isa<InvokeInst>(Inst))
1883 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1885 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
1889 if (CanUse(Inst, Ptr, PA, Class)) {
1890 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
1893 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
1901 llvm_unreachable("bottom-up pointer in retain state!");
1905 return NestingDetected;
1909 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1910 DenseMap<const BasicBlock *, BBState> &BBStates,
1911 MapVector<Value *, RRInfo> &Retains) {
1913 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
1915 bool NestingDetected = false;
1916 BBState &MyStates = BBStates[BB];
1918 // Merge the states from each successor to compute the initial state
1919 // for the current block.
1920 BBState::edge_iterator SI(MyStates.succ_begin()),
1921 SE(MyStates.succ_end());
1923 const BasicBlock *Succ = *SI;
1924 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
1925 assert(I != BBStates.end());
1926 MyStates.InitFromSucc(I->second);
1928 for (; SI != SE; ++SI) {
1930 I = BBStates.find(Succ);
1931 assert(I != BBStates.end());
1932 MyStates.MergeSucc(I->second);
1936 // If ARC Annotations are enabled, output the current state of pointers at the
1937 // bottom of the basic block.
1938 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
1940 // Visit all the instructions, bottom-up.
1941 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
1942 Instruction *Inst = llvm::prior(I);
1944 // Invoke instructions are visited as part of their successors (below).
1945 if (isa<InvokeInst>(Inst))
1948 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
1950 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
1953 // If there's a predecessor with an invoke, visit the invoke as if it were
1954 // part of this block, since we can't insert code after an invoke in its own
1955 // block, and we don't want to split critical edges.
1956 for (BBState::edge_iterator PI(MyStates.pred_begin()),
1957 PE(MyStates.pred_end()); PI != PE; ++PI) {
1958 BasicBlock *Pred = *PI;
1959 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
1960 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
1963 // If ARC Annotations are enabled, output the current state of pointers at the
1964 // top of the basic block.
1965 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
1967 return NestingDetected;
1971 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
1972 DenseMap<Value *, RRInfo> &Releases,
1973 BBState &MyStates) {
1974 bool NestingDetected = false;
1975 InstructionClass Class = GetInstructionClass(Inst);
1976 const Value *Arg = 0;
1979 case IC_RetainBlock:
1980 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1981 // objc_retainBlocks to objc_retains. Thus at this point any
1982 // objc_retainBlocks that we see are not optimizable.
1986 Arg = GetObjCArg(Inst);
1988 PtrState &S = MyStates.getPtrTopDownState(Arg);
1990 // Don't do retain+release tracking for IC_RetainRV, because it's
1991 // better to let it remain as the first instruction after a call.
1992 if (Class != IC_RetainRV) {
1993 // If we see two retains in a row on the same pointer. If so, make
1994 // a note, and we'll cicle back to revisit it after we've
1995 // hopefully eliminated the second retain, which may allow us to
1996 // eliminate the first retain too.
1997 // Theoretically we could implement removal of nested retain+release
1998 // pairs by making PtrState hold a stack of states, but this is
1999 // simple and avoids adding overhead for the non-nested case.
2000 if (S.GetSeq() == S_Retain)
2001 NestingDetected = true;
2003 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
2004 S.ResetSequenceProgress(S_Retain);
2005 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
2006 S.RRI.Calls.insert(Inst);
2009 S.SetKnownPositiveRefCount();
2011 // A retain can be a potential use; procede to the generic checking
2016 Arg = GetObjCArg(Inst);
2018 PtrState &S = MyStates.getPtrTopDownState(Arg);
2019 S.ClearKnownPositiveRefCount();
2021 switch (S.GetSeq()) {
2024 S.RRI.ReverseInsertPts.clear();
2027 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2028 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2029 Releases[Inst] = S.RRI;
2030 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
2031 S.ClearSequenceProgress();
2037 case S_MovableRelease:
2038 llvm_unreachable("top-down pointer in release state!");
2042 case IC_AutoreleasepoolPop:
2043 // Conservatively, clear MyStates for all known pointers.
2044 MyStates.clearTopDownPointers();
2045 return NestingDetected;
2046 case IC_AutoreleasepoolPush:
2048 // These are irrelevant.
2049 return NestingDetected;
2054 // Consider any other possible effects of this instruction on each
2055 // pointer being tracked.
2056 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2057 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2058 const Value *Ptr = MI->first;
2060 continue; // Handled above.
2061 PtrState &S = MI->second;
2062 Sequence Seq = S.GetSeq();
2064 // Check for possible releases.
2065 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2066 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
2068 S.ClearKnownPositiveRefCount();
2071 S.SetSeq(S_CanRelease);
2072 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
2073 assert(S.RRI.ReverseInsertPts.empty());
2074 S.RRI.ReverseInsertPts.insert(Inst);
2076 // One call can't cause a transition from S_Retain to S_CanRelease
2077 // and S_CanRelease to S_Use. If we've made the first transition,
2086 case S_MovableRelease:
2087 llvm_unreachable("top-down pointer in release state!");
2091 // Check for possible direct uses.
2094 if (CanUse(Inst, Ptr, PA, Class)) {
2095 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2098 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2107 case S_MovableRelease:
2108 llvm_unreachable("top-down pointer in release state!");
2112 return NestingDetected;
2116 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2117 DenseMap<const BasicBlock *, BBState> &BBStates,
2118 DenseMap<Value *, RRInfo> &Releases) {
2119 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
2120 bool NestingDetected = false;
2121 BBState &MyStates = BBStates[BB];
2123 // Merge the states from each predecessor to compute the initial state
2124 // for the current block.
2125 BBState::edge_iterator PI(MyStates.pred_begin()),
2126 PE(MyStates.pred_end());
2128 const BasicBlock *Pred = *PI;
2129 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2130 assert(I != BBStates.end());
2131 MyStates.InitFromPred(I->second);
2133 for (; PI != PE; ++PI) {
2135 I = BBStates.find(Pred);
2136 assert(I != BBStates.end());
2137 MyStates.MergePred(I->second);
2141 // If ARC Annotations are enabled, output the current state of pointers at the
2142 // top of the basic block.
2143 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
2145 // Visit all the instructions, top-down.
2146 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2147 Instruction *Inst = I;
2149 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
2151 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
2154 // If ARC Annotations are enabled, output the current state of pointers at the
2155 // bottom of the basic block.
2156 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
2158 CheckForCFGHazards(BB, BBStates, MyStates);
2159 return NestingDetected;
2163 ComputePostOrders(Function &F,
2164 SmallVectorImpl<BasicBlock *> &PostOrder,
2165 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2166 unsigned NoObjCARCExceptionsMDKind,
2167 DenseMap<const BasicBlock *, BBState> &BBStates) {
2168 /// The visited set, for doing DFS walks.
2169 SmallPtrSet<BasicBlock *, 16> Visited;
2171 // Do DFS, computing the PostOrder.
2172 SmallPtrSet<BasicBlock *, 16> OnStack;
2173 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2175 // Functions always have exactly one entry block, and we don't have
2176 // any other block that we treat like an entry block.
2177 BasicBlock *EntryBB = &F.getEntryBlock();
2178 BBState &MyStates = BBStates[EntryBB];
2179 MyStates.SetAsEntry();
2180 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2181 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
2182 Visited.insert(EntryBB);
2183 OnStack.insert(EntryBB);
2186 BasicBlock *CurrBB = SuccStack.back().first;
2187 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2188 succ_iterator SE(TI, false);
2190 while (SuccStack.back().second != SE) {
2191 BasicBlock *SuccBB = *SuccStack.back().second++;
2192 if (Visited.insert(SuccBB)) {
2193 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2194 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
2195 BBStates[CurrBB].addSucc(SuccBB);
2196 BBState &SuccStates = BBStates[SuccBB];
2197 SuccStates.addPred(CurrBB);
2198 OnStack.insert(SuccBB);
2202 if (!OnStack.count(SuccBB)) {
2203 BBStates[CurrBB].addSucc(SuccBB);
2204 BBStates[SuccBB].addPred(CurrBB);
2207 OnStack.erase(CurrBB);
2208 PostOrder.push_back(CurrBB);
2209 SuccStack.pop_back();
2210 } while (!SuccStack.empty());
2214 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2215 // Functions may have many exits, and there also blocks which we treat
2216 // as exits due to ignored edges.
2217 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2218 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2219 BasicBlock *ExitBB = I;
2220 BBState &MyStates = BBStates[ExitBB];
2221 if (!MyStates.isExit())
2224 MyStates.SetAsExit();
2226 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
2227 Visited.insert(ExitBB);
2228 while (!PredStack.empty()) {
2229 reverse_dfs_next_succ:
2230 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2231 while (PredStack.back().second != PE) {
2232 BasicBlock *BB = *PredStack.back().second++;
2233 if (Visited.insert(BB)) {
2234 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
2235 goto reverse_dfs_next_succ;
2238 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2243 // Visit the function both top-down and bottom-up.
2245 ObjCARCOpt::Visit(Function &F,
2246 DenseMap<const BasicBlock *, BBState> &BBStates,
2247 MapVector<Value *, RRInfo> &Retains,
2248 DenseMap<Value *, RRInfo> &Releases) {
2250 // Use reverse-postorder traversals, because we magically know that loops
2251 // will be well behaved, i.e. they won't repeatedly call retain on a single
2252 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2253 // class here because we want the reverse-CFG postorder to consider each
2254 // function exit point, and we want to ignore selected cycle edges.
2255 SmallVector<BasicBlock *, 16> PostOrder;
2256 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2257 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2258 NoObjCARCExceptionsMDKind,
2261 // Use reverse-postorder on the reverse CFG for bottom-up.
2262 bool BottomUpNestingDetected = false;
2263 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2264 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2266 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
2268 // Use reverse-postorder for top-down.
2269 bool TopDownNestingDetected = false;
2270 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2271 PostOrder.rbegin(), E = PostOrder.rend();
2273 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
2275 return TopDownNestingDetected && BottomUpNestingDetected;
2278 /// Move the calls in RetainsToMove and ReleasesToMove.
2279 void ObjCARCOpt::MoveCalls(Value *Arg,
2280 RRInfo &RetainsToMove,
2281 RRInfo &ReleasesToMove,
2282 MapVector<Value *, RRInfo> &Retains,
2283 DenseMap<Value *, RRInfo> &Releases,
2284 SmallVectorImpl<Instruction *> &DeadInsts,
2286 Type *ArgTy = Arg->getType();
2287 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2289 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
2291 // Insert the new retain and release calls.
2292 for (SmallPtrSet<Instruction *, 2>::const_iterator
2293 PI = ReleasesToMove.ReverseInsertPts.begin(),
2294 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2295 Instruction *InsertPt = *PI;
2296 Value *MyArg = ArgTy == ParamTy ? Arg :
2297 new BitCastInst(Arg, ParamTy, "", InsertPt);
2299 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
2300 Call->setDoesNotThrow();
2301 Call->setTailCall();
2303 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2304 "At insertion point: " << *InsertPt << "\n");
2306 for (SmallPtrSet<Instruction *, 2>::const_iterator
2307 PI = RetainsToMove.ReverseInsertPts.begin(),
2308 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2309 Instruction *InsertPt = *PI;
2310 Value *MyArg = ArgTy == ParamTy ? Arg :
2311 new BitCastInst(Arg, ParamTy, "", InsertPt);
2312 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2314 // Attach a clang.imprecise_release metadata tag, if appropriate.
2315 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2316 Call->setMetadata(ImpreciseReleaseMDKind, M);
2317 Call->setDoesNotThrow();
2318 if (ReleasesToMove.IsTailCallRelease)
2319 Call->setTailCall();
2321 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2322 "At insertion point: " << *InsertPt << "\n");
2325 // Delete the original retain and release calls.
2326 for (SmallPtrSet<Instruction *, 2>::const_iterator
2327 AI = RetainsToMove.Calls.begin(),
2328 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2329 Instruction *OrigRetain = *AI;
2330 Retains.blot(OrigRetain);
2331 DeadInsts.push_back(OrigRetain);
2332 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
2334 for (SmallPtrSet<Instruction *, 2>::const_iterator
2335 AI = ReleasesToMove.Calls.begin(),
2336 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2337 Instruction *OrigRelease = *AI;
2338 Releases.erase(OrigRelease);
2339 DeadInsts.push_back(OrigRelease);
2340 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
2346 ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2348 MapVector<Value *, RRInfo> &Retains,
2349 DenseMap<Value *, RRInfo> &Releases,
2351 SmallVector<Instruction *, 4> &NewRetains,
2352 SmallVector<Instruction *, 4> &NewReleases,
2353 SmallVector<Instruction *, 8> &DeadInsts,
2354 RRInfo &RetainsToMove,
2355 RRInfo &ReleasesToMove,
2358 bool &AnyPairsCompletelyEliminated) {
2359 // If a pair happens in a region where it is known that the reference count
2360 // is already incremented, we can similarly ignore possible decrements.
2361 bool KnownSafeTD = true, KnownSafeBU = true;
2363 // Connect the dots between the top-down-collected RetainsToMove and
2364 // bottom-up-collected ReleasesToMove to form sets of related calls.
2365 // This is an iterative process so that we connect multiple releases
2366 // to multiple retains if needed.
2367 unsigned OldDelta = 0;
2368 unsigned NewDelta = 0;
2369 unsigned OldCount = 0;
2370 unsigned NewCount = 0;
2371 bool FirstRelease = true;
2373 for (SmallVectorImpl<Instruction *>::const_iterator
2374 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2375 Instruction *NewRetain = *NI;
2376 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2377 assert(It != Retains.end());
2378 const RRInfo &NewRetainRRI = It->second;
2379 KnownSafeTD &= NewRetainRRI.KnownSafe;
2380 for (SmallPtrSet<Instruction *, 2>::const_iterator
2381 LI = NewRetainRRI.Calls.begin(),
2382 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2383 Instruction *NewRetainRelease = *LI;
2384 DenseMap<Value *, RRInfo>::const_iterator Jt =
2385 Releases.find(NewRetainRelease);
2386 if (Jt == Releases.end())
2388 const RRInfo &NewRetainReleaseRRI = Jt->second;
2389 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2390 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2392 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2394 // Merge the ReleaseMetadata and IsTailCallRelease values.
2396 ReleasesToMove.ReleaseMetadata =
2397 NewRetainReleaseRRI.ReleaseMetadata;
2398 ReleasesToMove.IsTailCallRelease =
2399 NewRetainReleaseRRI.IsTailCallRelease;
2400 FirstRelease = false;
2402 if (ReleasesToMove.ReleaseMetadata !=
2403 NewRetainReleaseRRI.ReleaseMetadata)
2404 ReleasesToMove.ReleaseMetadata = 0;
2405 if (ReleasesToMove.IsTailCallRelease !=
2406 NewRetainReleaseRRI.IsTailCallRelease)
2407 ReleasesToMove.IsTailCallRelease = false;
2410 // Collect the optimal insertion points.
2412 for (SmallPtrSet<Instruction *, 2>::const_iterator
2413 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2414 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2416 Instruction *RIP = *RI;
2417 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2418 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2420 NewReleases.push_back(NewRetainRelease);
2425 if (NewReleases.empty()) break;
2427 // Back the other way.
2428 for (SmallVectorImpl<Instruction *>::const_iterator
2429 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2430 Instruction *NewRelease = *NI;
2431 DenseMap<Value *, RRInfo>::const_iterator It =
2432 Releases.find(NewRelease);
2433 assert(It != Releases.end());
2434 const RRInfo &NewReleaseRRI = It->second;
2435 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2436 for (SmallPtrSet<Instruction *, 2>::const_iterator
2437 LI = NewReleaseRRI.Calls.begin(),
2438 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2439 Instruction *NewReleaseRetain = *LI;
2440 MapVector<Value *, RRInfo>::const_iterator Jt =
2441 Retains.find(NewReleaseRetain);
2442 if (Jt == Retains.end())
2444 const RRInfo &NewReleaseRetainRRI = Jt->second;
2445 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2446 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2447 unsigned PathCount =
2448 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2449 OldDelta += PathCount;
2450 OldCount += PathCount;
2452 // Collect the optimal insertion points.
2454 for (SmallPtrSet<Instruction *, 2>::const_iterator
2455 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2456 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2458 Instruction *RIP = *RI;
2459 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2460 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2461 NewDelta += PathCount;
2462 NewCount += PathCount;
2465 NewRetains.push_back(NewReleaseRetain);
2469 NewReleases.clear();
2470 if (NewRetains.empty()) break;
2473 // If the pointer is known incremented or nested, we can safely delete the
2474 // pair regardless of what's between them.
2475 if (KnownSafeTD || KnownSafeBU) {
2476 RetainsToMove.ReverseInsertPts.clear();
2477 ReleasesToMove.ReverseInsertPts.clear();
2480 // Determine whether the new insertion points we computed preserve the
2481 // balance of retain and release calls through the program.
2482 // TODO: If the fully aggressive solution isn't valid, try to find a
2483 // less aggressive solution which is.
2488 // Determine whether the original call points are balanced in the retain and
2489 // release calls through the program. If not, conservatively don't touch
2491 // TODO: It's theoretically possible to do code motion in this case, as
2492 // long as the existing imbalances are maintained.
2497 assert(OldCount != 0 && "Unreachable code?");
2498 NumRRs += OldCount - NewCount;
2499 // Set to true if we completely removed any RR pairs.
2500 AnyPairsCompletelyEliminated = NewCount == 0;
2502 // We can move calls!
2506 /// Identify pairings between the retains and releases, and delete and/or move
2509 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2511 MapVector<Value *, RRInfo> &Retains,
2512 DenseMap<Value *, RRInfo> &Releases,
2514 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2516 bool AnyPairsCompletelyEliminated = false;
2517 RRInfo RetainsToMove;
2518 RRInfo ReleasesToMove;
2519 SmallVector<Instruction *, 4> NewRetains;
2520 SmallVector<Instruction *, 4> NewReleases;
2521 SmallVector<Instruction *, 8> DeadInsts;
2523 // Visit each retain.
2524 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2525 E = Retains.end(); I != E; ++I) {
2526 Value *V = I->first;
2527 if (!V) continue; // blotted
2529 Instruction *Retain = cast<Instruction>(V);
2531 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
2533 Value *Arg = GetObjCArg(Retain);
2535 // If the object being released is in static or stack storage, we know it's
2536 // not being managed by ObjC reference counting, so we can delete pairs
2537 // regardless of what possible decrements or uses lie between them.
2538 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
2540 // A constant pointer can't be pointing to an object on the heap. It may
2541 // be reference-counted, but it won't be deleted.
2542 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2543 if (const GlobalVariable *GV =
2544 dyn_cast<GlobalVariable>(
2545 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2546 if (GV->isConstant())
2549 // Connect the dots between the top-down-collected RetainsToMove and
2550 // bottom-up-collected ReleasesToMove to form sets of related calls.
2551 NewRetains.push_back(Retain);
2552 bool PerformMoveCalls =
2553 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2554 NewReleases, DeadInsts, RetainsToMove,
2555 ReleasesToMove, Arg, KnownSafe,
2556 AnyPairsCompletelyEliminated);
2558 #ifdef ARC_ANNOTATIONS
2559 // Do not move calls if ARC annotations are requested. If we were to move
2560 // calls in this case, we would not be able
2561 PerformMoveCalls = PerformMoveCalls && !EnableARCAnnotations;
2562 #endif // ARC_ANNOTATIONS
2564 if (PerformMoveCalls) {
2565 // Ok, everything checks out and we're all set. Let's move/delete some
2567 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2568 Retains, Releases, DeadInsts, M);
2571 // Clean up state for next retain.
2572 NewReleases.clear();
2574 RetainsToMove.clear();
2575 ReleasesToMove.clear();
2578 // Now that we're done moving everything, we can delete the newly dead
2579 // instructions, as we no longer need them as insert points.
2580 while (!DeadInsts.empty())
2581 EraseInstruction(DeadInsts.pop_back_val());
2583 return AnyPairsCompletelyEliminated;
2586 /// Weak pointer optimizations.
2587 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2588 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
2590 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2591 // itself because it uses AliasAnalysis and we need to do provenance
2593 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2594 Instruction *Inst = &*I++;
2596 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
2598 InstructionClass Class = GetBasicInstructionClass(Inst);
2599 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2602 // Delete objc_loadWeak calls with no users.
2603 if (Class == IC_LoadWeak && Inst->use_empty()) {
2604 Inst->eraseFromParent();
2608 // TODO: For now, just look for an earlier available version of this value
2609 // within the same block. Theoretically, we could do memdep-style non-local
2610 // analysis too, but that would want caching. A better approach would be to
2611 // use the technique that EarlyCSE uses.
2612 inst_iterator Current = llvm::prior(I);
2613 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2614 for (BasicBlock::iterator B = CurrentBB->begin(),
2615 J = Current.getInstructionIterator();
2617 Instruction *EarlierInst = &*llvm::prior(J);
2618 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2619 switch (EarlierClass) {
2621 case IC_LoadWeakRetained: {
2622 // If this is loading from the same pointer, replace this load's value
2624 CallInst *Call = cast<CallInst>(Inst);
2625 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2626 Value *Arg = Call->getArgOperand(0);
2627 Value *EarlierArg = EarlierCall->getArgOperand(0);
2628 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2629 case AliasAnalysis::MustAlias:
2631 // If the load has a builtin retain, insert a plain retain for it.
2632 if (Class == IC_LoadWeakRetained) {
2634 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2638 // Zap the fully redundant load.
2639 Call->replaceAllUsesWith(EarlierCall);
2640 Call->eraseFromParent();
2642 case AliasAnalysis::MayAlias:
2643 case AliasAnalysis::PartialAlias:
2645 case AliasAnalysis::NoAlias:
2652 // If this is storing to the same pointer and has the same size etc.
2653 // replace this load's value with the stored value.
2654 CallInst *Call = cast<CallInst>(Inst);
2655 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2656 Value *Arg = Call->getArgOperand(0);
2657 Value *EarlierArg = EarlierCall->getArgOperand(0);
2658 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2659 case AliasAnalysis::MustAlias:
2661 // If the load has a builtin retain, insert a plain retain for it.
2662 if (Class == IC_LoadWeakRetained) {
2664 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2668 // Zap the fully redundant load.
2669 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2670 Call->eraseFromParent();
2672 case AliasAnalysis::MayAlias:
2673 case AliasAnalysis::PartialAlias:
2675 case AliasAnalysis::NoAlias:
2682 // TOOD: Grab the copied value.
2684 case IC_AutoreleasepoolPush:
2686 case IC_IntrinsicUser:
2688 // Weak pointers are only modified through the weak entry points
2689 // (and arbitrary calls, which could call the weak entry points).
2692 // Anything else could modify the weak pointer.
2699 // Then, for each destroyWeak with an alloca operand, check to see if
2700 // the alloca and all its users can be zapped.
2701 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2702 Instruction *Inst = &*I++;
2703 InstructionClass Class = GetBasicInstructionClass(Inst);
2704 if (Class != IC_DestroyWeak)
2707 CallInst *Call = cast<CallInst>(Inst);
2708 Value *Arg = Call->getArgOperand(0);
2709 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2710 for (Value::use_iterator UI = Alloca->use_begin(),
2711 UE = Alloca->use_end(); UI != UE; ++UI) {
2712 const Instruction *UserInst = cast<Instruction>(*UI);
2713 switch (GetBasicInstructionClass(UserInst)) {
2716 case IC_DestroyWeak:
2723 for (Value::use_iterator UI = Alloca->use_begin(),
2724 UE = Alloca->use_end(); UI != UE; ) {
2725 CallInst *UserInst = cast<CallInst>(*UI++);
2726 switch (GetBasicInstructionClass(UserInst)) {
2729 // These functions return their second argument.
2730 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2732 case IC_DestroyWeak:
2736 llvm_unreachable("alloca really is used!");
2738 UserInst->eraseFromParent();
2740 Alloca->eraseFromParent();
2746 /// Identify program paths which execute sequences of retains and releases which
2747 /// can be eliminated.
2748 bool ObjCARCOpt::OptimizeSequences(Function &F) {
2749 /// Releases, Retains - These are used to store the results of the main flow
2750 /// analysis. These use Value* as the key instead of Instruction* so that the
2751 /// map stays valid when we get around to rewriting code and calls get
2752 /// replaced by arguments.
2753 DenseMap<Value *, RRInfo> Releases;
2754 MapVector<Value *, RRInfo> Retains;
2756 /// This is used during the traversal of the function to track the
2757 /// states for each identified object at each block.
2758 DenseMap<const BasicBlock *, BBState> BBStates;
2760 // Analyze the CFG of the function, and all instructions.
2761 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2764 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
2768 /// Check if there is a dependent call earlier that does not have anything in
2769 /// between the Retain and the call that can affect the reference count of their
2770 /// shared pointer argument. Note that Retain need not be in BB.
2772 HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2773 SmallPtrSet<Instruction *, 4> &DepInsts,
2774 SmallPtrSet<const BasicBlock *, 4> &Visited,
2775 ProvenanceAnalysis &PA) {
2776 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2777 DepInsts, Visited, PA);
2778 if (DepInsts.size() != 1)
2782 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2784 // Check that the pointer is the return value of the call.
2785 if (!Call || Arg != Call)
2788 // Check that the call is a regular call.
2789 InstructionClass Class = GetBasicInstructionClass(Call);
2790 if (Class != IC_CallOrUser && Class != IC_Call)
2796 /// Find a dependent retain that precedes the given autorelease for which there
2797 /// is nothing in between the two instructions that can affect the ref count of
2800 FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2801 Instruction *Autorelease,
2802 SmallPtrSet<Instruction *, 4> &DepInsts,
2803 SmallPtrSet<const BasicBlock *, 4> &Visited,
2804 ProvenanceAnalysis &PA) {
2805 FindDependencies(CanChangeRetainCount, Arg,
2806 BB, Autorelease, DepInsts, Visited, PA);
2807 if (DepInsts.size() != 1)
2811 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2813 // Check that we found a retain with the same argument.
2815 !IsRetain(GetBasicInstructionClass(Retain)) ||
2816 GetObjCArg(Retain) != Arg) {
2823 /// Look for an ``autorelease'' instruction dependent on Arg such that there are
2824 /// no instructions dependent on Arg that need a positive ref count in between
2825 /// the autorelease and the ret.
2827 FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
2829 SmallPtrSet<Instruction *, 4> &DepInsts,
2830 SmallPtrSet<const BasicBlock *, 4> &V,
2831 ProvenanceAnalysis &PA) {
2832 FindDependencies(NeedsPositiveRetainCount, Arg,
2833 BB, Ret, DepInsts, V, PA);
2834 if (DepInsts.size() != 1)
2837 CallInst *Autorelease =
2838 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2841 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
2842 if (!IsAutorelease(AutoreleaseClass))
2844 if (GetObjCArg(Autorelease) != Arg)
2850 /// Look for this pattern:
2852 /// %call = call i8* @something(...)
2853 /// %2 = call i8* @objc_retain(i8* %call)
2854 /// %3 = call i8* @objc_autorelease(i8* %2)
2857 /// And delete the retain and autorelease.
2858 void ObjCARCOpt::OptimizeReturns(Function &F) {
2859 if (!F.getReturnType()->isPointerTy())
2862 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
2864 SmallPtrSet<Instruction *, 4> DependingInstructions;
2865 SmallPtrSet<const BasicBlock *, 4> Visited;
2866 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2867 BasicBlock *BB = FI;
2868 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
2870 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
2875 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
2877 // Look for an ``autorelease'' instruction that is a predecssor of Ret and
2878 // dependent on Arg such that there are no instructions dependent on Arg
2879 // that need a positive ref count in between the autorelease and Ret.
2880 CallInst *Autorelease =
2881 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
2882 DependingInstructions, Visited,
2885 DependingInstructions.clear();
2889 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
2890 DependingInstructions, Visited, PA);
2892 DependingInstructions.clear();
2895 // Check that there is nothing that can affect the reference count
2896 // between the retain and the call. Note that Retain need not be in BB.
2897 if (HasSafePathToPredecessorCall(Arg, Retain, DependingInstructions,
2899 // If so, we can zap the retain and autorelease.
2902 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
2903 << *Autorelease << "\n");
2904 EraseInstruction(Retain);
2905 EraseInstruction(Autorelease);
2910 DependingInstructions.clear();
2915 bool ObjCARCOpt::doInitialization(Module &M) {
2919 // If nothing in the Module uses ARC, don't do anything.
2920 Run = ModuleHasARC(M);
2924 // Identify the imprecise release metadata kind.
2925 ImpreciseReleaseMDKind =
2926 M.getContext().getMDKindID("clang.imprecise_release");
2927 CopyOnEscapeMDKind =
2928 M.getContext().getMDKindID("clang.arc.copy_on_escape");
2929 NoObjCARCExceptionsMDKind =
2930 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
2931 #ifdef ARC_ANNOTATIONS
2932 ARCAnnotationBottomUpMDKind =
2933 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
2934 ARCAnnotationTopDownMDKind =
2935 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
2936 ARCAnnotationProvenanceSourceMDKind =
2937 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
2938 #endif // ARC_ANNOTATIONS
2940 // Intuitively, objc_retain and others are nocapture, however in practice
2941 // they are not, because they return their argument value. And objc_release
2942 // calls finalizers which can have arbitrary side effects.
2944 // These are initialized lazily.
2946 AutoreleaseRVCallee = 0;
2949 RetainBlockCallee = 0;
2950 AutoreleaseCallee = 0;
2955 bool ObjCARCOpt::runOnFunction(Function &F) {
2959 // If nothing in the Module uses ARC, don't do anything.
2965 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
2968 PA.setAA(&getAnalysis<AliasAnalysis>());
2970 // This pass performs several distinct transformations. As a compile-time aid
2971 // when compiling code that isn't ObjC, skip these if the relevant ObjC
2972 // library functions aren't declared.
2974 // Preliminary optimizations. This also computs UsedInThisFunction.
2975 OptimizeIndividualCalls(F);
2977 // Optimizations for weak pointers.
2978 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
2979 (1 << IC_LoadWeakRetained) |
2980 (1 << IC_StoreWeak) |
2981 (1 << IC_InitWeak) |
2982 (1 << IC_CopyWeak) |
2983 (1 << IC_MoveWeak) |
2984 (1 << IC_DestroyWeak)))
2985 OptimizeWeakCalls(F);
2987 // Optimizations for retain+release pairs.
2988 if (UsedInThisFunction & ((1 << IC_Retain) |
2989 (1 << IC_RetainRV) |
2990 (1 << IC_RetainBlock)))
2991 if (UsedInThisFunction & (1 << IC_Release))
2992 // Run OptimizeSequences until it either stops making changes or
2993 // no retain+release pair nesting is detected.
2994 while (OptimizeSequences(F)) {}
2996 // Optimizations if objc_autorelease is used.
2997 if (UsedInThisFunction & ((1 << IC_Autorelease) |
2998 (1 << IC_AutoreleaseRV)))
3001 DEBUG(dbgs() << "\n");
3006 void ObjCARCOpt::releaseMemory() {