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 /// reverse 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) {}
412 bool IsTrackingImpreciseReleases() {
413 return ReleaseMetadata != 0;
418 void RRInfo::clear() {
420 IsTailCallRelease = false;
423 ReverseInsertPts.clear();
427 /// \brief This class summarizes several per-pointer runtime properties which
428 /// are propogated through the flow graph.
430 /// True if the reference count is known to be incremented.
431 bool KnownPositiveRefCount;
433 /// True if we've seen an opportunity for partial RR elimination, such as
434 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
437 /// The current position in the sequence.
441 /// Unidirectional information about the current sequence.
443 /// TODO: Encapsulate this better.
446 PtrState() : KnownPositiveRefCount(false), Partial(false),
449 void SetKnownPositiveRefCount() {
450 KnownPositiveRefCount = true;
453 void ClearKnownPositiveRefCount() {
454 KnownPositiveRefCount = false;
457 bool HasKnownPositiveRefCount() const {
458 return KnownPositiveRefCount;
461 void SetSeq(Sequence NewSeq) {
462 DEBUG(dbgs() << "Old: " << Seq << "; New: " << NewSeq << "\n");
466 Sequence GetSeq() const {
470 void ClearSequenceProgress() {
471 ResetSequenceProgress(S_None);
474 void ResetSequenceProgress(Sequence NewSeq) {
475 DEBUG(dbgs() << "Resetting sequence progress.\n");
481 void Merge(const PtrState &Other, bool TopDown);
486 PtrState::Merge(const PtrState &Other, bool TopDown) {
487 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
488 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
490 // If we're not in a sequence (anymore), drop all associated state.
494 } else if (Partial || Other.Partial) {
495 // If we're doing a merge on a path that's previously seen a partial
496 // merge, conservatively drop the sequence, to avoid doing partial
497 // RR elimination. If the branch predicates for the two merge differ,
498 // mixing them is unsafe.
499 ClearSequenceProgress();
501 // Conservatively merge the ReleaseMetadata information.
502 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
503 RRI.ReleaseMetadata = 0;
505 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
506 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
507 Other.RRI.IsTailCallRelease;
508 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
510 // Merge the insert point sets. If there are any differences,
511 // that makes this a partial merge.
512 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
513 for (SmallPtrSet<Instruction *, 2>::const_iterator
514 I = Other.RRI.ReverseInsertPts.begin(),
515 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
516 Partial |= RRI.ReverseInsertPts.insert(*I);
521 /// \brief Per-BasicBlock state.
523 /// The number of unique control paths from the entry which can reach this
525 unsigned TopDownPathCount;
527 /// The number of unique control paths to exits from this block.
528 unsigned BottomUpPathCount;
530 /// A type for PerPtrTopDown and PerPtrBottomUp.
531 typedef MapVector<const Value *, PtrState> MapTy;
533 /// The top-down traversal uses this to record information known about a
534 /// pointer at the bottom of each block.
537 /// The bottom-up traversal uses this to record information known about a
538 /// pointer at the top of each block.
539 MapTy PerPtrBottomUp;
541 /// Effective predecessors of the current block ignoring ignorable edges and
542 /// ignored backedges.
543 SmallVector<BasicBlock *, 2> Preds;
544 /// Effective successors of the current block ignoring ignorable edges and
545 /// ignored backedges.
546 SmallVector<BasicBlock *, 2> Succs;
549 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
551 typedef MapTy::iterator ptr_iterator;
552 typedef MapTy::const_iterator ptr_const_iterator;
554 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
555 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
556 ptr_const_iterator top_down_ptr_begin() const {
557 return PerPtrTopDown.begin();
559 ptr_const_iterator top_down_ptr_end() const {
560 return PerPtrTopDown.end();
563 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
564 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
565 ptr_const_iterator bottom_up_ptr_begin() const {
566 return PerPtrBottomUp.begin();
568 ptr_const_iterator bottom_up_ptr_end() const {
569 return PerPtrBottomUp.end();
572 /// Mark this block as being an entry block, which has one path from the
573 /// entry by definition.
574 void SetAsEntry() { TopDownPathCount = 1; }
576 /// Mark this block as being an exit block, which has one path to an exit by
578 void SetAsExit() { BottomUpPathCount = 1; }
580 PtrState &getPtrTopDownState(const Value *Arg) {
581 return PerPtrTopDown[Arg];
584 PtrState &getPtrBottomUpState(const Value *Arg) {
585 return PerPtrBottomUp[Arg];
588 void clearBottomUpPointers() {
589 PerPtrBottomUp.clear();
592 void clearTopDownPointers() {
593 PerPtrTopDown.clear();
596 void InitFromPred(const BBState &Other);
597 void InitFromSucc(const BBState &Other);
598 void MergePred(const BBState &Other);
599 void MergeSucc(const BBState &Other);
601 /// Return the number of possible unique paths from an entry to an exit
602 /// which pass through this block. This is only valid after both the
603 /// top-down and bottom-up traversals are complete.
604 unsigned GetAllPathCount() const {
605 assert(TopDownPathCount != 0);
606 assert(BottomUpPathCount != 0);
607 return TopDownPathCount * BottomUpPathCount;
610 // Specialized CFG utilities.
611 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
612 edge_iterator pred_begin() { return Preds.begin(); }
613 edge_iterator pred_end() { return Preds.end(); }
614 edge_iterator succ_begin() { return Succs.begin(); }
615 edge_iterator succ_end() { return Succs.end(); }
617 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
618 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
620 bool isExit() const { return Succs.empty(); }
624 void BBState::InitFromPred(const BBState &Other) {
625 PerPtrTopDown = Other.PerPtrTopDown;
626 TopDownPathCount = Other.TopDownPathCount;
629 void BBState::InitFromSucc(const BBState &Other) {
630 PerPtrBottomUp = Other.PerPtrBottomUp;
631 BottomUpPathCount = Other.BottomUpPathCount;
634 /// The top-down traversal uses this to merge information about predecessors to
635 /// form the initial state for a new block.
636 void BBState::MergePred(const BBState &Other) {
637 // Other.TopDownPathCount can be 0, in which case it is either dead or a
638 // loop backedge. Loop backedges are special.
639 TopDownPathCount += Other.TopDownPathCount;
641 // Check for overflow. If we have overflow, fall back to conservative
643 if (TopDownPathCount < Other.TopDownPathCount) {
644 clearTopDownPointers();
648 // For each entry in the other set, if our set has an entry with the same key,
649 // merge the entries. Otherwise, copy the entry and merge it with an empty
651 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
652 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
653 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
654 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
658 // For each entry in our set, if the other set doesn't have an entry with the
659 // same key, force it to merge with an empty entry.
660 for (ptr_iterator MI = top_down_ptr_begin(),
661 ME = top_down_ptr_end(); MI != ME; ++MI)
662 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
663 MI->second.Merge(PtrState(), /*TopDown=*/true);
666 /// The bottom-up traversal uses this to merge information about successors to
667 /// form the initial state for a new block.
668 void BBState::MergeSucc(const BBState &Other) {
669 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
670 // loop backedge. Loop backedges are special.
671 BottomUpPathCount += Other.BottomUpPathCount;
673 // Check for overflow. If we have overflow, fall back to conservative
675 if (BottomUpPathCount < Other.BottomUpPathCount) {
676 clearBottomUpPointers();
680 // For each entry in the other set, if our set has an entry with the
681 // same key, merge the entries. Otherwise, copy the entry and merge
682 // it with an empty entry.
683 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
684 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
685 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
686 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
690 // For each entry in our set, if the other set doesn't have an entry
691 // with the same key, force it to merge with an empty entry.
692 for (ptr_iterator MI = bottom_up_ptr_begin(),
693 ME = bottom_up_ptr_end(); MI != ME; ++MI)
694 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
695 MI->second.Merge(PtrState(), /*TopDown=*/false);
698 // Only enable ARC Annotations if we are building a debug version of
701 #define ARC_ANNOTATIONS
704 // Define some macros along the lines of DEBUG and some helper functions to make
705 // it cleaner to create annotations in the source code and to no-op when not
706 // building in debug mode.
707 #ifdef ARC_ANNOTATIONS
709 #include "llvm/Support/CommandLine.h"
711 /// Enable/disable ARC sequence annotations.
713 EnableARCAnnotations("enable-objc-arc-annotations", cl::init(false),
714 cl::desc("Enable emission of arc data flow analysis "
717 DisableCheckForCFGHazards("disable-objc-arc-checkforcfghazards", cl::init(false),
718 cl::desc("Disable check for cfg hazards when "
720 static cl::opt<std::string>
721 ARCAnnotationTargetIdentifier("objc-arc-annotation-target-identifier",
723 cl::desc("filter out all data flow annotations "
724 "but those that apply to the given "
725 "target llvm identifier."));
727 /// This function appends a unique ARCAnnotationProvenanceSourceMDKind id to an
728 /// instruction so that we can track backwards when post processing via the llvm
729 /// arc annotation processor tool. If the function is an
730 static MDString *AppendMDNodeToSourcePtr(unsigned NodeId,
734 // If pointer is a result of an instruction and it does not have a source
735 // MDNode it, attach a new MDNode onto it. If pointer is a result of
736 // an instruction and does have a source MDNode attached to it, return a
737 // reference to said Node. Otherwise just return 0.
738 if (Instruction *Inst = dyn_cast<Instruction>(Ptr)) {
740 if (!(Node = Inst->getMetadata(NodeId))) {
741 // We do not have any node. Generate and attatch the hash MDString to the
744 // We just use an MDString to ensure that this metadata gets written out
745 // of line at the module level and to provide a very simple format
746 // encoding the information herein. Both of these makes it simpler to
747 // parse the annotations by a simple external program.
749 raw_string_ostream os(Str);
750 os << "(" << Inst->getParent()->getParent()->getName() << ",%"
751 << Inst->getName() << ")";
753 Hash = MDString::get(Inst->getContext(), os.str());
754 Inst->setMetadata(NodeId, MDNode::get(Inst->getContext(),Hash));
756 // We have a node. Grab its hash and return it.
757 assert(Node->getNumOperands() == 1 &&
758 "An ARCAnnotationProvenanceSourceMDKind can only have 1 operand.");
759 Hash = cast<MDString>(Node->getOperand(0));
761 } else if (Argument *Arg = dyn_cast<Argument>(Ptr)) {
763 raw_string_ostream os(str);
764 os << "(" << Arg->getParent()->getName() << ",%" << Arg->getName()
766 Hash = MDString::get(Arg->getContext(), os.str());
772 static std::string SequenceToString(Sequence A) {
774 raw_string_ostream os(str);
779 /// Helper function to change a Sequence into a String object using our overload
780 /// for raw_ostream so we only have printing code in one location.
781 static MDString *SequenceToMDString(LLVMContext &Context,
783 return MDString::get(Context, SequenceToString(A));
786 /// A simple function to generate a MDNode which describes the change in state
787 /// for Value *Ptr caused by Instruction *Inst.
788 static void AppendMDNodeToInstForPtr(unsigned NodeId,
791 MDString *PtrSourceMDNodeID,
795 Value *tmp[3] = {PtrSourceMDNodeID,
796 SequenceToMDString(Inst->getContext(),
798 SequenceToMDString(Inst->getContext(),
800 Node = MDNode::get(Inst->getContext(),
801 ArrayRef<Value*>(tmp, 3));
803 Inst->setMetadata(NodeId, Node);
806 /// Add to the beginning of the basic block llvm.ptr.annotations which show the
807 /// state of a pointer at the entrance to a basic block.
808 static void GenerateARCBBEntranceAnnotation(const char *Name, BasicBlock *BB,
809 Value *Ptr, Sequence Seq) {
810 // If we have a target identifier, make sure that we match it before
812 if(!ARCAnnotationTargetIdentifier.empty() &&
813 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
816 Module *M = BB->getParent()->getParent();
817 LLVMContext &C = M->getContext();
818 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
819 Type *I8XX = PointerType::getUnqual(I8X);
820 Type *Params[] = {I8XX, I8XX};
821 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
822 ArrayRef<Type*>(Params, 2),
824 Constant *Callee = M->getOrInsertFunction(Name, FTy);
826 IRBuilder<> Builder(BB, BB->getFirstInsertionPt());
829 StringRef Tmp = Ptr->getName();
830 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
831 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
833 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
834 cast<Constant>(ActualPtrName), Tmp);
838 std::string SeqStr = SequenceToString(Seq);
839 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
840 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
842 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
843 cast<Constant>(ActualPtrName), SeqStr);
846 Builder.CreateCall2(Callee, PtrName, S);
849 /// Add to the end of the basic block llvm.ptr.annotations which show the state
850 /// of the pointer at the bottom of the basic block.
851 static void GenerateARCBBTerminatorAnnotation(const char *Name, BasicBlock *BB,
852 Value *Ptr, Sequence Seq) {
853 // If we have a target identifier, make sure that we match it before emitting
855 if(!ARCAnnotationTargetIdentifier.empty() &&
856 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
859 Module *M = BB->getParent()->getParent();
860 LLVMContext &C = M->getContext();
861 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
862 Type *I8XX = PointerType::getUnqual(I8X);
863 Type *Params[] = {I8XX, I8XX};
864 FunctionType *FTy = FunctionType::get(Type::getVoidTy(C),
865 ArrayRef<Type*>(Params, 2),
867 Constant *Callee = M->getOrInsertFunction(Name, FTy);
869 IRBuilder<> Builder(BB, llvm::prior(BB->end()));
872 StringRef Tmp = Ptr->getName();
873 if (0 == (PtrName = M->getGlobalVariable(Tmp, true))) {
874 Value *ActualPtrName = Builder.CreateGlobalStringPtr(Tmp,
876 PtrName = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
877 cast<Constant>(ActualPtrName), Tmp);
881 std::string SeqStr = SequenceToString(Seq);
882 if (0 == (S = M->getGlobalVariable(SeqStr, true))) {
883 Value *ActualPtrName = Builder.CreateGlobalStringPtr(SeqStr,
885 S = new GlobalVariable(*M, I8X, true, GlobalVariable::InternalLinkage,
886 cast<Constant>(ActualPtrName), SeqStr);
888 Builder.CreateCall2(Callee, PtrName, S);
891 /// Adds a source annotation to pointer and a state change annotation to Inst
892 /// referencing the source annotation and the old/new state of pointer.
893 static void GenerateARCAnnotation(unsigned InstMDId,
899 if (EnableARCAnnotations) {
900 // If we have a target identifier, make sure that we match it before
901 // emitting an annotation.
902 if(!ARCAnnotationTargetIdentifier.empty() &&
903 !Ptr->getName().equals(ARCAnnotationTargetIdentifier))
906 // First generate the source annotation on our pointer. This will return an
907 // MDString* if Ptr actually comes from an instruction implying we can put
908 // in a source annotation. If AppendMDNodeToSourcePtr returns 0 (i.e. NULL),
909 // then we know that our pointer is from an Argument so we put a reference
910 // to the argument number.
912 // The point of this is to make it easy for the
913 // llvm-arc-annotation-processor tool to cross reference where the source
914 // pointer is in the LLVM IR since the LLVM IR parser does not submit such
915 // information via debug info for backends to use (since why would anyone
916 // need such a thing from LLVM IR besides in non standard cases
918 MDString *SourcePtrMDNode =
919 AppendMDNodeToSourcePtr(PtrMDId, Ptr);
920 AppendMDNodeToInstForPtr(InstMDId, Inst, Ptr, SourcePtrMDNode, OldSeq,
925 // The actual interface for accessing the above functionality is defined via
926 // some simple macros which are defined below. We do this so that the user does
927 // not need to pass in what metadata id is needed resulting in cleaner code and
928 // additionally since it provides an easy way to conditionally no-op all
929 // annotation support in a non-debug build.
931 /// Use this macro to annotate a sequence state change when processing
932 /// instructions bottom up,
933 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new) \
934 GenerateARCAnnotation(ARCAnnotationBottomUpMDKind, \
935 ARCAnnotationProvenanceSourceMDKind, (inst), \
936 const_cast<Value*>(ptr), (old), (new))
937 /// Use this macro to annotate a sequence state change when processing
938 /// instructions top down.
939 #define ANNOTATE_TOPDOWN(inst, ptr, old, new) \
940 GenerateARCAnnotation(ARCAnnotationTopDownMDKind, \
941 ARCAnnotationProvenanceSourceMDKind, (inst), \
942 const_cast<Value*>(ptr), (old), (new))
944 #define ANNOTATE_BB(_states, _bb, _name, _type, _direction) \
946 if (EnableARCAnnotations) { \
947 for(BBState::ptr_const_iterator I = (_states)._direction##_ptr_begin(), \
948 E = (_states)._direction##_ptr_end(); I != E; ++I) { \
949 Value *Ptr = const_cast<Value*>(I->first); \
950 Sequence Seq = I->second.GetSeq(); \
951 GenerateARCBB ## _type ## Annotation(_name, (_bb), Ptr, Seq); \
956 #define ANNOTATE_BOTTOMUP_BBSTART(_states, _basicblock) \
957 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbstart", \
959 #define ANNOTATE_BOTTOMUP_BBEND(_states, _basicblock) \
960 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.bottomup.bbend", \
961 Terminator, bottom_up)
962 #define ANNOTATE_TOPDOWN_BBSTART(_states, _basicblock) \
963 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbstart", \
965 #define ANNOTATE_TOPDOWN_BBEND(_states, _basicblock) \
966 ANNOTATE_BB(_states, _basicblock, "llvm.arc.annotation.topdown.bbend", \
967 Terminator, top_down)
969 #else // !ARC_ANNOTATION
970 // If annotations are off, noop.
971 #define ANNOTATE_BOTTOMUP(inst, ptr, old, new)
972 #define ANNOTATE_TOPDOWN(inst, ptr, old, new)
973 #define ANNOTATE_BOTTOMUP_BBSTART(states, basicblock)
974 #define ANNOTATE_BOTTOMUP_BBEND(states, basicblock)
975 #define ANNOTATE_TOPDOWN_BBSTART(states, basicblock)
976 #define ANNOTATE_TOPDOWN_BBEND(states, basicblock)
977 #endif // !ARC_ANNOTATION
980 /// \brief The main ARC optimization pass.
981 class ObjCARCOpt : public FunctionPass {
983 ProvenanceAnalysis PA;
985 /// A flag indicating whether this optimization pass should run.
988 /// Declarations for ObjC runtime functions, for use in creating calls to
989 /// them. These are initialized lazily to avoid cluttering up the Module
990 /// with unused declarations.
992 /// Declaration for ObjC runtime function
993 /// objc_retainAutoreleasedReturnValue.
994 Constant *RetainRVCallee;
995 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
996 Constant *AutoreleaseRVCallee;
997 /// Declaration for ObjC runtime function objc_release.
998 Constant *ReleaseCallee;
999 /// Declaration for ObjC runtime function objc_retain.
1000 Constant *RetainCallee;
1001 /// Declaration for ObjC runtime function objc_retainBlock.
1002 Constant *RetainBlockCallee;
1003 /// Declaration for ObjC runtime function objc_autorelease.
1004 Constant *AutoreleaseCallee;
1006 /// Flags which determine whether each of the interesting runtine functions
1007 /// is in fact used in the current function.
1008 unsigned UsedInThisFunction;
1010 /// The Metadata Kind for clang.imprecise_release metadata.
1011 unsigned ImpreciseReleaseMDKind;
1013 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
1014 unsigned CopyOnEscapeMDKind;
1016 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
1017 unsigned NoObjCARCExceptionsMDKind;
1019 #ifdef ARC_ANNOTATIONS
1020 /// The Metadata Kind for llvm.arc.annotation.bottomup metadata.
1021 unsigned ARCAnnotationBottomUpMDKind;
1022 /// The Metadata Kind for llvm.arc.annotation.topdown metadata.
1023 unsigned ARCAnnotationTopDownMDKind;
1024 /// The Metadata Kind for llvm.arc.annotation.provenancesource metadata.
1025 unsigned ARCAnnotationProvenanceSourceMDKind;
1026 #endif // ARC_ANNOATIONS
1028 Constant *getRetainRVCallee(Module *M);
1029 Constant *getAutoreleaseRVCallee(Module *M);
1030 Constant *getReleaseCallee(Module *M);
1031 Constant *getRetainCallee(Module *M);
1032 Constant *getRetainBlockCallee(Module *M);
1033 Constant *getAutoreleaseCallee(Module *M);
1035 bool IsRetainBlockOptimizable(const Instruction *Inst);
1037 void OptimizeRetainCall(Function &F, Instruction *Retain);
1038 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1039 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1040 InstructionClass &Class);
1041 bool OptimizeRetainBlockCall(Function &F, Instruction *RetainBlock,
1042 InstructionClass &Class);
1043 void OptimizeIndividualCalls(Function &F);
1045 void CheckForCFGHazards(const BasicBlock *BB,
1046 DenseMap<const BasicBlock *, BBState> &BBStates,
1047 BBState &MyStates) const;
1048 bool VisitInstructionBottomUp(Instruction *Inst,
1050 MapVector<Value *, RRInfo> &Retains,
1052 bool VisitBottomUp(BasicBlock *BB,
1053 DenseMap<const BasicBlock *, BBState> &BBStates,
1054 MapVector<Value *, RRInfo> &Retains);
1055 bool VisitInstructionTopDown(Instruction *Inst,
1056 DenseMap<Value *, RRInfo> &Releases,
1058 bool VisitTopDown(BasicBlock *BB,
1059 DenseMap<const BasicBlock *, BBState> &BBStates,
1060 DenseMap<Value *, RRInfo> &Releases);
1061 bool Visit(Function &F,
1062 DenseMap<const BasicBlock *, BBState> &BBStates,
1063 MapVector<Value *, RRInfo> &Retains,
1064 DenseMap<Value *, RRInfo> &Releases);
1066 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1067 MapVector<Value *, RRInfo> &Retains,
1068 DenseMap<Value *, RRInfo> &Releases,
1069 SmallVectorImpl<Instruction *> &DeadInsts,
1072 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1073 MapVector<Value *, RRInfo> &Retains,
1074 DenseMap<Value *, RRInfo> &Releases,
1076 SmallVector<Instruction *, 4> &NewRetains,
1077 SmallVector<Instruction *, 4> &NewReleases,
1078 SmallVector<Instruction *, 8> &DeadInsts,
1079 RRInfo &RetainsToMove,
1080 RRInfo &ReleasesToMove,
1083 bool &AnyPairsCompletelyEliminated);
1085 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1086 MapVector<Value *, RRInfo> &Retains,
1087 DenseMap<Value *, RRInfo> &Releases,
1090 void OptimizeWeakCalls(Function &F);
1092 bool OptimizeSequences(Function &F);
1094 void OptimizeReturns(Function &F);
1096 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1097 virtual bool doInitialization(Module &M);
1098 virtual bool runOnFunction(Function &F);
1099 virtual void releaseMemory();
1103 ObjCARCOpt() : FunctionPass(ID) {
1104 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1109 char ObjCARCOpt::ID = 0;
1110 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1111 "objc-arc", "ObjC ARC optimization", false, false)
1112 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1113 INITIALIZE_PASS_END(ObjCARCOpt,
1114 "objc-arc", "ObjC ARC optimization", false, false)
1116 Pass *llvm::createObjCARCOptPass() {
1117 return new ObjCARCOpt();
1120 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1121 AU.addRequired<ObjCARCAliasAnalysis>();
1122 AU.addRequired<AliasAnalysis>();
1123 // ARC optimization doesn't currently split critical edges.
1124 AU.setPreservesCFG();
1127 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1128 // Without the magic metadata tag, we have to assume this might be an
1129 // objc_retainBlock call inserted to convert a block pointer to an id,
1130 // in which case it really is needed.
1131 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1134 // If the pointer "escapes" (not including being used in a call),
1135 // the copy may be needed.
1136 if (DoesRetainableObjPtrEscape(Inst))
1139 // Otherwise, it's not needed.
1143 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1144 if (!RetainRVCallee) {
1145 LLVMContext &C = M->getContext();
1146 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1147 Type *Params[] = { I8X };
1148 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1149 AttributeSet Attribute =
1150 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1151 Attribute::NoUnwind);
1153 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1156 return RetainRVCallee;
1159 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1160 if (!AutoreleaseRVCallee) {
1161 LLVMContext &C = M->getContext();
1162 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1163 Type *Params[] = { I8X };
1164 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1165 AttributeSet Attribute =
1166 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1167 Attribute::NoUnwind);
1168 AutoreleaseRVCallee =
1169 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1172 return AutoreleaseRVCallee;
1175 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1176 if (!ReleaseCallee) {
1177 LLVMContext &C = M->getContext();
1178 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1179 AttributeSet Attribute =
1180 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1181 Attribute::NoUnwind);
1183 M->getOrInsertFunction(
1185 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1188 return ReleaseCallee;
1191 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1192 if (!RetainCallee) {
1193 LLVMContext &C = M->getContext();
1194 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1195 AttributeSet Attribute =
1196 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1197 Attribute::NoUnwind);
1199 M->getOrInsertFunction(
1201 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1204 return RetainCallee;
1207 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1208 if (!RetainBlockCallee) {
1209 LLVMContext &C = M->getContext();
1210 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1211 // objc_retainBlock is not nounwind because it calls user copy constructors
1212 // which could theoretically throw.
1214 M->getOrInsertFunction(
1216 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1219 return RetainBlockCallee;
1222 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1223 if (!AutoreleaseCallee) {
1224 LLVMContext &C = M->getContext();
1225 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1226 AttributeSet Attribute =
1227 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1228 Attribute::NoUnwind);
1230 M->getOrInsertFunction(
1232 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1235 return AutoreleaseCallee;
1238 /// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
1241 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
1242 ImmutableCallSite CS(GetObjCArg(Retain));
1243 const Instruction *Call = CS.getInstruction();
1245 if (Call->getParent() != Retain->getParent()) return;
1247 // Check that the call is next to the retain.
1248 BasicBlock::const_iterator I = Call;
1250 while (IsNoopInstruction(I)) ++I;
1254 // Turn it to an objc_retainAutoreleasedReturnValue..
1258 DEBUG(dbgs() << "Transforming objc_retain => "
1259 "objc_retainAutoreleasedReturnValue since the operand is a "
1260 "return value.\nOld: "<< *Retain << "\n");
1262 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
1264 DEBUG(dbgs() << "New: " << *Retain << "\n");
1267 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1268 /// not a return value. Or, if it can be paired with an
1269 /// objc_autoreleaseReturnValue, delete the pair and return true.
1271 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1272 // Check for the argument being from an immediately preceding call or invoke.
1273 const Value *Arg = GetObjCArg(RetainRV);
1274 ImmutableCallSite CS(Arg);
1275 if (const Instruction *Call = CS.getInstruction()) {
1276 if (Call->getParent() == RetainRV->getParent()) {
1277 BasicBlock::const_iterator I = Call;
1279 while (IsNoopInstruction(I)) ++I;
1280 if (&*I == RetainRV)
1282 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
1283 BasicBlock *RetainRVParent = RetainRV->getParent();
1284 if (II->getNormalDest() == RetainRVParent) {
1285 BasicBlock::const_iterator I = RetainRVParent->begin();
1286 while (IsNoopInstruction(I)) ++I;
1287 if (&*I == RetainRV)
1293 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1294 // pointer. In this case, we can delete the pair.
1295 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1297 do --I; while (I != Begin && IsNoopInstruction(I));
1298 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1299 GetObjCArg(I) == Arg) {
1303 DEBUG(dbgs() << "Erasing autoreleaseRV,retainRV pair: " << *I << "\n"
1304 << "Erasing " << *RetainRV << "\n");
1306 EraseInstruction(I);
1307 EraseInstruction(RetainRV);
1312 // Turn it to a plain objc_retain.
1316 DEBUG(dbgs() << "Transforming objc_retainAutoreleasedReturnValue => "
1317 "objc_retain since the operand is not a return value.\n"
1318 "Old = " << *RetainRV << "\n");
1320 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
1322 DEBUG(dbgs() << "New = " << *RetainRV << "\n");
1327 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1328 /// used as a return value.
1330 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1331 InstructionClass &Class) {
1332 // Check for a return of the pointer value.
1333 const Value *Ptr = GetObjCArg(AutoreleaseRV);
1334 SmallVector<const Value *, 2> Users;
1335 Users.push_back(Ptr);
1337 Ptr = Users.pop_back_val();
1338 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1340 const User *I = *UI;
1341 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1343 if (isa<BitCastInst>(I))
1346 } while (!Users.empty());
1351 DEBUG(dbgs() << "Transforming objc_autoreleaseReturnValue => "
1352 "objc_autorelease since its operand is not used as a return "
1354 "Old = " << *AutoreleaseRV << "\n");
1356 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1358 setCalledFunction(getAutoreleaseCallee(F.getParent()));
1359 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
1360 Class = IC_Autorelease;
1362 DEBUG(dbgs() << "New: " << *AutoreleaseRV << "\n");
1366 // \brief Attempt to strength reduce objc_retainBlock calls to objc_retain
1369 // Specifically: If an objc_retainBlock call has the copy_on_escape metadata and
1370 // does not escape (following the rules of block escaping), strength reduce the
1371 // objc_retainBlock to an objc_retain.
1373 // TODO: If an objc_retainBlock call is dominated period by a previous
1374 // objc_retainBlock call, strength reduce the objc_retainBlock to an
1377 ObjCARCOpt::OptimizeRetainBlockCall(Function &F, Instruction *Inst,
1378 InstructionClass &Class) {
1379 assert(GetBasicInstructionClass(Inst) == Class);
1380 assert(IC_RetainBlock == Class);
1382 // If we can not optimize Inst, return false.
1383 if (!IsRetainBlockOptimizable(Inst))
1386 CallInst *RetainBlock = cast<CallInst>(Inst);
1387 RetainBlock->setCalledFunction(getRetainCallee(F.getParent()));
1388 // Remove copy_on_escape metadata.
1389 RetainBlock->setMetadata(CopyOnEscapeMDKind, 0);
1395 /// Visit each call, one at a time, and make simplifications without doing any
1396 /// additional analysis.
1397 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1398 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeIndividualCalls ==\n");
1399 // Reset all the flags in preparation for recomputing them.
1400 UsedInThisFunction = 0;
1402 // Visit all objc_* calls in F.
1403 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1404 Instruction *Inst = &*I++;
1406 InstructionClass Class = GetBasicInstructionClass(Inst);
1408 DEBUG(dbgs() << "Visiting: Class: " << Class << "; " << *Inst << "\n");
1413 // Delete no-op casts. These function calls have special semantics, but
1414 // the semantics are entirely implemented via lowering in the front-end,
1415 // so by the time they reach the optimizer, they are just no-op calls
1416 // which return their argument.
1418 // There are gray areas here, as the ability to cast reference-counted
1419 // pointers to raw void* and back allows code to break ARC assumptions,
1420 // however these are currently considered to be unimportant.
1424 DEBUG(dbgs() << "Erasing no-op cast: " << *Inst << "\n");
1425 EraseInstruction(Inst);
1428 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1431 case IC_LoadWeakRetained:
1433 case IC_DestroyWeak: {
1434 CallInst *CI = cast<CallInst>(Inst);
1435 if (IsNullOrUndef(CI->getArgOperand(0))) {
1437 Type *Ty = CI->getArgOperand(0)->getType();
1438 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1439 Constant::getNullValue(Ty),
1441 llvm::Value *NewValue = UndefValue::get(CI->getType());
1442 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1443 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1444 CI->replaceAllUsesWith(NewValue);
1445 CI->eraseFromParent();
1452 CallInst *CI = cast<CallInst>(Inst);
1453 if (IsNullOrUndef(CI->getArgOperand(0)) ||
1454 IsNullOrUndef(CI->getArgOperand(1))) {
1456 Type *Ty = CI->getArgOperand(0)->getType();
1457 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1458 Constant::getNullValue(Ty),
1461 llvm::Value *NewValue = UndefValue::get(CI->getType());
1462 DEBUG(dbgs() << "A null pointer-to-weak-pointer is undefined behavior."
1463 "\nOld = " << *CI << "\nNew = " << *NewValue << "\n");
1465 CI->replaceAllUsesWith(NewValue);
1466 CI->eraseFromParent();
1471 case IC_RetainBlock:
1472 // If we strength reduce an objc_retainBlock to amn objc_retain, continue
1473 // onto the objc_retain peephole optimizations. Otherwise break.
1474 if (!OptimizeRetainBlockCall(F, Inst, Class))
1478 OptimizeRetainCall(F, Inst);
1481 if (OptimizeRetainRVCall(F, Inst))
1484 case IC_AutoreleaseRV:
1485 OptimizeAutoreleaseRVCall(F, Inst, Class);
1489 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
1490 if (IsAutorelease(Class) && Inst->use_empty()) {
1491 CallInst *Call = cast<CallInst>(Inst);
1492 const Value *Arg = Call->getArgOperand(0);
1493 Arg = FindSingleUseIdentifiedObject(Arg);
1498 // Create the declaration lazily.
1499 LLVMContext &C = Inst->getContext();
1501 CallInst::Create(getReleaseCallee(F.getParent()),
1502 Call->getArgOperand(0), "", Call);
1503 NewCall->setMetadata(ImpreciseReleaseMDKind,
1504 MDNode::get(C, ArrayRef<Value *>()));
1506 DEBUG(dbgs() << "Replacing autorelease{,RV}(x) with objc_release(x) "
1507 "since x is otherwise unused.\nOld: " << *Call << "\nNew: "
1508 << *NewCall << "\n");
1510 EraseInstruction(Call);
1516 // For functions which can never be passed stack arguments, add
1518 if (IsAlwaysTail(Class)) {
1520 DEBUG(dbgs() << "Adding tail keyword to function since it can never be "
1521 "passed stack args: " << *Inst << "\n");
1522 cast<CallInst>(Inst)->setTailCall();
1525 // Ensure that functions that can never have a "tail" keyword due to the
1526 // semantics of ARC truly do not do so.
1527 if (IsNeverTail(Class)) {
1529 DEBUG(dbgs() << "Removing tail keyword from function: " << *Inst <<
1531 cast<CallInst>(Inst)->setTailCall(false);
1534 // Set nounwind as needed.
1535 if (IsNoThrow(Class)) {
1537 DEBUG(dbgs() << "Found no throw class. Setting nounwind on: " << *Inst
1539 cast<CallInst>(Inst)->setDoesNotThrow();
1542 if (!IsNoopOnNull(Class)) {
1543 UsedInThisFunction |= 1 << Class;
1547 const Value *Arg = GetObjCArg(Inst);
1549 // ARC calls with null are no-ops. Delete them.
1550 if (IsNullOrUndef(Arg)) {
1553 DEBUG(dbgs() << "ARC calls with null are no-ops. Erasing: " << *Inst
1555 EraseInstruction(Inst);
1559 // Keep track of which of retain, release, autorelease, and retain_block
1560 // are actually present in this function.
1561 UsedInThisFunction |= 1 << Class;
1563 // If Arg is a PHI, and one or more incoming values to the
1564 // PHI are null, and the call is control-equivalent to the PHI, and there
1565 // are no relevant side effects between the PHI and the call, the call
1566 // could be pushed up to just those paths with non-null incoming values.
1567 // For now, don't bother splitting critical edges for this.
1568 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1569 Worklist.push_back(std::make_pair(Inst, Arg));
1571 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1575 const PHINode *PN = dyn_cast<PHINode>(Arg);
1578 // Determine if the PHI has any null operands, or any incoming
1580 bool HasNull = false;
1581 bool HasCriticalEdges = false;
1582 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1584 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1585 if (IsNullOrUndef(Incoming))
1587 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1588 .getNumSuccessors() != 1) {
1589 HasCriticalEdges = true;
1593 // If we have null operands and no critical edges, optimize.
1594 if (!HasCriticalEdges && HasNull) {
1595 SmallPtrSet<Instruction *, 4> DependingInstructions;
1596 SmallPtrSet<const BasicBlock *, 4> Visited;
1598 // Check that there is nothing that cares about the reference
1599 // count between the call and the phi.
1602 case IC_RetainBlock:
1603 // These can always be moved up.
1606 // These can't be moved across things that care about the retain
1608 FindDependencies(NeedsPositiveRetainCount, Arg,
1609 Inst->getParent(), Inst,
1610 DependingInstructions, Visited, PA);
1612 case IC_Autorelease:
1613 // These can't be moved across autorelease pool scope boundaries.
1614 FindDependencies(AutoreleasePoolBoundary, Arg,
1615 Inst->getParent(), Inst,
1616 DependingInstructions, Visited, PA);
1619 case IC_AutoreleaseRV:
1620 // Don't move these; the RV optimization depends on the autoreleaseRV
1621 // being tail called, and the retainRV being immediately after a call
1622 // (which might still happen if we get lucky with codegen layout, but
1623 // it's not worth taking the chance).
1626 llvm_unreachable("Invalid dependence flavor");
1629 if (DependingInstructions.size() == 1 &&
1630 *DependingInstructions.begin() == PN) {
1633 // Clone the call into each predecessor that has a non-null value.
1634 CallInst *CInst = cast<CallInst>(Inst);
1635 Type *ParamTy = CInst->getArgOperand(0)->getType();
1636 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1638 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1639 if (!IsNullOrUndef(Incoming)) {
1640 CallInst *Clone = cast<CallInst>(CInst->clone());
1641 Value *Op = PN->getIncomingValue(i);
1642 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1643 if (Op->getType() != ParamTy)
1644 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1645 Clone->setArgOperand(0, Op);
1646 Clone->insertBefore(InsertPos);
1648 DEBUG(dbgs() << "Cloning "
1650 "And inserting clone at " << *InsertPos << "\n");
1651 Worklist.push_back(std::make_pair(Clone, Incoming));
1654 // Erase the original call.
1655 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
1656 EraseInstruction(CInst);
1660 } while (!Worklist.empty());
1664 /// If we have a top down pointer in the S_Use state, make sure that there are
1665 /// no CFG hazards by checking the states of various bottom up pointers.
1666 static void CheckForUseCFGHazard(const Sequence SuccSSeq,
1667 const bool SuccSRRIKnownSafe,
1669 bool &SomeSuccHasSame,
1670 bool &AllSuccsHaveSame,
1671 bool &ShouldContinue) {
1673 case S_CanRelease: {
1674 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
1675 S.ClearSequenceProgress();
1678 ShouldContinue = true;
1682 SomeSuccHasSame = true;
1686 case S_MovableRelease:
1687 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1688 AllSuccsHaveSame = false;
1691 llvm_unreachable("bottom-up pointer in retain state!");
1693 llvm_unreachable("This should have been handled earlier.");
1697 /// If we have a Top Down pointer in the S_CanRelease state, make sure that
1698 /// there are no CFG hazards by checking the states of various bottom up
1700 static void CheckForCanReleaseCFGHazard(const Sequence SuccSSeq,
1701 const bool SuccSRRIKnownSafe,
1703 bool &SomeSuccHasSame,
1704 bool &AllSuccsHaveSame) {
1707 SomeSuccHasSame = true;
1711 case S_MovableRelease:
1713 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
1714 AllSuccsHaveSame = false;
1717 llvm_unreachable("bottom-up pointer in retain state!");
1719 llvm_unreachable("This should have been handled earlier.");
1723 /// Check for critical edges, loop boundaries, irreducible control flow, or
1724 /// other CFG structures where moving code across the edge would result in it
1725 /// being executed more.
1727 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
1728 DenseMap<const BasicBlock *, BBState> &BBStates,
1729 BBState &MyStates) const {
1730 // If any top-down local-use or possible-dec has a succ which is earlier in
1731 // the sequence, forget it.
1732 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
1733 E = MyStates.top_down_ptr_end(); I != E; ++I) {
1734 PtrState &S = I->second;
1735 const Sequence Seq = I->second.GetSeq();
1737 // We only care about S_Retain, S_CanRelease, and S_Use.
1741 // Make sure that if extra top down states are added in the future that this
1742 // code is updated to handle it.
1743 assert((Seq == S_Retain || Seq == S_CanRelease || Seq == S_Use) &&
1744 "Unknown top down sequence state.");
1746 const Value *Arg = I->first;
1747 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1748 bool SomeSuccHasSame = false;
1749 bool AllSuccsHaveSame = true;
1751 succ_const_iterator SI(TI), SE(TI, false);
1753 for (; SI != SE; ++SI) {
1754 // If VisitBottomUp has pointer information for this successor, take
1755 // what we know about it.
1756 const DenseMap<const BasicBlock *, BBState>::iterator BBI =
1758 assert(BBI != BBStates.end());
1759 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
1760 const Sequence SuccSSeq = SuccS.GetSeq();
1762 // If bottom up, the pointer is in an S_None state, clear the sequence
1763 // progress since the sequence in the bottom up state finished
1764 // suggesting a mismatch in between retains/releases. This is true for
1765 // all three cases that we are handling here: S_Retain, S_Use, and
1767 if (SuccSSeq == S_None) {
1768 S.ClearSequenceProgress();
1772 // If we have S_Use or S_CanRelease, perform our check for cfg hazard
1774 const bool SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
1776 // *NOTE* We do not use Seq from above here since we are allowing for
1777 // S.GetSeq() to change while we are visiting basic blocks.
1778 switch(S.GetSeq()) {
1780 bool ShouldContinue = false;
1781 CheckForUseCFGHazard(SuccSSeq, SuccSRRIKnownSafe, S,
1782 SomeSuccHasSame, AllSuccsHaveSame,
1788 case S_CanRelease: {
1789 CheckForCanReleaseCFGHazard(SuccSSeq, SuccSRRIKnownSafe,
1798 case S_MovableRelease:
1803 // If the state at the other end of any of the successor edges
1804 // matches the current state, require all edges to match. This
1805 // guards against loops in the middle of a sequence.
1806 if (SomeSuccHasSame && !AllSuccsHaveSame)
1807 S.ClearSequenceProgress();
1812 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
1814 MapVector<Value *, RRInfo> &Retains,
1815 BBState &MyStates) {
1816 bool NestingDetected = false;
1817 InstructionClass Class = GetInstructionClass(Inst);
1818 const Value *Arg = 0;
1820 DEBUG(dbgs() << "Class: " << Class << "\n");
1824 Arg = GetObjCArg(Inst);
1826 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1828 // If we see two releases in a row on the same pointer. If so, make
1829 // a note, and we'll cicle back to revisit it after we've
1830 // hopefully eliminated the second release, which may allow us to
1831 // eliminate the first release too.
1832 // Theoretically we could implement removal of nested retain+release
1833 // pairs by making PtrState hold a stack of states, but this is
1834 // simple and avoids adding overhead for the non-nested case.
1835 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
1836 DEBUG(dbgs() << "Found nested releases (i.e. a release pair)\n");
1837 NestingDetected = true;
1840 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
1841 Sequence NewSeq = ReleaseMetadata ? S_MovableRelease : S_Release;
1842 ANNOTATE_BOTTOMUP(Inst, Arg, S.GetSeq(), NewSeq);
1843 S.ResetSequenceProgress(NewSeq);
1844 S.RRI.ReleaseMetadata = ReleaseMetadata;
1845 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
1846 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
1847 S.RRI.Calls.insert(Inst);
1848 S.SetKnownPositiveRefCount();
1851 case IC_RetainBlock:
1852 // In OptimizeIndividualCalls, we have strength reduced all optimizable
1853 // objc_retainBlocks to objc_retains. Thus at this point any
1854 // objc_retainBlocks that we see are not optimizable.
1858 Arg = GetObjCArg(Inst);
1860 PtrState &S = MyStates.getPtrBottomUpState(Arg);
1861 S.SetKnownPositiveRefCount();
1863 Sequence OldSeq = S.GetSeq();
1867 case S_MovableRelease:
1869 // If OldSeq is not S_Use or OldSeq is S_Use and we are tracking an
1870 // imprecise release, clear our reverse insertion points.
1871 if (OldSeq != S_Use || S.RRI.IsTrackingImpreciseReleases())
1872 S.RRI.ReverseInsertPts.clear();
1875 // Don't do retain+release tracking for IC_RetainRV, because it's
1876 // better to let it remain as the first instruction after a call.
1877 if (Class != IC_RetainRV)
1878 Retains[Inst] = S.RRI;
1879 S.ClearSequenceProgress();
1884 llvm_unreachable("bottom-up pointer in retain state!");
1886 ANNOTATE_BOTTOMUP(Inst, Arg, OldSeq, S.GetSeq());
1887 // A retain moving bottom up can be a use.
1890 case IC_AutoreleasepoolPop:
1891 // Conservatively, clear MyStates for all known pointers.
1892 MyStates.clearBottomUpPointers();
1893 return NestingDetected;
1894 case IC_AutoreleasepoolPush:
1896 // These are irrelevant.
1897 return NestingDetected;
1902 // Consider any other possible effects of this instruction on each
1903 // pointer being tracked.
1904 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
1905 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
1906 const Value *Ptr = MI->first;
1908 continue; // Handled above.
1909 PtrState &S = MI->second;
1910 Sequence Seq = S.GetSeq();
1912 // Check for possible releases.
1913 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
1914 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
1916 S.ClearKnownPositiveRefCount();
1919 S.SetSeq(S_CanRelease);
1920 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S.GetSeq());
1924 case S_MovableRelease:
1929 llvm_unreachable("bottom-up pointer in retain state!");
1933 // Check for possible direct uses.
1936 case S_MovableRelease:
1937 if (CanUse(Inst, Ptr, PA, Class)) {
1938 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
1940 assert(S.RRI.ReverseInsertPts.empty());
1941 // If this is an invoke instruction, we're scanning it as part of
1942 // one of its successor blocks, since we can't insert code after it
1943 // in its own block, and we don't want to split critical edges.
1944 if (isa<InvokeInst>(Inst))
1945 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1947 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
1949 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
1950 } else if (Seq == S_Release && IsUser(Class)) {
1951 DEBUG(dbgs() << "PreciseReleaseUse: Seq: " << Seq << "; " << *Ptr
1953 // Non-movable releases depend on any possible objc pointer use.
1955 ANNOTATE_BOTTOMUP(Inst, Ptr, S_Release, S_Stop);
1956 assert(S.RRI.ReverseInsertPts.empty());
1957 // As above; handle invoke specially.
1958 if (isa<InvokeInst>(Inst))
1959 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
1961 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
1965 if (CanUse(Inst, Ptr, PA, Class)) {
1966 DEBUG(dbgs() << "PreciseStopUse: Seq: " << Seq << "; " << *Ptr
1969 ANNOTATE_BOTTOMUP(Inst, Ptr, Seq, S_Use);
1977 llvm_unreachable("bottom-up pointer in retain state!");
1981 return NestingDetected;
1985 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
1986 DenseMap<const BasicBlock *, BBState> &BBStates,
1987 MapVector<Value *, RRInfo> &Retains) {
1989 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitBottomUp ==\n");
1991 bool NestingDetected = false;
1992 BBState &MyStates = BBStates[BB];
1994 // Merge the states from each successor to compute the initial state
1995 // for the current block.
1996 BBState::edge_iterator SI(MyStates.succ_begin()),
1997 SE(MyStates.succ_end());
1999 const BasicBlock *Succ = *SI;
2000 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2001 assert(I != BBStates.end());
2002 MyStates.InitFromSucc(I->second);
2004 for (; SI != SE; ++SI) {
2006 I = BBStates.find(Succ);
2007 assert(I != BBStates.end());
2008 MyStates.MergeSucc(I->second);
2012 // If ARC Annotations are enabled, output the current state of pointers at the
2013 // bottom of the basic block.
2014 ANNOTATE_BOTTOMUP_BBEND(MyStates, BB);
2016 // Visit all the instructions, bottom-up.
2017 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2018 Instruction *Inst = llvm::prior(I);
2020 // Invoke instructions are visited as part of their successors (below).
2021 if (isa<InvokeInst>(Inst))
2024 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
2026 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2029 // If there's a predecessor with an invoke, visit the invoke as if it were
2030 // part of this block, since we can't insert code after an invoke in its own
2031 // block, and we don't want to split critical edges.
2032 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2033 PE(MyStates.pred_end()); PI != PE; ++PI) {
2034 BasicBlock *Pred = *PI;
2035 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2036 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
2039 // If ARC Annotations are enabled, output the current state of pointers at the
2040 // top of the basic block.
2041 ANNOTATE_BOTTOMUP_BBSTART(MyStates, BB);
2043 return NestingDetected;
2047 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2048 DenseMap<Value *, RRInfo> &Releases,
2049 BBState &MyStates) {
2050 bool NestingDetected = false;
2051 InstructionClass Class = GetInstructionClass(Inst);
2052 const Value *Arg = 0;
2055 case IC_RetainBlock:
2056 // In OptimizeIndividualCalls, we have strength reduced all optimizable
2057 // objc_retainBlocks to objc_retains. Thus at this point any
2058 // objc_retainBlocks that we see are not optimizable.
2062 Arg = GetObjCArg(Inst);
2064 PtrState &S = MyStates.getPtrTopDownState(Arg);
2066 // Don't do retain+release tracking for IC_RetainRV, because it's
2067 // better to let it remain as the first instruction after a call.
2068 if (Class != IC_RetainRV) {
2069 // If we see two retains in a row on the same pointer. If so, make
2070 // a note, and we'll cicle back to revisit it after we've
2071 // hopefully eliminated the second retain, which may allow us to
2072 // eliminate the first retain too.
2073 // Theoretically we could implement removal of nested retain+release
2074 // pairs by making PtrState hold a stack of states, but this is
2075 // simple and avoids adding overhead for the non-nested case.
2076 if (S.GetSeq() == S_Retain)
2077 NestingDetected = true;
2079 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_Retain);
2080 S.ResetSequenceProgress(S_Retain);
2081 S.RRI.KnownSafe = S.HasKnownPositiveRefCount();
2082 S.RRI.Calls.insert(Inst);
2085 S.SetKnownPositiveRefCount();
2087 // A retain can be a potential use; procede to the generic checking
2092 Arg = GetObjCArg(Inst);
2094 PtrState &S = MyStates.getPtrTopDownState(Arg);
2095 S.ClearKnownPositiveRefCount();
2097 Sequence OldSeq = S.GetSeq();
2099 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2104 if (OldSeq == S_Retain || ReleaseMetadata != 0)
2105 S.RRI.ReverseInsertPts.clear();
2108 S.RRI.ReleaseMetadata = ReleaseMetadata;
2109 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2110 Releases[Inst] = S.RRI;
2111 ANNOTATE_TOPDOWN(Inst, Arg, S.GetSeq(), S_None);
2112 S.ClearSequenceProgress();
2118 case S_MovableRelease:
2119 llvm_unreachable("top-down pointer in release state!");
2123 case IC_AutoreleasepoolPop:
2124 // Conservatively, clear MyStates for all known pointers.
2125 MyStates.clearTopDownPointers();
2126 return NestingDetected;
2127 case IC_AutoreleasepoolPush:
2129 // These are irrelevant.
2130 return NestingDetected;
2135 // Consider any other possible effects of this instruction on each
2136 // pointer being tracked.
2137 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2138 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2139 const Value *Ptr = MI->first;
2141 continue; // Handled above.
2142 PtrState &S = MI->second;
2143 Sequence Seq = S.GetSeq();
2145 // Check for possible releases.
2146 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2147 DEBUG(dbgs() << "CanAlterRefCount: Seq: " << Seq << "; " << *Ptr
2149 S.ClearKnownPositiveRefCount();
2152 S.SetSeq(S_CanRelease);
2153 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_CanRelease);
2154 assert(S.RRI.ReverseInsertPts.empty());
2155 S.RRI.ReverseInsertPts.insert(Inst);
2157 // One call can't cause a transition from S_Retain to S_CanRelease
2158 // and S_CanRelease to S_Use. If we've made the first transition,
2167 case S_MovableRelease:
2168 llvm_unreachable("top-down pointer in release state!");
2172 // Check for possible direct uses.
2175 if (CanUse(Inst, Ptr, PA, Class)) {
2176 DEBUG(dbgs() << "CanUse: Seq: " << Seq << "; " << *Ptr
2179 ANNOTATE_TOPDOWN(Inst, Ptr, Seq, S_Use);
2188 case S_MovableRelease:
2189 llvm_unreachable("top-down pointer in release state!");
2193 return NestingDetected;
2197 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2198 DenseMap<const BasicBlock *, BBState> &BBStates,
2199 DenseMap<Value *, RRInfo> &Releases) {
2200 DEBUG(dbgs() << "\n== ObjCARCOpt::VisitTopDown ==\n");
2201 bool NestingDetected = false;
2202 BBState &MyStates = BBStates[BB];
2204 // Merge the states from each predecessor to compute the initial state
2205 // for the current block.
2206 BBState::edge_iterator PI(MyStates.pred_begin()),
2207 PE(MyStates.pred_end());
2209 const BasicBlock *Pred = *PI;
2210 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2211 assert(I != BBStates.end());
2212 MyStates.InitFromPred(I->second);
2214 for (; PI != PE; ++PI) {
2216 I = BBStates.find(Pred);
2217 assert(I != BBStates.end());
2218 MyStates.MergePred(I->second);
2222 // If ARC Annotations are enabled, output the current state of pointers at the
2223 // top of the basic block.
2224 ANNOTATE_TOPDOWN_BBSTART(MyStates, BB);
2226 // Visit all the instructions, top-down.
2227 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2228 Instruction *Inst = I;
2230 DEBUG(dbgs() << "Visiting " << *Inst << "\n");
2232 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
2235 // If ARC Annotations are enabled, output the current state of pointers at the
2236 // bottom of the basic block.
2237 ANNOTATE_TOPDOWN_BBEND(MyStates, BB);
2239 #ifdef ARC_ANNOTATIONS
2240 if (!(EnableARCAnnotations && DisableCheckForCFGHazards))
2242 CheckForCFGHazards(BB, BBStates, MyStates);
2243 return NestingDetected;
2247 ComputePostOrders(Function &F,
2248 SmallVectorImpl<BasicBlock *> &PostOrder,
2249 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2250 unsigned NoObjCARCExceptionsMDKind,
2251 DenseMap<const BasicBlock *, BBState> &BBStates) {
2252 /// The visited set, for doing DFS walks.
2253 SmallPtrSet<BasicBlock *, 16> Visited;
2255 // Do DFS, computing the PostOrder.
2256 SmallPtrSet<BasicBlock *, 16> OnStack;
2257 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2259 // Functions always have exactly one entry block, and we don't have
2260 // any other block that we treat like an entry block.
2261 BasicBlock *EntryBB = &F.getEntryBlock();
2262 BBState &MyStates = BBStates[EntryBB];
2263 MyStates.SetAsEntry();
2264 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2265 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
2266 Visited.insert(EntryBB);
2267 OnStack.insert(EntryBB);
2270 BasicBlock *CurrBB = SuccStack.back().first;
2271 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2272 succ_iterator SE(TI, false);
2274 while (SuccStack.back().second != SE) {
2275 BasicBlock *SuccBB = *SuccStack.back().second++;
2276 if (Visited.insert(SuccBB)) {
2277 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2278 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
2279 BBStates[CurrBB].addSucc(SuccBB);
2280 BBState &SuccStates = BBStates[SuccBB];
2281 SuccStates.addPred(CurrBB);
2282 OnStack.insert(SuccBB);
2286 if (!OnStack.count(SuccBB)) {
2287 BBStates[CurrBB].addSucc(SuccBB);
2288 BBStates[SuccBB].addPred(CurrBB);
2291 OnStack.erase(CurrBB);
2292 PostOrder.push_back(CurrBB);
2293 SuccStack.pop_back();
2294 } while (!SuccStack.empty());
2298 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2299 // Functions may have many exits, and there also blocks which we treat
2300 // as exits due to ignored edges.
2301 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2302 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2303 BasicBlock *ExitBB = I;
2304 BBState &MyStates = BBStates[ExitBB];
2305 if (!MyStates.isExit())
2308 MyStates.SetAsExit();
2310 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
2311 Visited.insert(ExitBB);
2312 while (!PredStack.empty()) {
2313 reverse_dfs_next_succ:
2314 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2315 while (PredStack.back().second != PE) {
2316 BasicBlock *BB = *PredStack.back().second++;
2317 if (Visited.insert(BB)) {
2318 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
2319 goto reverse_dfs_next_succ;
2322 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2327 // Visit the function both top-down and bottom-up.
2329 ObjCARCOpt::Visit(Function &F,
2330 DenseMap<const BasicBlock *, BBState> &BBStates,
2331 MapVector<Value *, RRInfo> &Retains,
2332 DenseMap<Value *, RRInfo> &Releases) {
2334 // Use reverse-postorder traversals, because we magically know that loops
2335 // will be well behaved, i.e. they won't repeatedly call retain on a single
2336 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2337 // class here because we want the reverse-CFG postorder to consider each
2338 // function exit point, and we want to ignore selected cycle edges.
2339 SmallVector<BasicBlock *, 16> PostOrder;
2340 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2341 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2342 NoObjCARCExceptionsMDKind,
2345 // Use reverse-postorder on the reverse CFG for bottom-up.
2346 bool BottomUpNestingDetected = false;
2347 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2348 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2350 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
2352 // Use reverse-postorder for top-down.
2353 bool TopDownNestingDetected = false;
2354 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2355 PostOrder.rbegin(), E = PostOrder.rend();
2357 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
2359 return TopDownNestingDetected && BottomUpNestingDetected;
2362 /// Move the calls in RetainsToMove and ReleasesToMove.
2363 void ObjCARCOpt::MoveCalls(Value *Arg,
2364 RRInfo &RetainsToMove,
2365 RRInfo &ReleasesToMove,
2366 MapVector<Value *, RRInfo> &Retains,
2367 DenseMap<Value *, RRInfo> &Releases,
2368 SmallVectorImpl<Instruction *> &DeadInsts,
2370 Type *ArgTy = Arg->getType();
2371 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2373 DEBUG(dbgs() << "== ObjCARCOpt::MoveCalls ==\n");
2375 // Insert the new retain and release calls.
2376 for (SmallPtrSet<Instruction *, 2>::const_iterator
2377 PI = ReleasesToMove.ReverseInsertPts.begin(),
2378 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2379 Instruction *InsertPt = *PI;
2380 Value *MyArg = ArgTy == ParamTy ? Arg :
2381 new BitCastInst(Arg, ParamTy, "", InsertPt);
2383 CallInst::Create(getRetainCallee(M), MyArg, "", InsertPt);
2384 Call->setDoesNotThrow();
2385 Call->setTailCall();
2387 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2388 "At insertion point: " << *InsertPt << "\n");
2390 for (SmallPtrSet<Instruction *, 2>::const_iterator
2391 PI = RetainsToMove.ReverseInsertPts.begin(),
2392 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2393 Instruction *InsertPt = *PI;
2394 Value *MyArg = ArgTy == ParamTy ? Arg :
2395 new BitCastInst(Arg, ParamTy, "", InsertPt);
2396 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2398 // Attach a clang.imprecise_release metadata tag, if appropriate.
2399 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2400 Call->setMetadata(ImpreciseReleaseMDKind, M);
2401 Call->setDoesNotThrow();
2402 if (ReleasesToMove.IsTailCallRelease)
2403 Call->setTailCall();
2405 DEBUG(dbgs() << "Inserting new Release: " << *Call << "\n"
2406 "At insertion point: " << *InsertPt << "\n");
2409 // Delete the original retain and release calls.
2410 for (SmallPtrSet<Instruction *, 2>::const_iterator
2411 AI = RetainsToMove.Calls.begin(),
2412 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2413 Instruction *OrigRetain = *AI;
2414 Retains.blot(OrigRetain);
2415 DeadInsts.push_back(OrigRetain);
2416 DEBUG(dbgs() << "Deleting retain: " << *OrigRetain << "\n");
2418 for (SmallPtrSet<Instruction *, 2>::const_iterator
2419 AI = ReleasesToMove.Calls.begin(),
2420 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2421 Instruction *OrigRelease = *AI;
2422 Releases.erase(OrigRelease);
2423 DeadInsts.push_back(OrigRelease);
2424 DEBUG(dbgs() << "Deleting release: " << *OrigRelease << "\n");
2430 ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2432 MapVector<Value *, RRInfo> &Retains,
2433 DenseMap<Value *, RRInfo> &Releases,
2435 SmallVector<Instruction *, 4> &NewRetains,
2436 SmallVector<Instruction *, 4> &NewReleases,
2437 SmallVector<Instruction *, 8> &DeadInsts,
2438 RRInfo &RetainsToMove,
2439 RRInfo &ReleasesToMove,
2442 bool &AnyPairsCompletelyEliminated) {
2443 // If a pair happens in a region where it is known that the reference count
2444 // is already incremented, we can similarly ignore possible decrements.
2445 bool KnownSafeTD = true, KnownSafeBU = true;
2447 // Connect the dots between the top-down-collected RetainsToMove and
2448 // bottom-up-collected ReleasesToMove to form sets of related calls.
2449 // This is an iterative process so that we connect multiple releases
2450 // to multiple retains if needed.
2451 unsigned OldDelta = 0;
2452 unsigned NewDelta = 0;
2453 unsigned OldCount = 0;
2454 unsigned NewCount = 0;
2455 bool FirstRelease = true;
2457 for (SmallVectorImpl<Instruction *>::const_iterator
2458 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2459 Instruction *NewRetain = *NI;
2460 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2461 assert(It != Retains.end());
2462 const RRInfo &NewRetainRRI = It->second;
2463 KnownSafeTD &= NewRetainRRI.KnownSafe;
2464 for (SmallPtrSet<Instruction *, 2>::const_iterator
2465 LI = NewRetainRRI.Calls.begin(),
2466 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2467 Instruction *NewRetainRelease = *LI;
2468 DenseMap<Value *, RRInfo>::const_iterator Jt =
2469 Releases.find(NewRetainRelease);
2470 if (Jt == Releases.end())
2472 const RRInfo &NewRetainReleaseRRI = Jt->second;
2473 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2474 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2476 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2478 // Merge the ReleaseMetadata and IsTailCallRelease values.
2480 ReleasesToMove.ReleaseMetadata =
2481 NewRetainReleaseRRI.ReleaseMetadata;
2482 ReleasesToMove.IsTailCallRelease =
2483 NewRetainReleaseRRI.IsTailCallRelease;
2484 FirstRelease = false;
2486 if (ReleasesToMove.ReleaseMetadata !=
2487 NewRetainReleaseRRI.ReleaseMetadata)
2488 ReleasesToMove.ReleaseMetadata = 0;
2489 if (ReleasesToMove.IsTailCallRelease !=
2490 NewRetainReleaseRRI.IsTailCallRelease)
2491 ReleasesToMove.IsTailCallRelease = false;
2494 // Collect the optimal insertion points.
2496 for (SmallPtrSet<Instruction *, 2>::const_iterator
2497 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2498 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2500 Instruction *RIP = *RI;
2501 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2502 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2504 NewReleases.push_back(NewRetainRelease);
2509 if (NewReleases.empty()) break;
2511 // Back the other way.
2512 for (SmallVectorImpl<Instruction *>::const_iterator
2513 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2514 Instruction *NewRelease = *NI;
2515 DenseMap<Value *, RRInfo>::const_iterator It =
2516 Releases.find(NewRelease);
2517 assert(It != Releases.end());
2518 const RRInfo &NewReleaseRRI = It->second;
2519 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2520 for (SmallPtrSet<Instruction *, 2>::const_iterator
2521 LI = NewReleaseRRI.Calls.begin(),
2522 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2523 Instruction *NewReleaseRetain = *LI;
2524 MapVector<Value *, RRInfo>::const_iterator Jt =
2525 Retains.find(NewReleaseRetain);
2526 if (Jt == Retains.end())
2528 const RRInfo &NewReleaseRetainRRI = Jt->second;
2529 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2530 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2531 unsigned PathCount =
2532 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2533 OldDelta += PathCount;
2534 OldCount += PathCount;
2536 // Collect the optimal insertion points.
2538 for (SmallPtrSet<Instruction *, 2>::const_iterator
2539 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2540 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2542 Instruction *RIP = *RI;
2543 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2544 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2545 NewDelta += PathCount;
2546 NewCount += PathCount;
2549 NewRetains.push_back(NewReleaseRetain);
2553 NewReleases.clear();
2554 if (NewRetains.empty()) break;
2557 // If the pointer is known incremented or nested, we can safely delete the
2558 // pair regardless of what's between them.
2559 if (KnownSafeTD || KnownSafeBU) {
2560 RetainsToMove.ReverseInsertPts.clear();
2561 ReleasesToMove.ReverseInsertPts.clear();
2564 // Determine whether the new insertion points we computed preserve the
2565 // balance of retain and release calls through the program.
2566 // TODO: If the fully aggressive solution isn't valid, try to find a
2567 // less aggressive solution which is.
2572 // Determine whether the original call points are balanced in the retain and
2573 // release calls through the program. If not, conservatively don't touch
2575 // TODO: It's theoretically possible to do code motion in this case, as
2576 // long as the existing imbalances are maintained.
2581 assert(OldCount != 0 && "Unreachable code?");
2582 NumRRs += OldCount - NewCount;
2583 // Set to true if we completely removed any RR pairs.
2584 AnyPairsCompletelyEliminated = NewCount == 0;
2586 // We can move calls!
2590 /// Identify pairings between the retains and releases, and delete and/or move
2593 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2595 MapVector<Value *, RRInfo> &Retains,
2596 DenseMap<Value *, RRInfo> &Releases,
2598 DEBUG(dbgs() << "\n== ObjCARCOpt::PerformCodePlacement ==\n");
2600 bool AnyPairsCompletelyEliminated = false;
2601 RRInfo RetainsToMove;
2602 RRInfo ReleasesToMove;
2603 SmallVector<Instruction *, 4> NewRetains;
2604 SmallVector<Instruction *, 4> NewReleases;
2605 SmallVector<Instruction *, 8> DeadInsts;
2607 // Visit each retain.
2608 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2609 E = Retains.end(); I != E; ++I) {
2610 Value *V = I->first;
2611 if (!V) continue; // blotted
2613 Instruction *Retain = cast<Instruction>(V);
2615 DEBUG(dbgs() << "Visiting: " << *Retain << "\n");
2617 Value *Arg = GetObjCArg(Retain);
2619 // If the object being released is in static or stack storage, we know it's
2620 // not being managed by ObjC reference counting, so we can delete pairs
2621 // regardless of what possible decrements or uses lie between them.
2622 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
2624 // A constant pointer can't be pointing to an object on the heap. It may
2625 // be reference-counted, but it won't be deleted.
2626 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2627 if (const GlobalVariable *GV =
2628 dyn_cast<GlobalVariable>(
2629 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2630 if (GV->isConstant())
2633 // Connect the dots between the top-down-collected RetainsToMove and
2634 // bottom-up-collected ReleasesToMove to form sets of related calls.
2635 NewRetains.push_back(Retain);
2636 bool PerformMoveCalls =
2637 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2638 NewReleases, DeadInsts, RetainsToMove,
2639 ReleasesToMove, Arg, KnownSafe,
2640 AnyPairsCompletelyEliminated);
2642 #ifdef ARC_ANNOTATIONS
2643 // Do not move calls if ARC annotations are requested. If we were to move
2644 // calls in this case, we would not be able
2645 PerformMoveCalls = PerformMoveCalls && !EnableARCAnnotations;
2646 #endif // ARC_ANNOTATIONS
2648 if (PerformMoveCalls) {
2649 // Ok, everything checks out and we're all set. Let's move/delete some
2651 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2652 Retains, Releases, DeadInsts, M);
2655 // Clean up state for next retain.
2656 NewReleases.clear();
2658 RetainsToMove.clear();
2659 ReleasesToMove.clear();
2662 // Now that we're done moving everything, we can delete the newly dead
2663 // instructions, as we no longer need them as insert points.
2664 while (!DeadInsts.empty())
2665 EraseInstruction(DeadInsts.pop_back_val());
2667 return AnyPairsCompletelyEliminated;
2670 /// Weak pointer optimizations.
2671 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2672 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeWeakCalls ==\n");
2674 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2675 // itself because it uses AliasAnalysis and we need to do provenance
2677 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2678 Instruction *Inst = &*I++;
2680 DEBUG(dbgs() << "Visiting: " << *Inst << "\n");
2682 InstructionClass Class = GetBasicInstructionClass(Inst);
2683 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2686 // Delete objc_loadWeak calls with no users.
2687 if (Class == IC_LoadWeak && Inst->use_empty()) {
2688 Inst->eraseFromParent();
2692 // TODO: For now, just look for an earlier available version of this value
2693 // within the same block. Theoretically, we could do memdep-style non-local
2694 // analysis too, but that would want caching. A better approach would be to
2695 // use the technique that EarlyCSE uses.
2696 inst_iterator Current = llvm::prior(I);
2697 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2698 for (BasicBlock::iterator B = CurrentBB->begin(),
2699 J = Current.getInstructionIterator();
2701 Instruction *EarlierInst = &*llvm::prior(J);
2702 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2703 switch (EarlierClass) {
2705 case IC_LoadWeakRetained: {
2706 // If this is loading from the same pointer, replace this load's value
2708 CallInst *Call = cast<CallInst>(Inst);
2709 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2710 Value *Arg = Call->getArgOperand(0);
2711 Value *EarlierArg = EarlierCall->getArgOperand(0);
2712 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2713 case AliasAnalysis::MustAlias:
2715 // If the load has a builtin retain, insert a plain retain for it.
2716 if (Class == IC_LoadWeakRetained) {
2718 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2722 // Zap the fully redundant load.
2723 Call->replaceAllUsesWith(EarlierCall);
2724 Call->eraseFromParent();
2726 case AliasAnalysis::MayAlias:
2727 case AliasAnalysis::PartialAlias:
2729 case AliasAnalysis::NoAlias:
2736 // If this is storing to the same pointer and has the same size etc.
2737 // replace this load's value with the stored value.
2738 CallInst *Call = cast<CallInst>(Inst);
2739 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2740 Value *Arg = Call->getArgOperand(0);
2741 Value *EarlierArg = EarlierCall->getArgOperand(0);
2742 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2743 case AliasAnalysis::MustAlias:
2745 // If the load has a builtin retain, insert a plain retain for it.
2746 if (Class == IC_LoadWeakRetained) {
2748 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2752 // Zap the fully redundant load.
2753 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2754 Call->eraseFromParent();
2756 case AliasAnalysis::MayAlias:
2757 case AliasAnalysis::PartialAlias:
2759 case AliasAnalysis::NoAlias:
2766 // TOOD: Grab the copied value.
2768 case IC_AutoreleasepoolPush:
2770 case IC_IntrinsicUser:
2772 // Weak pointers are only modified through the weak entry points
2773 // (and arbitrary calls, which could call the weak entry points).
2776 // Anything else could modify the weak pointer.
2783 // Then, for each destroyWeak with an alloca operand, check to see if
2784 // the alloca and all its users can be zapped.
2785 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2786 Instruction *Inst = &*I++;
2787 InstructionClass Class = GetBasicInstructionClass(Inst);
2788 if (Class != IC_DestroyWeak)
2791 CallInst *Call = cast<CallInst>(Inst);
2792 Value *Arg = Call->getArgOperand(0);
2793 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2794 for (Value::use_iterator UI = Alloca->use_begin(),
2795 UE = Alloca->use_end(); UI != UE; ++UI) {
2796 const Instruction *UserInst = cast<Instruction>(*UI);
2797 switch (GetBasicInstructionClass(UserInst)) {
2800 case IC_DestroyWeak:
2807 for (Value::use_iterator UI = Alloca->use_begin(),
2808 UE = Alloca->use_end(); UI != UE; ) {
2809 CallInst *UserInst = cast<CallInst>(*UI++);
2810 switch (GetBasicInstructionClass(UserInst)) {
2813 // These functions return their second argument.
2814 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
2816 case IC_DestroyWeak:
2820 llvm_unreachable("alloca really is used!");
2822 UserInst->eraseFromParent();
2824 Alloca->eraseFromParent();
2830 /// Identify program paths which execute sequences of retains and releases which
2831 /// can be eliminated.
2832 bool ObjCARCOpt::OptimizeSequences(Function &F) {
2833 /// Releases, Retains - These are used to store the results of the main flow
2834 /// analysis. These use Value* as the key instead of Instruction* so that the
2835 /// map stays valid when we get around to rewriting code and calls get
2836 /// replaced by arguments.
2837 DenseMap<Value *, RRInfo> Releases;
2838 MapVector<Value *, RRInfo> Retains;
2840 /// This is used during the traversal of the function to track the
2841 /// states for each identified object at each block.
2842 DenseMap<const BasicBlock *, BBState> BBStates;
2844 // Analyze the CFG of the function, and all instructions.
2845 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2848 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
2852 /// Check if there is a dependent call earlier that does not have anything in
2853 /// between the Retain and the call that can affect the reference count of their
2854 /// shared pointer argument. Note that Retain need not be in BB.
2856 HasSafePathToPredecessorCall(const Value *Arg, Instruction *Retain,
2857 SmallPtrSet<Instruction *, 4> &DepInsts,
2858 SmallPtrSet<const BasicBlock *, 4> &Visited,
2859 ProvenanceAnalysis &PA) {
2860 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
2861 DepInsts, Visited, PA);
2862 if (DepInsts.size() != 1)
2866 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2868 // Check that the pointer is the return value of the call.
2869 if (!Call || Arg != Call)
2872 // Check that the call is a regular call.
2873 InstructionClass Class = GetBasicInstructionClass(Call);
2874 if (Class != IC_CallOrUser && Class != IC_Call)
2880 /// Find a dependent retain that precedes the given autorelease for which there
2881 /// is nothing in between the two instructions that can affect the ref count of
2884 FindPredecessorRetainWithSafePath(const Value *Arg, BasicBlock *BB,
2885 Instruction *Autorelease,
2886 SmallPtrSet<Instruction *, 4> &DepInsts,
2887 SmallPtrSet<const BasicBlock *, 4> &Visited,
2888 ProvenanceAnalysis &PA) {
2889 FindDependencies(CanChangeRetainCount, Arg,
2890 BB, Autorelease, DepInsts, Visited, PA);
2891 if (DepInsts.size() != 1)
2895 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2897 // Check that we found a retain with the same argument.
2899 !IsRetain(GetBasicInstructionClass(Retain)) ||
2900 GetObjCArg(Retain) != Arg) {
2907 /// Look for an ``autorelease'' instruction dependent on Arg such that there are
2908 /// no instructions dependent on Arg that need a positive ref count in between
2909 /// the autorelease and the ret.
2911 FindPredecessorAutoreleaseWithSafePath(const Value *Arg, BasicBlock *BB,
2913 SmallPtrSet<Instruction *, 4> &DepInsts,
2914 SmallPtrSet<const BasicBlock *, 4> &V,
2915 ProvenanceAnalysis &PA) {
2916 FindDependencies(NeedsPositiveRetainCount, Arg,
2917 BB, Ret, DepInsts, V, PA);
2918 if (DepInsts.size() != 1)
2921 CallInst *Autorelease =
2922 dyn_cast_or_null<CallInst>(*DepInsts.begin());
2925 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
2926 if (!IsAutorelease(AutoreleaseClass))
2928 if (GetObjCArg(Autorelease) != Arg)
2934 /// Look for this pattern:
2936 /// %call = call i8* @something(...)
2937 /// %2 = call i8* @objc_retain(i8* %call)
2938 /// %3 = call i8* @objc_autorelease(i8* %2)
2941 /// And delete the retain and autorelease.
2942 void ObjCARCOpt::OptimizeReturns(Function &F) {
2943 if (!F.getReturnType()->isPointerTy())
2946 DEBUG(dbgs() << "\n== ObjCARCOpt::OptimizeReturns ==\n");
2948 SmallPtrSet<Instruction *, 4> DependingInstructions;
2949 SmallPtrSet<const BasicBlock *, 4> Visited;
2950 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2951 BasicBlock *BB = FI;
2952 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
2954 DEBUG(dbgs() << "Visiting: " << *Ret << "\n");
2959 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
2961 // Look for an ``autorelease'' instruction that is a predecessor of Ret and
2962 // dependent on Arg such that there are no instructions dependent on Arg
2963 // that need a positive ref count in between the autorelease and Ret.
2964 CallInst *Autorelease =
2965 FindPredecessorAutoreleaseWithSafePath(Arg, BB, Ret,
2966 DependingInstructions, Visited,
2968 DependingInstructions.clear();
2975 FindPredecessorRetainWithSafePath(Arg, BB, Autorelease,
2976 DependingInstructions, Visited, PA);
2977 DependingInstructions.clear();
2983 // Check that there is nothing that can affect the reference count
2984 // between the retain and the call. Note that Retain need not be in BB.
2985 bool HasSafePathToCall = HasSafePathToPredecessorCall(Arg, Retain,
2986 DependingInstructions,
2988 DependingInstructions.clear();
2991 if (!HasSafePathToCall)
2994 // If so, we can zap the retain and autorelease.
2997 DEBUG(dbgs() << "Erasing: " << *Retain << "\nErasing: "
2998 << *Autorelease << "\n");
2999 EraseInstruction(Retain);
3000 EraseInstruction(Autorelease);
3004 bool ObjCARCOpt::doInitialization(Module &M) {
3008 // If nothing in the Module uses ARC, don't do anything.
3009 Run = ModuleHasARC(M);
3013 // Identify the imprecise release metadata kind.
3014 ImpreciseReleaseMDKind =
3015 M.getContext().getMDKindID("clang.imprecise_release");
3016 CopyOnEscapeMDKind =
3017 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3018 NoObjCARCExceptionsMDKind =
3019 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3020 #ifdef ARC_ANNOTATIONS
3021 ARCAnnotationBottomUpMDKind =
3022 M.getContext().getMDKindID("llvm.arc.annotation.bottomup");
3023 ARCAnnotationTopDownMDKind =
3024 M.getContext().getMDKindID("llvm.arc.annotation.topdown");
3025 ARCAnnotationProvenanceSourceMDKind =
3026 M.getContext().getMDKindID("llvm.arc.annotation.provenancesource");
3027 #endif // ARC_ANNOTATIONS
3029 // Intuitively, objc_retain and others are nocapture, however in practice
3030 // they are not, because they return their argument value. And objc_release
3031 // calls finalizers which can have arbitrary side effects.
3033 // These are initialized lazily.
3035 AutoreleaseRVCallee = 0;
3038 RetainBlockCallee = 0;
3039 AutoreleaseCallee = 0;
3044 bool ObjCARCOpt::runOnFunction(Function &F) {
3048 // If nothing in the Module uses ARC, don't do anything.
3054 DEBUG(dbgs() << "<<< ObjCARCOpt: Visiting Function: " << F.getName() << " >>>"
3057 PA.setAA(&getAnalysis<AliasAnalysis>());
3059 // This pass performs several distinct transformations. As a compile-time aid
3060 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3061 // library functions aren't declared.
3063 // Preliminary optimizations. This also computs UsedInThisFunction.
3064 OptimizeIndividualCalls(F);
3066 // Optimizations for weak pointers.
3067 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3068 (1 << IC_LoadWeakRetained) |
3069 (1 << IC_StoreWeak) |
3070 (1 << IC_InitWeak) |
3071 (1 << IC_CopyWeak) |
3072 (1 << IC_MoveWeak) |
3073 (1 << IC_DestroyWeak)))
3074 OptimizeWeakCalls(F);
3076 // Optimizations for retain+release pairs.
3077 if (UsedInThisFunction & ((1 << IC_Retain) |
3078 (1 << IC_RetainRV) |
3079 (1 << IC_RetainBlock)))
3080 if (UsedInThisFunction & (1 << IC_Release))
3081 // Run OptimizeSequences until it either stops making changes or
3082 // no retain+release pair nesting is detected.
3083 while (OptimizeSequences(F)) {}
3085 // Optimizations if objc_autorelease is used.
3086 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3087 (1 << IC_AutoreleaseRV)))
3090 DEBUG(dbgs() << "\n");
3095 void ObjCARCOpt::releaseMemory() {