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, pattern-matching and replacement of
17 /// low-level operations into higher-level operations, and numerous minor
20 /// This file also defines a simple ARC-aware AliasAnalysis.
22 /// WARNING: This file knows about certain library functions. It recognizes them
23 /// by name, and hardwires knowledge of their semantics.
25 /// WARNING: This file knows about how certain Objective-C library functions are
26 /// used. Naive LLVM IR transformations which would otherwise be
27 /// behavior-preserving may break these assumptions.
29 //===----------------------------------------------------------------------===//
31 #define DEBUG_TYPE "objc-arc-opts"
33 #include "ObjCARCAliasAnalysis.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/SmallPtrSet.h"
37 #include "llvm/ADT/STLExtras.h"
40 using namespace llvm::objcarc;
42 /// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
46 /// \brief An associative container with fast insertion-order (deterministic)
47 /// iteration over its elements. Plus the special blot operation.
48 template<class KeyT, class ValueT>
50 /// Map keys to indices in Vector.
51 typedef DenseMap<KeyT, size_t> MapTy;
54 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
59 typedef typename VectorTy::iterator iterator;
60 typedef typename VectorTy::const_iterator const_iterator;
61 iterator begin() { return Vector.begin(); }
62 iterator end() { return Vector.end(); }
63 const_iterator begin() const { return Vector.begin(); }
64 const_iterator end() const { return Vector.end(); }
68 assert(Vector.size() >= Map.size()); // May differ due to blotting.
69 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
71 assert(I->second < Vector.size());
72 assert(Vector[I->second].first == I->first);
74 for (typename VectorTy::const_iterator I = Vector.begin(),
75 E = Vector.end(); I != E; ++I)
77 (Map.count(I->first) &&
78 Map[I->first] == size_t(I - Vector.begin())));
82 ValueT &operator[](const KeyT &Arg) {
83 std::pair<typename MapTy::iterator, bool> Pair =
84 Map.insert(std::make_pair(Arg, size_t(0)));
86 size_t Num = Vector.size();
87 Pair.first->second = Num;
88 Vector.push_back(std::make_pair(Arg, ValueT()));
89 return Vector[Num].second;
91 return Vector[Pair.first->second].second;
94 std::pair<iterator, bool>
95 insert(const std::pair<KeyT, ValueT> &InsertPair) {
96 std::pair<typename MapTy::iterator, bool> Pair =
97 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
99 size_t Num = Vector.size();
100 Pair.first->second = Num;
101 Vector.push_back(InsertPair);
102 return std::make_pair(Vector.begin() + Num, true);
104 return std::make_pair(Vector.begin() + Pair.first->second, false);
107 const_iterator find(const KeyT &Key) const {
108 typename MapTy::const_iterator It = Map.find(Key);
109 if (It == Map.end()) return Vector.end();
110 return Vector.begin() + It->second;
113 /// This is similar to erase, but instead of removing the element from the
114 /// vector, it just zeros out the key in the vector. This leaves iterators
115 /// intact, but clients must be prepared for zeroed-out keys when iterating.
116 void blot(const KeyT &Key) {
117 typename MapTy::iterator It = Map.find(Key);
118 if (It == Map.end()) return;
119 Vector[It->second].first = KeyT();
132 /// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
135 #include "llvm/IR/Intrinsics.h"
136 #include "llvm/Support/CallSite.h"
137 #include "llvm/Transforms/Utils/Local.h"
139 /// \brief Test whether the given value is possible a retainable object pointer.
140 static bool IsPotentialRetainableObjPtr(const Value *Op) {
141 // Pointers to static or stack storage are not valid retainable object pointers.
142 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
144 // Special arguments can not be a valid retainable object pointer.
145 if (const Argument *Arg = dyn_cast<Argument>(Op))
146 if (Arg->hasByValAttr() ||
147 Arg->hasNestAttr() ||
148 Arg->hasStructRetAttr())
150 // Only consider values with pointer types.
152 // It seemes intuitive to exclude function pointer types as well, since
153 // functions are never retainable object pointers, however clang occasionally
154 // bitcasts retainable object pointers to function-pointer type temporarily.
155 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
158 // Conservatively assume anything else is a potential retainable object pointer.
162 /// \brief Helper for GetInstructionClass. Determines what kind of construct CS
164 static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
165 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
167 if (IsPotentialRetainableObjPtr(*I))
168 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
170 return CS.onlyReadsMemory() ? IC_None : IC_Call;
173 /// \brief Determine what kind of construct V is.
174 static InstructionClass GetInstructionClass(const Value *V) {
175 if (const Instruction *I = dyn_cast<Instruction>(V)) {
176 // Any instruction other than bitcast and gep with a pointer operand have a
177 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
178 // to a subsequent use, rather than using it themselves, in this sense.
179 // As a short cut, several other opcodes are known to have no pointer
180 // operands of interest. And ret is never followed by a release, so it's
181 // not interesting to examine.
182 switch (I->getOpcode()) {
183 case Instruction::Call: {
184 const CallInst *CI = cast<CallInst>(I);
185 // Check for calls to special functions.
186 if (const Function *F = CI->getCalledFunction()) {
187 InstructionClass Class = GetFunctionClass(F);
188 if (Class != IC_CallOrUser)
191 // None of the intrinsic functions do objc_release. For intrinsics, the
192 // only question is whether or not they may be users.
193 switch (F->getIntrinsicID()) {
194 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
195 case Intrinsic::stacksave: case Intrinsic::stackrestore:
196 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
197 case Intrinsic::objectsize: case Intrinsic::prefetch:
198 case Intrinsic::stackprotector:
199 case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
200 case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
201 case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
202 case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
203 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
204 case Intrinsic::invariant_start: case Intrinsic::invariant_end:
205 // Don't let dbg info affect our results.
206 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
207 // Short cut: Some intrinsics obviously don't use ObjC pointers.
213 return GetCallSiteClass(CI);
215 case Instruction::Invoke:
216 return GetCallSiteClass(cast<InvokeInst>(I));
217 case Instruction::BitCast:
218 case Instruction::GetElementPtr:
219 case Instruction::Select: case Instruction::PHI:
220 case Instruction::Ret: case Instruction::Br:
221 case Instruction::Switch: case Instruction::IndirectBr:
222 case Instruction::Alloca: case Instruction::VAArg:
223 case Instruction::Add: case Instruction::FAdd:
224 case Instruction::Sub: case Instruction::FSub:
225 case Instruction::Mul: case Instruction::FMul:
226 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
227 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
228 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
229 case Instruction::And: case Instruction::Or: case Instruction::Xor:
230 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
231 case Instruction::IntToPtr: case Instruction::FCmp:
232 case Instruction::FPTrunc: case Instruction::FPExt:
233 case Instruction::FPToUI: case Instruction::FPToSI:
234 case Instruction::UIToFP: case Instruction::SIToFP:
235 case Instruction::InsertElement: case Instruction::ExtractElement:
236 case Instruction::ShuffleVector:
237 case Instruction::ExtractValue:
239 case Instruction::ICmp:
240 // Comparing a pointer with null, or any other constant, isn't an
241 // interesting use, because we don't care what the pointer points to, or
242 // about the values of any other dynamic reference-counted pointers.
243 if (IsPotentialRetainableObjPtr(I->getOperand(1)))
247 // For anything else, check all the operands.
248 // Note that this includes both operands of a Store: while the first
249 // operand isn't actually being dereferenced, it is being stored to
250 // memory where we can no longer track who might read it and dereference
251 // it, so we have to consider it potentially used.
252 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
254 if (IsPotentialRetainableObjPtr(*OI))
259 // Otherwise, it's totally inert for ARC purposes.
263 /// \brief Erase the given instruction.
265 /// Many ObjC calls return their argument verbatim,
266 /// so if it's such a call and the return value has users, replace them with the
269 static void EraseInstruction(Instruction *CI) {
270 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
272 bool Unused = CI->use_empty();
275 // Replace the return value with the argument.
276 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
277 "Can't delete non-forwarding instruction with users!");
278 CI->replaceAllUsesWith(OldArg);
281 CI->eraseFromParent();
284 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
287 /// \brief Assuming the given instruction is one of the special calls such as
288 /// objc_retain or objc_release, return the argument value, stripped of no-op
289 /// casts and forwarding calls.
290 static Value *GetObjCArg(Value *Inst) {
291 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
294 /// \brief Return true if this value refers to a distinct and identifiable
297 /// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
298 /// special knowledge of ObjC conventions.
299 static bool IsObjCIdentifiedObject(const Value *V) {
300 // Assume that call results and arguments have their own "provenance".
301 // Constants (including GlobalVariables) and Allocas are never
302 // reference-counted.
303 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
304 isa<Argument>(V) || isa<Constant>(V) ||
308 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
309 const Value *Pointer =
310 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
311 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
312 // A constant pointer can't be pointing to an object on the heap. It may
313 // be reference-counted, but it won't be deleted.
314 if (GV->isConstant())
316 StringRef Name = GV->getName();
317 // These special variables are known to hold values which are not
318 // reference-counted pointers.
319 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
320 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
321 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
322 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
323 Name.startswith("\01l_objc_msgSend_fixup_"))
331 /// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
332 /// as it finds a value with multiple uses.
333 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
334 if (Arg->hasOneUse()) {
335 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
336 return FindSingleUseIdentifiedObject(BC->getOperand(0));
337 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
338 if (GEP->hasAllZeroIndices())
339 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
340 if (IsForwarding(GetBasicInstructionClass(Arg)))
341 return FindSingleUseIdentifiedObject(
342 cast<CallInst>(Arg)->getArgOperand(0));
343 if (!IsObjCIdentifiedObject(Arg))
348 // If we found an identifiable object but it has multiple uses, but they are
349 // trivial uses, we can still consider this to be a single-use value.
350 if (IsObjCIdentifiedObject(Arg)) {
351 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
354 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
364 /// \brief Test whether the given pointer, which is an Objective C block
365 /// pointer, does not "escape".
367 /// This differs from regular escape analysis in that a use as an
368 /// argument to a call is not considered an escape.
370 static bool DoesObjCBlockEscape(const Value *BlockPtr) {
372 DEBUG(dbgs() << "DoesObjCBlockEscape: Target: " << *BlockPtr << "\n");
374 // Walk the def-use chains.
375 SmallVector<const Value *, 4> Worklist;
376 Worklist.push_back(BlockPtr);
378 // Ensure we do not visit any value twice.
379 SmallPtrSet<const Value *, 4> VisitedSet;
382 const Value *V = Worklist.pop_back_val();
384 DEBUG(dbgs() << "DoesObjCBlockEscape: Visiting: " << *V << "\n");
386 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
388 const User *UUser = *UI;
390 DEBUG(dbgs() << "DoesObjCBlockEscape: User: " << *UUser << "\n");
392 // Special - Use by a call (callee or argument) is not considered
394 switch (GetBasicInstructionClass(UUser)) {
399 case IC_AutoreleaseRV: {
400 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies pointer arguments. "
402 // These special functions make copies of their pointer arguments.
407 // Use by an instruction which copies the value is an escape if the
408 // result is an escape.
409 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
410 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
412 if (!VisitedSet.insert(UUser)) {
413 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies value. Escapes "
414 "if result escapes. Adding to list.\n");
415 Worklist.push_back(UUser);
417 DEBUG(dbgs() << "DoesObjCBlockEscape: Already visited node.\n");
421 // Use by a load is not an escape.
422 if (isa<LoadInst>(UUser))
424 // Use by a store is not an escape if the use is the address.
425 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
426 if (V != SI->getValueOperand())
430 // Regular calls and other stuff are not considered escapes.
433 // Otherwise, conservatively assume an escape.
434 DEBUG(dbgs() << "DoesObjCBlockEscape: Assuming block escapes.\n");
437 } while (!Worklist.empty());
440 DEBUG(dbgs() << "DoesObjCBlockEscape: Block does not escape.\n");
446 /// \defgroup ARCOpt ARC Optimization.
449 // TODO: On code like this:
452 // stuff_that_cannot_release()
453 // objc_autorelease(%x)
454 // stuff_that_cannot_release()
456 // stuff_that_cannot_release()
457 // objc_autorelease(%x)
459 // The second retain and autorelease can be deleted.
461 // TODO: It should be possible to delete
462 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
463 // pairs if nothing is actually autoreleased between them. Also, autorelease
464 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
465 // after inlining) can be turned into plain release calls.
467 // TODO: Critical-edge splitting. If the optimial insertion point is
468 // a critical edge, the current algorithm has to fail, because it doesn't
469 // know how to split edges. It should be possible to make the optimizer
470 // think in terms of edges, rather than blocks, and then split critical
473 // TODO: OptimizeSequences could generalized to be Interprocedural.
475 // TODO: Recognize that a bunch of other objc runtime calls have
476 // non-escaping arguments and non-releasing arguments, and may be
477 // non-autoreleasing.
479 // TODO: Sink autorelease calls as far as possible. Unfortunately we
480 // usually can't sink them past other calls, which would be the main
481 // case where it would be useful.
483 // TODO: The pointer returned from objc_loadWeakRetained is retained.
485 // TODO: Delete release+retain pairs (rare).
487 #include "llvm/ADT/SmallPtrSet.h"
488 #include "llvm/ADT/Statistic.h"
489 #include "llvm/IR/LLVMContext.h"
490 #include "llvm/Support/CFG.h"
492 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
493 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
494 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
495 STATISTIC(NumRets, "Number of return value forwarding "
496 "retain+autoreleaes eliminated");
497 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
498 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
501 /// \brief This is similar to BasicAliasAnalysis, and it uses many of the same
502 /// techniques, except it uses special ObjC-specific reasoning about pointer
505 /// In this context ``Provenance'' is defined as the history of an object's
506 /// ownership. Thus ``Provenance Analysis'' is defined by using the notion of
507 /// an ``independent provenance source'' of a pointer to determine whether or
508 /// not two pointers have the same provenance source and thus could
509 /// potentially be related.
510 class ProvenanceAnalysis {
513 typedef std::pair<const Value *, const Value *> ValuePairTy;
514 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
515 CachedResultsTy CachedResults;
517 bool relatedCheck(const Value *A, const Value *B);
518 bool relatedSelect(const SelectInst *A, const Value *B);
519 bool relatedPHI(const PHINode *A, const Value *B);
521 void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
522 ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
525 ProvenanceAnalysis() {}
527 void setAA(AliasAnalysis *aa) { AA = aa; }
529 AliasAnalysis *getAA() const { return AA; }
531 bool related(const Value *A, const Value *B);
534 CachedResults.clear();
539 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
540 // If the values are Selects with the same condition, we can do a more precise
541 // check: just check for relations between the values on corresponding arms.
542 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
543 if (A->getCondition() == SB->getCondition())
544 return related(A->getTrueValue(), SB->getTrueValue()) ||
545 related(A->getFalseValue(), SB->getFalseValue());
547 // Check both arms of the Select node individually.
548 return related(A->getTrueValue(), B) ||
549 related(A->getFalseValue(), B);
552 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
553 // If the values are PHIs in the same block, we can do a more precise as well
554 // as efficient check: just check for relations between the values on
555 // corresponding edges.
556 if (const PHINode *PNB = dyn_cast<PHINode>(B))
557 if (PNB->getParent() == A->getParent()) {
558 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
559 if (related(A->getIncomingValue(i),
560 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
565 // Check each unique source of the PHI node against B.
566 SmallPtrSet<const Value *, 4> UniqueSrc;
567 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
568 const Value *PV1 = A->getIncomingValue(i);
569 if (UniqueSrc.insert(PV1) && related(PV1, B))
573 // All of the arms checked out.
577 /// Test if the value of P, or any value covered by its provenance, is ever
578 /// stored within the function (not counting callees).
579 static bool isStoredObjCPointer(const Value *P) {
580 SmallPtrSet<const Value *, 8> Visited;
581 SmallVector<const Value *, 8> Worklist;
582 Worklist.push_back(P);
585 P = Worklist.pop_back_val();
586 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
588 const User *Ur = *UI;
589 if (isa<StoreInst>(Ur)) {
590 if (UI.getOperandNo() == 0)
591 // The pointer is stored.
593 // The pointed is stored through.
596 if (isa<CallInst>(Ur))
597 // The pointer is passed as an argument, ignore this.
599 if (isa<PtrToIntInst>(P))
602 if (Visited.insert(Ur))
603 Worklist.push_back(Ur);
605 } while (!Worklist.empty());
607 // Everything checked out.
611 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
612 // Skip past provenance pass-throughs.
613 A = GetUnderlyingObjCPtr(A);
614 B = GetUnderlyingObjCPtr(B);
620 // Ask regular AliasAnalysis, for a first approximation.
621 switch (AA->alias(A, B)) {
622 case AliasAnalysis::NoAlias:
624 case AliasAnalysis::MustAlias:
625 case AliasAnalysis::PartialAlias:
627 case AliasAnalysis::MayAlias:
631 bool AIsIdentified = IsObjCIdentifiedObject(A);
632 bool BIsIdentified = IsObjCIdentifiedObject(B);
634 // An ObjC-Identified object can't alias a load if it is never locally stored.
636 // Check for an obvious escape.
637 if (isa<LoadInst>(B))
638 return isStoredObjCPointer(A);
640 // Check for an obvious escape.
641 if (isa<LoadInst>(A))
642 return isStoredObjCPointer(B);
643 // Both pointers are identified and escapes aren't an evident problem.
646 } else if (BIsIdentified) {
647 // Check for an obvious escape.
648 if (isa<LoadInst>(A))
649 return isStoredObjCPointer(B);
652 // Special handling for PHI and Select.
653 if (const PHINode *PN = dyn_cast<PHINode>(A))
654 return relatedPHI(PN, B);
655 if (const PHINode *PN = dyn_cast<PHINode>(B))
656 return relatedPHI(PN, A);
657 if (const SelectInst *S = dyn_cast<SelectInst>(A))
658 return relatedSelect(S, B);
659 if (const SelectInst *S = dyn_cast<SelectInst>(B))
660 return relatedSelect(S, A);
666 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
667 // Begin by inserting a conservative value into the map. If the insertion
668 // fails, we have the answer already. If it succeeds, leave it there until we
669 // compute the real answer to guard against recursive queries.
670 if (A > B) std::swap(A, B);
671 std::pair<CachedResultsTy::iterator, bool> Pair =
672 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
674 return Pair.first->second;
676 bool Result = relatedCheck(A, B);
677 CachedResults[ValuePairTy(A, B)] = Result;
684 /// \brief A sequence of states that a pointer may go through in which an
685 /// objc_retain and objc_release are actually needed.
688 S_Retain, ///< objc_retain(x)
689 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
690 S_Use, ///< any use of x
691 S_Stop, ///< like S_Release, but code motion is stopped
692 S_Release, ///< objc_release(x)
693 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
697 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
701 if (A == S_None || B == S_None)
704 if (A > B) std::swap(A, B);
706 // Choose the side which is further along in the sequence.
707 if ((A == S_Retain || A == S_CanRelease) &&
708 (B == S_CanRelease || B == S_Use))
711 // Choose the side which is further along in the sequence.
712 if ((A == S_Use || A == S_CanRelease) &&
713 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
715 // If both sides are releases, choose the more conservative one.
716 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
718 if (A == S_Release && B == S_MovableRelease)
726 /// \brief Unidirectional information about either a
727 /// retain-decrement-use-release sequence or release-use-decrement-retain
728 /// reverese sequence.
730 /// After an objc_retain, the reference count of the referenced
731 /// object is known to be positive. Similarly, before an objc_release, the
732 /// reference count of the referenced object is known to be positive. If
733 /// there are retain-release pairs in code regions where the retain count
734 /// is known to be positive, they can be eliminated, regardless of any side
735 /// effects between them.
737 /// Also, a retain+release pair nested within another retain+release
738 /// pair all on the known same pointer value can be eliminated, regardless
739 /// of any intervening side effects.
741 /// KnownSafe is true when either of these conditions is satisfied.
744 /// True if the Calls are objc_retainBlock calls (as opposed to objc_retain
748 /// True of the objc_release calls are all marked with the "tail" keyword.
749 bool IsTailCallRelease;
751 /// If the Calls are objc_release calls and they all have a
752 /// clang.imprecise_release tag, this is the metadata tag.
753 MDNode *ReleaseMetadata;
755 /// For a top-down sequence, the set of objc_retains or
756 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
757 SmallPtrSet<Instruction *, 2> Calls;
759 /// The set of optimal insert positions for moving calls in the opposite
761 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
764 KnownSafe(false), IsRetainBlock(false),
765 IsTailCallRelease(false),
766 ReleaseMetadata(0) {}
772 void RRInfo::clear() {
774 IsRetainBlock = false;
775 IsTailCallRelease = false;
778 ReverseInsertPts.clear();
782 /// \brief This class summarizes several per-pointer runtime properties which
783 /// are propogated through the flow graph.
785 /// True if the reference count is known to be incremented.
786 bool KnownPositiveRefCount;
788 /// True of we've seen an opportunity for partial RR elimination, such as
789 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
792 /// The current position in the sequence.
796 /// Unidirectional information about the current sequence.
798 /// TODO: Encapsulate this better.
801 PtrState() : KnownPositiveRefCount(false), Partial(false),
804 void SetKnownPositiveRefCount() {
805 KnownPositiveRefCount = true;
808 void ClearRefCount() {
809 KnownPositiveRefCount = false;
812 bool IsKnownIncremented() const {
813 return KnownPositiveRefCount;
816 void SetSeq(Sequence NewSeq) {
820 Sequence GetSeq() const {
824 void ClearSequenceProgress() {
825 ResetSequenceProgress(S_None);
828 void ResetSequenceProgress(Sequence NewSeq) {
834 void Merge(const PtrState &Other, bool TopDown);
839 PtrState::Merge(const PtrState &Other, bool TopDown) {
840 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
841 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
843 // We can't merge a plain objc_retain with an objc_retainBlock.
844 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
847 // If we're not in a sequence (anymore), drop all associated state.
851 } else if (Partial || Other.Partial) {
852 // If we're doing a merge on a path that's previously seen a partial
853 // merge, conservatively drop the sequence, to avoid doing partial
854 // RR elimination. If the branch predicates for the two merge differ,
855 // mixing them is unsafe.
856 ClearSequenceProgress();
858 // Conservatively merge the ReleaseMetadata information.
859 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
860 RRI.ReleaseMetadata = 0;
862 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
863 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
864 Other.RRI.IsTailCallRelease;
865 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
867 // Merge the insert point sets. If there are any differences,
868 // that makes this a partial merge.
869 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
870 for (SmallPtrSet<Instruction *, 2>::const_iterator
871 I = Other.RRI.ReverseInsertPts.begin(),
872 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
873 Partial |= RRI.ReverseInsertPts.insert(*I);
878 /// \brief Per-BasicBlock state.
880 /// The number of unique control paths from the entry which can reach this
882 unsigned TopDownPathCount;
884 /// The number of unique control paths to exits from this block.
885 unsigned BottomUpPathCount;
887 /// A type for PerPtrTopDown and PerPtrBottomUp.
888 typedef MapVector<const Value *, PtrState> MapTy;
890 /// The top-down traversal uses this to record information known about a
891 /// pointer at the bottom of each block.
894 /// The bottom-up traversal uses this to record information known about a
895 /// pointer at the top of each block.
896 MapTy PerPtrBottomUp;
898 /// Effective predecessors of the current block ignoring ignorable edges and
899 /// ignored backedges.
900 SmallVector<BasicBlock *, 2> Preds;
901 /// Effective successors of the current block ignoring ignorable edges and
902 /// ignored backedges.
903 SmallVector<BasicBlock *, 2> Succs;
906 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
908 typedef MapTy::iterator ptr_iterator;
909 typedef MapTy::const_iterator ptr_const_iterator;
911 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
912 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
913 ptr_const_iterator top_down_ptr_begin() const {
914 return PerPtrTopDown.begin();
916 ptr_const_iterator top_down_ptr_end() const {
917 return PerPtrTopDown.end();
920 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
921 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
922 ptr_const_iterator bottom_up_ptr_begin() const {
923 return PerPtrBottomUp.begin();
925 ptr_const_iterator bottom_up_ptr_end() const {
926 return PerPtrBottomUp.end();
929 /// Mark this block as being an entry block, which has one path from the
930 /// entry by definition.
931 void SetAsEntry() { TopDownPathCount = 1; }
933 /// Mark this block as being an exit block, which has one path to an exit by
935 void SetAsExit() { BottomUpPathCount = 1; }
937 PtrState &getPtrTopDownState(const Value *Arg) {
938 return PerPtrTopDown[Arg];
941 PtrState &getPtrBottomUpState(const Value *Arg) {
942 return PerPtrBottomUp[Arg];
945 void clearBottomUpPointers() {
946 PerPtrBottomUp.clear();
949 void clearTopDownPointers() {
950 PerPtrTopDown.clear();
953 void InitFromPred(const BBState &Other);
954 void InitFromSucc(const BBState &Other);
955 void MergePred(const BBState &Other);
956 void MergeSucc(const BBState &Other);
958 /// Return the number of possible unique paths from an entry to an exit
959 /// which pass through this block. This is only valid after both the
960 /// top-down and bottom-up traversals are complete.
961 unsigned GetAllPathCount() const {
962 assert(TopDownPathCount != 0);
963 assert(BottomUpPathCount != 0);
964 return TopDownPathCount * BottomUpPathCount;
967 // Specialized CFG utilities.
968 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
969 edge_iterator pred_begin() { return Preds.begin(); }
970 edge_iterator pred_end() { return Preds.end(); }
971 edge_iterator succ_begin() { return Succs.begin(); }
972 edge_iterator succ_end() { return Succs.end(); }
974 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
975 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
977 bool isExit() const { return Succs.empty(); }
981 void BBState::InitFromPred(const BBState &Other) {
982 PerPtrTopDown = Other.PerPtrTopDown;
983 TopDownPathCount = Other.TopDownPathCount;
986 void BBState::InitFromSucc(const BBState &Other) {
987 PerPtrBottomUp = Other.PerPtrBottomUp;
988 BottomUpPathCount = Other.BottomUpPathCount;
991 /// The top-down traversal uses this to merge information about predecessors to
992 /// form the initial state for a new block.
993 void BBState::MergePred(const BBState &Other) {
994 // Other.TopDownPathCount can be 0, in which case it is either dead or a
995 // loop backedge. Loop backedges are special.
996 TopDownPathCount += Other.TopDownPathCount;
998 // Check for overflow. If we have overflow, fall back to conservative
1000 if (TopDownPathCount < Other.TopDownPathCount) {
1001 clearTopDownPointers();
1005 // For each entry in the other set, if our set has an entry with the same key,
1006 // merge the entries. Otherwise, copy the entry and merge it with an empty
1008 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1009 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1010 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1011 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1015 // For each entry in our set, if the other set doesn't have an entry with the
1016 // same key, force it to merge with an empty entry.
1017 for (ptr_iterator MI = top_down_ptr_begin(),
1018 ME = top_down_ptr_end(); MI != ME; ++MI)
1019 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1020 MI->second.Merge(PtrState(), /*TopDown=*/true);
1023 /// The bottom-up traversal uses this to merge information about successors to
1024 /// form the initial state for a new block.
1025 void BBState::MergeSucc(const BBState &Other) {
1026 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1027 // loop backedge. Loop backedges are special.
1028 BottomUpPathCount += Other.BottomUpPathCount;
1030 // Check for overflow. If we have overflow, fall back to conservative
1032 if (BottomUpPathCount < Other.BottomUpPathCount) {
1033 clearBottomUpPointers();
1037 // For each entry in the other set, if our set has an entry with the
1038 // same key, merge the entries. Otherwise, copy the entry and merge
1039 // it with an empty entry.
1040 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1041 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1042 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1043 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1047 // For each entry in our set, if the other set doesn't have an entry
1048 // with the same key, force it to merge with an empty entry.
1049 for (ptr_iterator MI = bottom_up_ptr_begin(),
1050 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1051 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1052 MI->second.Merge(PtrState(), /*TopDown=*/false);
1056 /// \brief The main ARC optimization pass.
1057 class ObjCARCOpt : public FunctionPass {
1059 ProvenanceAnalysis PA;
1061 /// A flag indicating whether this optimization pass should run.
1064 /// Declarations for ObjC runtime functions, for use in creating calls to
1065 /// them. These are initialized lazily to avoid cluttering up the Module
1066 /// with unused declarations.
1068 /// Declaration for ObjC runtime function
1069 /// objc_retainAutoreleasedReturnValue.
1070 Constant *RetainRVCallee;
1071 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1072 Constant *AutoreleaseRVCallee;
1073 /// Declaration for ObjC runtime function objc_release.
1074 Constant *ReleaseCallee;
1075 /// Declaration for ObjC runtime function objc_retain.
1076 Constant *RetainCallee;
1077 /// Declaration for ObjC runtime function objc_retainBlock.
1078 Constant *RetainBlockCallee;
1079 /// Declaration for ObjC runtime function objc_autorelease.
1080 Constant *AutoreleaseCallee;
1082 /// Flags which determine whether each of the interesting runtine functions
1083 /// is in fact used in the current function.
1084 unsigned UsedInThisFunction;
1086 /// The Metadata Kind for clang.imprecise_release metadata.
1087 unsigned ImpreciseReleaseMDKind;
1089 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
1090 unsigned CopyOnEscapeMDKind;
1092 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
1093 unsigned NoObjCARCExceptionsMDKind;
1095 Constant *getRetainRVCallee(Module *M);
1096 Constant *getAutoreleaseRVCallee(Module *M);
1097 Constant *getReleaseCallee(Module *M);
1098 Constant *getRetainCallee(Module *M);
1099 Constant *getRetainBlockCallee(Module *M);
1100 Constant *getAutoreleaseCallee(Module *M);
1102 bool IsRetainBlockOptimizable(const Instruction *Inst);
1104 void OptimizeRetainCall(Function &F, Instruction *Retain);
1105 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1106 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1107 InstructionClass &Class);
1108 void OptimizeIndividualCalls(Function &F);
1110 void CheckForCFGHazards(const BasicBlock *BB,
1111 DenseMap<const BasicBlock *, BBState> &BBStates,
1112 BBState &MyStates) const;
1113 bool VisitInstructionBottomUp(Instruction *Inst,
1115 MapVector<Value *, RRInfo> &Retains,
1117 bool VisitBottomUp(BasicBlock *BB,
1118 DenseMap<const BasicBlock *, BBState> &BBStates,
1119 MapVector<Value *, RRInfo> &Retains);
1120 bool VisitInstructionTopDown(Instruction *Inst,
1121 DenseMap<Value *, RRInfo> &Releases,
1123 bool VisitTopDown(BasicBlock *BB,
1124 DenseMap<const BasicBlock *, BBState> &BBStates,
1125 DenseMap<Value *, RRInfo> &Releases);
1126 bool Visit(Function &F,
1127 DenseMap<const BasicBlock *, BBState> &BBStates,
1128 MapVector<Value *, RRInfo> &Retains,
1129 DenseMap<Value *, RRInfo> &Releases);
1131 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1132 MapVector<Value *, RRInfo> &Retains,
1133 DenseMap<Value *, RRInfo> &Releases,
1134 SmallVectorImpl<Instruction *> &DeadInsts,
1137 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1138 MapVector<Value *, RRInfo> &Retains,
1139 DenseMap<Value *, RRInfo> &Releases,
1141 SmallVector<Instruction *, 4> &NewRetains,
1142 SmallVector<Instruction *, 4> &NewReleases,
1143 SmallVector<Instruction *, 8> &DeadInsts,
1144 RRInfo &RetainsToMove,
1145 RRInfo &ReleasesToMove,
1148 bool &AnyPairsCompletelyEliminated);
1150 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1151 MapVector<Value *, RRInfo> &Retains,
1152 DenseMap<Value *, RRInfo> &Releases,
1155 void OptimizeWeakCalls(Function &F);
1157 bool OptimizeSequences(Function &F);
1159 void OptimizeReturns(Function &F);
1161 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1162 virtual bool doInitialization(Module &M);
1163 virtual bool runOnFunction(Function &F);
1164 virtual void releaseMemory();
1168 ObjCARCOpt() : FunctionPass(ID) {
1169 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1174 char ObjCARCOpt::ID = 0;
1175 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1176 "objc-arc", "ObjC ARC optimization", false, false)
1177 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1178 INITIALIZE_PASS_END(ObjCARCOpt,
1179 "objc-arc", "ObjC ARC optimization", false, false)
1181 Pass *llvm::createObjCARCOptPass() {
1182 return new ObjCARCOpt();
1185 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1186 AU.addRequired<ObjCARCAliasAnalysis>();
1187 AU.addRequired<AliasAnalysis>();
1188 // ARC optimization doesn't currently split critical edges.
1189 AU.setPreservesCFG();
1192 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1193 // Without the magic metadata tag, we have to assume this might be an
1194 // objc_retainBlock call inserted to convert a block pointer to an id,
1195 // in which case it really is needed.
1196 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1199 // If the pointer "escapes" (not including being used in a call),
1200 // the copy may be needed.
1201 if (DoesObjCBlockEscape(Inst))
1204 // Otherwise, it's not needed.
1208 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1209 if (!RetainRVCallee) {
1210 LLVMContext &C = M->getContext();
1211 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1212 Type *Params[] = { I8X };
1213 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1214 AttributeSet Attribute =
1215 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1216 Attribute::NoUnwind);
1218 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1221 return RetainRVCallee;
1224 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1225 if (!AutoreleaseRVCallee) {
1226 LLVMContext &C = M->getContext();
1227 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1228 Type *Params[] = { I8X };
1229 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1230 AttributeSet Attribute =
1231 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1232 Attribute::NoUnwind);
1233 AutoreleaseRVCallee =
1234 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1237 return AutoreleaseRVCallee;
1240 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1241 if (!ReleaseCallee) {
1242 LLVMContext &C = M->getContext();
1243 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1244 AttributeSet Attribute =
1245 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1246 Attribute::NoUnwind);
1248 M->getOrInsertFunction(
1250 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1253 return ReleaseCallee;
1256 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1257 if (!RetainCallee) {
1258 LLVMContext &C = M->getContext();
1259 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1260 AttributeSet Attribute =
1261 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1262 Attribute::NoUnwind);
1264 M->getOrInsertFunction(
1266 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1269 return RetainCallee;
1272 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1273 if (!RetainBlockCallee) {
1274 LLVMContext &C = M->getContext();
1275 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1276 // objc_retainBlock is not nounwind because it calls user copy constructors
1277 // which could theoretically throw.
1279 M->getOrInsertFunction(
1281 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1284 return RetainBlockCallee;
1287 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1288 if (!AutoreleaseCallee) {
1289 LLVMContext &C = M->getContext();
1290 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1291 AttributeSet Attribute =
1292 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1293 Attribute::NoUnwind);
1295 M->getOrInsertFunction(
1297 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1300 return AutoreleaseCallee;
1303 /// Test whether the given value is possible a reference-counted pointer,
1304 /// including tests which utilize AliasAnalysis.
1305 static bool IsPotentialRetainableObjPtr(const Value *Op, AliasAnalysis &AA) {
1306 // First make the rudimentary check.
1307 if (!IsPotentialRetainableObjPtr(Op))
1310 // Objects in constant memory are not reference-counted.
1311 if (AA.pointsToConstantMemory(Op))
1314 // Pointers in constant memory are not pointing to reference-counted objects.
1315 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1316 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1319 // Otherwise assume the worst.
1323 /// Test whether the given instruction can result in a reference count
1324 /// modification (positive or negative) for the pointer's object.
1326 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1327 ProvenanceAnalysis &PA, InstructionClass Class) {
1329 case IC_Autorelease:
1330 case IC_AutoreleaseRV:
1332 // These operations never directly modify a reference count.
1337 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1338 assert(CS && "Only calls can alter reference counts!");
1340 // See if AliasAnalysis can help us with the call.
1341 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1342 if (AliasAnalysis::onlyReadsMemory(MRB))
1344 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1345 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1347 const Value *Op = *I;
1348 if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op))
1354 // Assume the worst.
1358 /// Test whether the given instruction can "use" the given pointer's object in a
1359 /// way that requires the reference count to be positive.
1361 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1362 InstructionClass Class) {
1363 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1364 if (Class == IC_Call)
1367 // Consider various instructions which may have pointer arguments which are
1369 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1370 // Comparing a pointer with null, or any other constant, isn't really a use,
1371 // because we don't care what the pointer points to, or about the values
1372 // of any other dynamic reference-counted pointers.
1373 if (!IsPotentialRetainableObjPtr(ICI->getOperand(1), *PA.getAA()))
1375 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1376 // For calls, just check the arguments (and not the callee operand).
1377 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1378 OE = CS.arg_end(); OI != OE; ++OI) {
1379 const Value *Op = *OI;
1380 if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op))
1384 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1385 // Special-case stores, because we don't care about the stored value, just
1386 // the store address.
1387 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1388 // If we can't tell what the underlying object was, assume there is a
1390 return IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Op, Ptr);
1393 // Check each operand for a match.
1394 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1396 const Value *Op = *OI;
1397 if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op))
1403 /// Test whether the given instruction can autorelease any pointer or cause an
1404 /// autoreleasepool pop.
1406 CanInterruptRV(InstructionClass Class) {
1408 case IC_AutoreleasepoolPop:
1411 case IC_Autorelease:
1412 case IC_AutoreleaseRV:
1413 case IC_FusedRetainAutorelease:
1414 case IC_FusedRetainAutoreleaseRV:
1422 /// \enum DependenceKind
1423 /// \brief Defines different dependence kinds among various ARC constructs.
1425 /// There are several kinds of dependence-like concepts in use here.
1427 enum DependenceKind {
1428 NeedsPositiveRetainCount,
1429 AutoreleasePoolBoundary,
1430 CanChangeRetainCount,
1431 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1432 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1433 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1437 /// Test if there can be dependencies on Inst through Arg. This function only
1438 /// tests dependencies relevant for removing pairs of calls.
1440 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1441 ProvenanceAnalysis &PA) {
1442 // If we've reached the definition of Arg, stop.
1447 case NeedsPositiveRetainCount: {
1448 InstructionClass Class = GetInstructionClass(Inst);
1450 case IC_AutoreleasepoolPop:
1451 case IC_AutoreleasepoolPush:
1455 return CanUse(Inst, Arg, PA, Class);
1459 case AutoreleasePoolBoundary: {
1460 InstructionClass Class = GetInstructionClass(Inst);
1462 case IC_AutoreleasepoolPop:
1463 case IC_AutoreleasepoolPush:
1464 // These mark the end and begin of an autorelease pool scope.
1467 // Nothing else does this.
1472 case CanChangeRetainCount: {
1473 InstructionClass Class = GetInstructionClass(Inst);
1475 case IC_AutoreleasepoolPop:
1476 // Conservatively assume this can decrement any count.
1478 case IC_AutoreleasepoolPush:
1482 return CanAlterRefCount(Inst, Arg, PA, Class);
1486 case RetainAutoreleaseDep:
1487 switch (GetBasicInstructionClass(Inst)) {
1488 case IC_AutoreleasepoolPop:
1489 case IC_AutoreleasepoolPush:
1490 // Don't merge an objc_autorelease with an objc_retain inside a different
1491 // autoreleasepool scope.
1495 // Check for a retain of the same pointer for merging.
1496 return GetObjCArg(Inst) == Arg;
1498 // Nothing else matters for objc_retainAutorelease formation.
1502 case RetainAutoreleaseRVDep: {
1503 InstructionClass Class = GetBasicInstructionClass(Inst);
1507 // Check for a retain of the same pointer for merging.
1508 return GetObjCArg(Inst) == Arg;
1510 // Anything that can autorelease interrupts
1511 // retainAutoreleaseReturnValue formation.
1512 return CanInterruptRV(Class);
1517 return CanInterruptRV(GetBasicInstructionClass(Inst));
1520 llvm_unreachable("Invalid dependence flavor");
1523 /// Walk up the CFG from StartPos (which is in StartBB) and find local and
1524 /// non-local dependencies on Arg.
1526 /// TODO: Cache results?
1528 FindDependencies(DependenceKind Flavor,
1530 BasicBlock *StartBB, Instruction *StartInst,
1531 SmallPtrSet<Instruction *, 4> &DependingInstructions,
1532 SmallPtrSet<const BasicBlock *, 4> &Visited,
1533 ProvenanceAnalysis &PA) {
1534 BasicBlock::iterator StartPos = StartInst;
1536 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
1537 Worklist.push_back(std::make_pair(StartBB, StartPos));
1539 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
1540 Worklist.pop_back_val();
1541 BasicBlock *LocalStartBB = Pair.first;
1542 BasicBlock::iterator LocalStartPos = Pair.second;
1543 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
1545 if (LocalStartPos == StartBBBegin) {
1546 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
1548 // If we've reached the function entry, produce a null dependence.
1549 DependingInstructions.insert(0);
1551 // Add the predecessors to the worklist.
1553 BasicBlock *PredBB = *PI;
1554 if (Visited.insert(PredBB))
1555 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
1556 } while (++PI != PE);
1560 Instruction *Inst = --LocalStartPos;
1561 if (Depends(Flavor, Inst, Arg, PA)) {
1562 DependingInstructions.insert(Inst);
1566 } while (!Worklist.empty());
1568 // Determine whether the original StartBB post-dominates all of the blocks we
1569 // visited. If not, insert a sentinal indicating that most optimizations are
1571 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
1572 E = Visited.end(); I != E; ++I) {
1573 const BasicBlock *BB = *I;
1576 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1577 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
1578 const BasicBlock *Succ = *SI;
1579 if (Succ != StartBB && !Visited.count(Succ)) {
1580 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
1587 static bool isNullOrUndef(const Value *V) {
1588 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
1591 static bool isNoopInstruction(const Instruction *I) {
1592 return isa<BitCastInst>(I) ||
1593 (isa<GetElementPtrInst>(I) &&
1594 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
1597 /// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
1600 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
1601 ImmutableCallSite CS(GetObjCArg(Retain));
1602 const Instruction *Call = CS.getInstruction();
1604 if (Call->getParent() != Retain->getParent()) return;
1606 // Check that the call is next to the retain.
1607 BasicBlock::const_iterator I = Call;
1609 while (isNoopInstruction(I)) ++I;
1613 // Turn it to an objc_retainAutoreleasedReturnValue..
1617 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
1618 "objc_retain => objc_retainAutoreleasedReturnValue"
1619 " since the operand is a return value.\n"
1621 << *Retain << "\n");
1623 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
1625 DEBUG(dbgs() << " New: "
1626 << *Retain << "\n");
1629 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1630 /// not a return value. Or, if it can be paired with an
1631 /// objc_autoreleaseReturnValue, delete the pair and return true.
1633 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1634 // Check for the argument being from an immediately preceding call or invoke.
1635 const Value *Arg = GetObjCArg(RetainRV);
1636 ImmutableCallSite CS(Arg);
1637 if (const Instruction *Call = CS.getInstruction()) {
1638 if (Call->getParent() == RetainRV->getParent()) {
1639 BasicBlock::const_iterator I = Call;
1641 while (isNoopInstruction(I)) ++I;
1642 if (&*I == RetainRV)
1644 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
1645 BasicBlock *RetainRVParent = RetainRV->getParent();
1646 if (II->getNormalDest() == RetainRVParent) {
1647 BasicBlock::const_iterator I = RetainRVParent->begin();
1648 while (isNoopInstruction(I)) ++I;
1649 if (&*I == RetainRV)
1655 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1656 // pointer. In this case, we can delete the pair.
1657 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1659 do --I; while (I != Begin && isNoopInstruction(I));
1660 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1661 GetObjCArg(I) == Arg) {
1665 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
1666 << " Erasing " << *RetainRV
1669 EraseInstruction(I);
1670 EraseInstruction(RetainRV);
1675 // Turn it to a plain objc_retain.
1679 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
1680 "objc_retainAutoreleasedReturnValue => "
1681 "objc_retain since the operand is not a return value.\n"
1683 << *RetainRV << "\n");
1685 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
1687 DEBUG(dbgs() << " New: "
1688 << *RetainRV << "\n");
1693 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1694 /// used as a return value.
1696 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1697 InstructionClass &Class) {
1698 // Check for a return of the pointer value.
1699 const Value *Ptr = GetObjCArg(AutoreleaseRV);
1700 SmallVector<const Value *, 2> Users;
1701 Users.push_back(Ptr);
1703 Ptr = Users.pop_back_val();
1704 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1706 const User *I = *UI;
1707 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1709 if (isa<BitCastInst>(I))
1712 } while (!Users.empty());
1717 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
1718 "objc_autoreleaseReturnValue => "
1719 "objc_autorelease since its operand is not used as a return "
1722 << *AutoreleaseRV << "\n");
1724 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
1726 setCalledFunction(getAutoreleaseCallee(F.getParent()));
1727 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
1728 Class = IC_Autorelease;
1730 DEBUG(dbgs() << " New: "
1731 << *AutoreleaseRV << "\n");
1735 /// Visit each call, one at a time, and make simplifications without doing any
1736 /// additional analysis.
1737 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1738 // Reset all the flags in preparation for recomputing them.
1739 UsedInThisFunction = 0;
1741 // Visit all objc_* calls in F.
1742 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1743 Instruction *Inst = &*I++;
1745 InstructionClass Class = GetBasicInstructionClass(Inst);
1747 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: Class: "
1748 << Class << "; " << *Inst << "\n");
1753 // Delete no-op casts. These function calls have special semantics, but
1754 // the semantics are entirely implemented via lowering in the front-end,
1755 // so by the time they reach the optimizer, they are just no-op calls
1756 // which return their argument.
1758 // There are gray areas here, as the ability to cast reference-counted
1759 // pointers to raw void* and back allows code to break ARC assumptions,
1760 // however these are currently considered to be unimportant.
1764 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
1765 " " << *Inst << "\n");
1766 EraseInstruction(Inst);
1769 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1772 case IC_LoadWeakRetained:
1774 case IC_DestroyWeak: {
1775 CallInst *CI = cast<CallInst>(Inst);
1776 if (isNullOrUndef(CI->getArgOperand(0))) {
1778 Type *Ty = CI->getArgOperand(0)->getType();
1779 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1780 Constant::getNullValue(Ty),
1782 llvm::Value *NewValue = UndefValue::get(CI->getType());
1783 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
1784 "pointer-to-weak-pointer is undefined behavior.\n"
1788 CI->replaceAllUsesWith(NewValue);
1789 CI->eraseFromParent();
1796 CallInst *CI = cast<CallInst>(Inst);
1797 if (isNullOrUndef(CI->getArgOperand(0)) ||
1798 isNullOrUndef(CI->getArgOperand(1))) {
1800 Type *Ty = CI->getArgOperand(0)->getType();
1801 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1802 Constant::getNullValue(Ty),
1805 llvm::Value *NewValue = UndefValue::get(CI->getType());
1806 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
1807 "pointer-to-weak-pointer is undefined behavior.\n"
1812 CI->replaceAllUsesWith(NewValue);
1813 CI->eraseFromParent();
1819 OptimizeRetainCall(F, Inst);
1822 if (OptimizeRetainRVCall(F, Inst))
1825 case IC_AutoreleaseRV:
1826 OptimizeAutoreleaseRVCall(F, Inst, Class);
1830 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
1831 if (IsAutorelease(Class) && Inst->use_empty()) {
1832 CallInst *Call = cast<CallInst>(Inst);
1833 const Value *Arg = Call->getArgOperand(0);
1834 Arg = FindSingleUseIdentifiedObject(Arg);
1839 // Create the declaration lazily.
1840 LLVMContext &C = Inst->getContext();
1842 CallInst::Create(getReleaseCallee(F.getParent()),
1843 Call->getArgOperand(0), "", Call);
1844 NewCall->setMetadata(ImpreciseReleaseMDKind,
1845 MDNode::get(C, ArrayRef<Value *>()));
1847 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
1848 "objc_autorelease(x) with objc_release(x) since x is "
1849 "otherwise unused.\n"
1850 " Old: " << *Call <<
1854 EraseInstruction(Call);
1860 // For functions which can never be passed stack arguments, add
1862 if (IsAlwaysTail(Class)) {
1864 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
1865 " to function since it can never be passed stack args: " << *Inst <<
1867 cast<CallInst>(Inst)->setTailCall();
1870 // Ensure that functions that can never have a "tail" keyword due to the
1871 // semantics of ARC truly do not do so.
1872 if (IsNeverTail(Class)) {
1874 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail "
1875 "keyword from function: " << *Inst <<
1877 cast<CallInst>(Inst)->setTailCall(false);
1880 // Set nounwind as needed.
1881 if (IsNoThrow(Class)) {
1883 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
1884 " class. Setting nounwind on: " << *Inst << "\n");
1885 cast<CallInst>(Inst)->setDoesNotThrow();
1888 if (!IsNoopOnNull(Class)) {
1889 UsedInThisFunction |= 1 << Class;
1893 const Value *Arg = GetObjCArg(Inst);
1895 // ARC calls with null are no-ops. Delete them.
1896 if (isNullOrUndef(Arg)) {
1899 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
1900 " null are no-ops. Erasing: " << *Inst << "\n");
1901 EraseInstruction(Inst);
1905 // Keep track of which of retain, release, autorelease, and retain_block
1906 // are actually present in this function.
1907 UsedInThisFunction |= 1 << Class;
1909 // If Arg is a PHI, and one or more incoming values to the
1910 // PHI are null, and the call is control-equivalent to the PHI, and there
1911 // are no relevant side effects between the PHI and the call, the call
1912 // could be pushed up to just those paths with non-null incoming values.
1913 // For now, don't bother splitting critical edges for this.
1914 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
1915 Worklist.push_back(std::make_pair(Inst, Arg));
1917 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
1921 const PHINode *PN = dyn_cast<PHINode>(Arg);
1924 // Determine if the PHI has any null operands, or any incoming
1926 bool HasNull = false;
1927 bool HasCriticalEdges = false;
1928 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1930 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1931 if (isNullOrUndef(Incoming))
1933 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
1934 .getNumSuccessors() != 1) {
1935 HasCriticalEdges = true;
1939 // If we have null operands and no critical edges, optimize.
1940 if (!HasCriticalEdges && HasNull) {
1941 SmallPtrSet<Instruction *, 4> DependingInstructions;
1942 SmallPtrSet<const BasicBlock *, 4> Visited;
1944 // Check that there is nothing that cares about the reference
1945 // count between the call and the phi.
1948 case IC_RetainBlock:
1949 // These can always be moved up.
1952 // These can't be moved across things that care about the retain
1954 FindDependencies(NeedsPositiveRetainCount, Arg,
1955 Inst->getParent(), Inst,
1956 DependingInstructions, Visited, PA);
1958 case IC_Autorelease:
1959 // These can't be moved across autorelease pool scope boundaries.
1960 FindDependencies(AutoreleasePoolBoundary, Arg,
1961 Inst->getParent(), Inst,
1962 DependingInstructions, Visited, PA);
1965 case IC_AutoreleaseRV:
1966 // Don't move these; the RV optimization depends on the autoreleaseRV
1967 // being tail called, and the retainRV being immediately after a call
1968 // (which might still happen if we get lucky with codegen layout, but
1969 // it's not worth taking the chance).
1972 llvm_unreachable("Invalid dependence flavor");
1975 if (DependingInstructions.size() == 1 &&
1976 *DependingInstructions.begin() == PN) {
1979 // Clone the call into each predecessor that has a non-null value.
1980 CallInst *CInst = cast<CallInst>(Inst);
1981 Type *ParamTy = CInst->getArgOperand(0)->getType();
1982 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1984 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
1985 if (!isNullOrUndef(Incoming)) {
1986 CallInst *Clone = cast<CallInst>(CInst->clone());
1987 Value *Op = PN->getIncomingValue(i);
1988 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
1989 if (Op->getType() != ParamTy)
1990 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
1991 Clone->setArgOperand(0, Op);
1992 Clone->insertBefore(InsertPos);
1994 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
1997 "clone at " << *InsertPos << "\n");
1998 Worklist.push_back(std::make_pair(Clone, Incoming));
2001 // Erase the original call.
2002 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
2003 EraseInstruction(CInst);
2007 } while (!Worklist.empty());
2009 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
2012 /// Check for critical edges, loop boundaries, irreducible control flow, or
2013 /// other CFG structures where moving code across the edge would result in it
2014 /// being executed more.
2016 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2017 DenseMap<const BasicBlock *, BBState> &BBStates,
2018 BBState &MyStates) const {
2019 // If any top-down local-use or possible-dec has a succ which is earlier in
2020 // the sequence, forget it.
2021 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
2022 E = MyStates.top_down_ptr_end(); I != E; ++I)
2023 switch (I->second.GetSeq()) {
2026 const Value *Arg = I->first;
2027 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2028 bool SomeSuccHasSame = false;
2029 bool AllSuccsHaveSame = true;
2030 PtrState &S = I->second;
2031 succ_const_iterator SI(TI), SE(TI, false);
2033 for (; SI != SE; ++SI) {
2034 Sequence SuccSSeq = S_None;
2035 bool SuccSRRIKnownSafe = false;
2036 // If VisitBottomUp has pointer information for this successor, take
2037 // what we know about it.
2038 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2040 assert(BBI != BBStates.end());
2041 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2042 SuccSSeq = SuccS.GetSeq();
2043 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2046 case S_CanRelease: {
2047 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2048 S.ClearSequenceProgress();
2054 SomeSuccHasSame = true;
2058 case S_MovableRelease:
2059 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2060 AllSuccsHaveSame = false;
2063 llvm_unreachable("bottom-up pointer in retain state!");
2066 // If the state at the other end of any of the successor edges
2067 // matches the current state, require all edges to match. This
2068 // guards against loops in the middle of a sequence.
2069 if (SomeSuccHasSame && !AllSuccsHaveSame)
2070 S.ClearSequenceProgress();
2073 case S_CanRelease: {
2074 const Value *Arg = I->first;
2075 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2076 bool SomeSuccHasSame = false;
2077 bool AllSuccsHaveSame = true;
2078 PtrState &S = I->second;
2079 succ_const_iterator SI(TI), SE(TI, false);
2081 for (; SI != SE; ++SI) {
2082 Sequence SuccSSeq = S_None;
2083 bool SuccSRRIKnownSafe = false;
2084 // If VisitBottomUp has pointer information for this successor, take
2085 // what we know about it.
2086 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2088 assert(BBI != BBStates.end());
2089 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2090 SuccSSeq = SuccS.GetSeq();
2091 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2094 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2095 S.ClearSequenceProgress();
2101 SomeSuccHasSame = true;
2105 case S_MovableRelease:
2107 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2108 AllSuccsHaveSame = false;
2111 llvm_unreachable("bottom-up pointer in retain state!");
2114 // If the state at the other end of any of the successor edges
2115 // matches the current state, require all edges to match. This
2116 // guards against loops in the middle of a sequence.
2117 if (SomeSuccHasSame && !AllSuccsHaveSame)
2118 S.ClearSequenceProgress();
2125 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
2127 MapVector<Value *, RRInfo> &Retains,
2128 BBState &MyStates) {
2129 bool NestingDetected = false;
2130 InstructionClass Class = GetInstructionClass(Inst);
2131 const Value *Arg = 0;
2135 Arg = GetObjCArg(Inst);
2137 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2139 // If we see two releases in a row on the same pointer. If so, make
2140 // a note, and we'll cicle back to revisit it after we've
2141 // hopefully eliminated the second release, which may allow us to
2142 // eliminate the first release too.
2143 // Theoretically we could implement removal of nested retain+release
2144 // pairs by making PtrState hold a stack of states, but this is
2145 // simple and avoids adding overhead for the non-nested case.
2146 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
2147 DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested "
2148 "releases (i.e. a release pair)\n");
2149 NestingDetected = true;
2152 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2153 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
2154 S.RRI.ReleaseMetadata = ReleaseMetadata;
2155 S.RRI.KnownSafe = S.IsKnownIncremented();
2156 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2157 S.RRI.Calls.insert(Inst);
2159 S.SetKnownPositiveRefCount();
2162 case IC_RetainBlock:
2163 // An objc_retainBlock call with just a use may need to be kept,
2164 // because it may be copying a block from the stack to the heap.
2165 if (!IsRetainBlockOptimizable(Inst))
2170 Arg = GetObjCArg(Inst);
2172 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2173 S.SetKnownPositiveRefCount();
2175 switch (S.GetSeq()) {
2178 case S_MovableRelease:
2180 S.RRI.ReverseInsertPts.clear();
2183 // Don't do retain+release tracking for IC_RetainRV, because it's
2184 // better to let it remain as the first instruction after a call.
2185 if (Class != IC_RetainRV) {
2186 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2187 Retains[Inst] = S.RRI;
2189 S.ClearSequenceProgress();
2194 llvm_unreachable("bottom-up pointer in retain state!");
2196 return NestingDetected;
2198 case IC_AutoreleasepoolPop:
2199 // Conservatively, clear MyStates for all known pointers.
2200 MyStates.clearBottomUpPointers();
2201 return NestingDetected;
2202 case IC_AutoreleasepoolPush:
2204 // These are irrelevant.
2205 return NestingDetected;
2210 // Consider any other possible effects of this instruction on each
2211 // pointer being tracked.
2212 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2213 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2214 const Value *Ptr = MI->first;
2216 continue; // Handled above.
2217 PtrState &S = MI->second;
2218 Sequence Seq = S.GetSeq();
2220 // Check for possible releases.
2221 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2225 S.SetSeq(S_CanRelease);
2229 case S_MovableRelease:
2234 llvm_unreachable("bottom-up pointer in retain state!");
2238 // Check for possible direct uses.
2241 case S_MovableRelease:
2242 if (CanUse(Inst, Ptr, PA, Class)) {
2243 assert(S.RRI.ReverseInsertPts.empty());
2244 // If this is an invoke instruction, we're scanning it as part of
2245 // one of its successor blocks, since we can't insert code after it
2246 // in its own block, and we don't want to split critical edges.
2247 if (isa<InvokeInst>(Inst))
2248 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2250 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2252 } else if (Seq == S_Release &&
2253 (Class == IC_User || Class == IC_CallOrUser)) {
2254 // Non-movable releases depend on any possible objc pointer use.
2256 assert(S.RRI.ReverseInsertPts.empty());
2257 // As above; handle invoke specially.
2258 if (isa<InvokeInst>(Inst))
2259 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2261 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2265 if (CanUse(Inst, Ptr, PA, Class))
2273 llvm_unreachable("bottom-up pointer in retain state!");
2277 return NestingDetected;
2281 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2282 DenseMap<const BasicBlock *, BBState> &BBStates,
2283 MapVector<Value *, RRInfo> &Retains) {
2284 bool NestingDetected = false;
2285 BBState &MyStates = BBStates[BB];
2287 // Merge the states from each successor to compute the initial state
2288 // for the current block.
2289 BBState::edge_iterator SI(MyStates.succ_begin()),
2290 SE(MyStates.succ_end());
2292 const BasicBlock *Succ = *SI;
2293 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2294 assert(I != BBStates.end());
2295 MyStates.InitFromSucc(I->second);
2297 for (; SI != SE; ++SI) {
2299 I = BBStates.find(Succ);
2300 assert(I != BBStates.end());
2301 MyStates.MergeSucc(I->second);
2305 // Visit all the instructions, bottom-up.
2306 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2307 Instruction *Inst = llvm::prior(I);
2309 // Invoke instructions are visited as part of their successors (below).
2310 if (isa<InvokeInst>(Inst))
2313 DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n");
2315 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2318 // If there's a predecessor with an invoke, visit the invoke as if it were
2319 // part of this block, since we can't insert code after an invoke in its own
2320 // block, and we don't want to split critical edges.
2321 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2322 PE(MyStates.pred_end()); PI != PE; ++PI) {
2323 BasicBlock *Pred = *PI;
2324 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2325 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
2328 return NestingDetected;
2332 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2333 DenseMap<Value *, RRInfo> &Releases,
2334 BBState &MyStates) {
2335 bool NestingDetected = false;
2336 InstructionClass Class = GetInstructionClass(Inst);
2337 const Value *Arg = 0;
2340 case IC_RetainBlock:
2341 // An objc_retainBlock call with just a use may need to be kept,
2342 // because it may be copying a block from the stack to the heap.
2343 if (!IsRetainBlockOptimizable(Inst))
2348 Arg = GetObjCArg(Inst);
2350 PtrState &S = MyStates.getPtrTopDownState(Arg);
2352 // Don't do retain+release tracking for IC_RetainRV, because it's
2353 // better to let it remain as the first instruction after a call.
2354 if (Class != IC_RetainRV) {
2355 // If we see two retains in a row on the same pointer. If so, make
2356 // a note, and we'll cicle back to revisit it after we've
2357 // hopefully eliminated the second retain, which may allow us to
2358 // eliminate the first retain too.
2359 // Theoretically we could implement removal of nested retain+release
2360 // pairs by making PtrState hold a stack of states, but this is
2361 // simple and avoids adding overhead for the non-nested case.
2362 if (S.GetSeq() == S_Retain)
2363 NestingDetected = true;
2365 S.ResetSequenceProgress(S_Retain);
2366 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2367 S.RRI.KnownSafe = S.IsKnownIncremented();
2368 S.RRI.Calls.insert(Inst);
2371 S.SetKnownPositiveRefCount();
2373 // A retain can be a potential use; procede to the generic checking
2378 Arg = GetObjCArg(Inst);
2380 PtrState &S = MyStates.getPtrTopDownState(Arg);
2383 switch (S.GetSeq()) {
2386 S.RRI.ReverseInsertPts.clear();
2389 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2390 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2391 Releases[Inst] = S.RRI;
2392 S.ClearSequenceProgress();
2398 case S_MovableRelease:
2399 llvm_unreachable("top-down pointer in release state!");
2403 case IC_AutoreleasepoolPop:
2404 // Conservatively, clear MyStates for all known pointers.
2405 MyStates.clearTopDownPointers();
2406 return NestingDetected;
2407 case IC_AutoreleasepoolPush:
2409 // These are irrelevant.
2410 return NestingDetected;
2415 // Consider any other possible effects of this instruction on each
2416 // pointer being tracked.
2417 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2418 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2419 const Value *Ptr = MI->first;
2421 continue; // Handled above.
2422 PtrState &S = MI->second;
2423 Sequence Seq = S.GetSeq();
2425 // Check for possible releases.
2426 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2430 S.SetSeq(S_CanRelease);
2431 assert(S.RRI.ReverseInsertPts.empty());
2432 S.RRI.ReverseInsertPts.insert(Inst);
2434 // One call can't cause a transition from S_Retain to S_CanRelease
2435 // and S_CanRelease to S_Use. If we've made the first transition,
2444 case S_MovableRelease:
2445 llvm_unreachable("top-down pointer in release state!");
2449 // Check for possible direct uses.
2452 if (CanUse(Inst, Ptr, PA, Class))
2461 case S_MovableRelease:
2462 llvm_unreachable("top-down pointer in release state!");
2466 return NestingDetected;
2470 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2471 DenseMap<const BasicBlock *, BBState> &BBStates,
2472 DenseMap<Value *, RRInfo> &Releases) {
2473 bool NestingDetected = false;
2474 BBState &MyStates = BBStates[BB];
2476 // Merge the states from each predecessor to compute the initial state
2477 // for the current block.
2478 BBState::edge_iterator PI(MyStates.pred_begin()),
2479 PE(MyStates.pred_end());
2481 const BasicBlock *Pred = *PI;
2482 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2483 assert(I != BBStates.end());
2484 MyStates.InitFromPred(I->second);
2486 for (; PI != PE; ++PI) {
2488 I = BBStates.find(Pred);
2489 assert(I != BBStates.end());
2490 MyStates.MergePred(I->second);
2494 // Visit all the instructions, top-down.
2495 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2496 Instruction *Inst = I;
2498 DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n");
2500 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
2503 CheckForCFGHazards(BB, BBStates, MyStates);
2504 return NestingDetected;
2508 ComputePostOrders(Function &F,
2509 SmallVectorImpl<BasicBlock *> &PostOrder,
2510 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2511 unsigned NoObjCARCExceptionsMDKind,
2512 DenseMap<const BasicBlock *, BBState> &BBStates) {
2513 /// The visited set, for doing DFS walks.
2514 SmallPtrSet<BasicBlock *, 16> Visited;
2516 // Do DFS, computing the PostOrder.
2517 SmallPtrSet<BasicBlock *, 16> OnStack;
2518 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2520 // Functions always have exactly one entry block, and we don't have
2521 // any other block that we treat like an entry block.
2522 BasicBlock *EntryBB = &F.getEntryBlock();
2523 BBState &MyStates = BBStates[EntryBB];
2524 MyStates.SetAsEntry();
2525 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2526 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
2527 Visited.insert(EntryBB);
2528 OnStack.insert(EntryBB);
2531 BasicBlock *CurrBB = SuccStack.back().first;
2532 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2533 succ_iterator SE(TI, false);
2535 while (SuccStack.back().second != SE) {
2536 BasicBlock *SuccBB = *SuccStack.back().second++;
2537 if (Visited.insert(SuccBB)) {
2538 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2539 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
2540 BBStates[CurrBB].addSucc(SuccBB);
2541 BBState &SuccStates = BBStates[SuccBB];
2542 SuccStates.addPred(CurrBB);
2543 OnStack.insert(SuccBB);
2547 if (!OnStack.count(SuccBB)) {
2548 BBStates[CurrBB].addSucc(SuccBB);
2549 BBStates[SuccBB].addPred(CurrBB);
2552 OnStack.erase(CurrBB);
2553 PostOrder.push_back(CurrBB);
2554 SuccStack.pop_back();
2555 } while (!SuccStack.empty());
2559 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2560 // Functions may have many exits, and there also blocks which we treat
2561 // as exits due to ignored edges.
2562 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2563 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2564 BasicBlock *ExitBB = I;
2565 BBState &MyStates = BBStates[ExitBB];
2566 if (!MyStates.isExit())
2569 MyStates.SetAsExit();
2571 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
2572 Visited.insert(ExitBB);
2573 while (!PredStack.empty()) {
2574 reverse_dfs_next_succ:
2575 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2576 while (PredStack.back().second != PE) {
2577 BasicBlock *BB = *PredStack.back().second++;
2578 if (Visited.insert(BB)) {
2579 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
2580 goto reverse_dfs_next_succ;
2583 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2588 // Visit the function both top-down and bottom-up.
2590 ObjCARCOpt::Visit(Function &F,
2591 DenseMap<const BasicBlock *, BBState> &BBStates,
2592 MapVector<Value *, RRInfo> &Retains,
2593 DenseMap<Value *, RRInfo> &Releases) {
2595 // Use reverse-postorder traversals, because we magically know that loops
2596 // will be well behaved, i.e. they won't repeatedly call retain on a single
2597 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2598 // class here because we want the reverse-CFG postorder to consider each
2599 // function exit point, and we want to ignore selected cycle edges.
2600 SmallVector<BasicBlock *, 16> PostOrder;
2601 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2602 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2603 NoObjCARCExceptionsMDKind,
2606 // Use reverse-postorder on the reverse CFG for bottom-up.
2607 bool BottomUpNestingDetected = false;
2608 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2609 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2611 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
2613 // Use reverse-postorder for top-down.
2614 bool TopDownNestingDetected = false;
2615 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2616 PostOrder.rbegin(), E = PostOrder.rend();
2618 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
2620 return TopDownNestingDetected && BottomUpNestingDetected;
2623 /// Move the calls in RetainsToMove and ReleasesToMove.
2624 void ObjCARCOpt::MoveCalls(Value *Arg,
2625 RRInfo &RetainsToMove,
2626 RRInfo &ReleasesToMove,
2627 MapVector<Value *, RRInfo> &Retains,
2628 DenseMap<Value *, RRInfo> &Releases,
2629 SmallVectorImpl<Instruction *> &DeadInsts,
2631 Type *ArgTy = Arg->getType();
2632 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2634 // Insert the new retain and release calls.
2635 for (SmallPtrSet<Instruction *, 2>::const_iterator
2636 PI = ReleasesToMove.ReverseInsertPts.begin(),
2637 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2638 Instruction *InsertPt = *PI;
2639 Value *MyArg = ArgTy == ParamTy ? Arg :
2640 new BitCastInst(Arg, ParamTy, "", InsertPt);
2642 CallInst::Create(RetainsToMove.IsRetainBlock ?
2643 getRetainBlockCallee(M) : getRetainCallee(M),
2644 MyArg, "", InsertPt);
2645 Call->setDoesNotThrow();
2646 if (RetainsToMove.IsRetainBlock)
2647 Call->setMetadata(CopyOnEscapeMDKind,
2648 MDNode::get(M->getContext(), ArrayRef<Value *>()));
2650 Call->setTailCall();
2652 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
2654 " At insertion point: " << *InsertPt
2657 for (SmallPtrSet<Instruction *, 2>::const_iterator
2658 PI = RetainsToMove.ReverseInsertPts.begin(),
2659 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2660 Instruction *InsertPt = *PI;
2661 Value *MyArg = ArgTy == ParamTy ? Arg :
2662 new BitCastInst(Arg, ParamTy, "", InsertPt);
2663 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2665 // Attach a clang.imprecise_release metadata tag, if appropriate.
2666 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2667 Call->setMetadata(ImpreciseReleaseMDKind, M);
2668 Call->setDoesNotThrow();
2669 if (ReleasesToMove.IsTailCallRelease)
2670 Call->setTailCall();
2672 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
2674 " At insertion point: " << *InsertPt
2678 // Delete the original retain and release calls.
2679 for (SmallPtrSet<Instruction *, 2>::const_iterator
2680 AI = RetainsToMove.Calls.begin(),
2681 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2682 Instruction *OrigRetain = *AI;
2683 Retains.blot(OrigRetain);
2684 DeadInsts.push_back(OrigRetain);
2685 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
2688 for (SmallPtrSet<Instruction *, 2>::const_iterator
2689 AI = ReleasesToMove.Calls.begin(),
2690 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2691 Instruction *OrigRelease = *AI;
2692 Releases.erase(OrigRelease);
2693 DeadInsts.push_back(OrigRelease);
2694 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
2700 ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2702 MapVector<Value *, RRInfo> &Retains,
2703 DenseMap<Value *, RRInfo> &Releases,
2705 SmallVector<Instruction *, 4> &NewRetains,
2706 SmallVector<Instruction *, 4> &NewReleases,
2707 SmallVector<Instruction *, 8> &DeadInsts,
2708 RRInfo &RetainsToMove,
2709 RRInfo &ReleasesToMove,
2712 bool &AnyPairsCompletelyEliminated) {
2713 // If a pair happens in a region where it is known that the reference count
2714 // is already incremented, we can similarly ignore possible decrements.
2715 bool KnownSafeTD = true, KnownSafeBU = true;
2717 // Connect the dots between the top-down-collected RetainsToMove and
2718 // bottom-up-collected ReleasesToMove to form sets of related calls.
2719 // This is an iterative process so that we connect multiple releases
2720 // to multiple retains if needed.
2721 unsigned OldDelta = 0;
2722 unsigned NewDelta = 0;
2723 unsigned OldCount = 0;
2724 unsigned NewCount = 0;
2725 bool FirstRelease = true;
2726 bool FirstRetain = true;
2728 for (SmallVectorImpl<Instruction *>::const_iterator
2729 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2730 Instruction *NewRetain = *NI;
2731 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2732 assert(It != Retains.end());
2733 const RRInfo &NewRetainRRI = It->second;
2734 KnownSafeTD &= NewRetainRRI.KnownSafe;
2735 for (SmallPtrSet<Instruction *, 2>::const_iterator
2736 LI = NewRetainRRI.Calls.begin(),
2737 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2738 Instruction *NewRetainRelease = *LI;
2739 DenseMap<Value *, RRInfo>::const_iterator Jt =
2740 Releases.find(NewRetainRelease);
2741 if (Jt == Releases.end())
2743 const RRInfo &NewRetainReleaseRRI = Jt->second;
2744 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2745 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2747 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2749 // Merge the ReleaseMetadata and IsTailCallRelease values.
2751 ReleasesToMove.ReleaseMetadata =
2752 NewRetainReleaseRRI.ReleaseMetadata;
2753 ReleasesToMove.IsTailCallRelease =
2754 NewRetainReleaseRRI.IsTailCallRelease;
2755 FirstRelease = false;
2757 if (ReleasesToMove.ReleaseMetadata !=
2758 NewRetainReleaseRRI.ReleaseMetadata)
2759 ReleasesToMove.ReleaseMetadata = 0;
2760 if (ReleasesToMove.IsTailCallRelease !=
2761 NewRetainReleaseRRI.IsTailCallRelease)
2762 ReleasesToMove.IsTailCallRelease = false;
2765 // Collect the optimal insertion points.
2767 for (SmallPtrSet<Instruction *, 2>::const_iterator
2768 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2769 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2771 Instruction *RIP = *RI;
2772 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2773 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2775 NewReleases.push_back(NewRetainRelease);
2780 if (NewReleases.empty()) break;
2782 // Back the other way.
2783 for (SmallVectorImpl<Instruction *>::const_iterator
2784 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2785 Instruction *NewRelease = *NI;
2786 DenseMap<Value *, RRInfo>::const_iterator It =
2787 Releases.find(NewRelease);
2788 assert(It != Releases.end());
2789 const RRInfo &NewReleaseRRI = It->second;
2790 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2791 for (SmallPtrSet<Instruction *, 2>::const_iterator
2792 LI = NewReleaseRRI.Calls.begin(),
2793 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2794 Instruction *NewReleaseRetain = *LI;
2795 MapVector<Value *, RRInfo>::const_iterator Jt =
2796 Retains.find(NewReleaseRetain);
2797 if (Jt == Retains.end())
2799 const RRInfo &NewReleaseRetainRRI = Jt->second;
2800 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2801 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2802 unsigned PathCount =
2803 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2804 OldDelta += PathCount;
2805 OldCount += PathCount;
2807 // Merge the IsRetainBlock values.
2809 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
2810 FirstRetain = false;
2811 } else if (ReleasesToMove.IsRetainBlock !=
2812 NewReleaseRetainRRI.IsRetainBlock)
2813 // It's not possible to merge the sequences if one uses
2814 // objc_retain and the other uses objc_retainBlock.
2817 // Collect the optimal insertion points.
2819 for (SmallPtrSet<Instruction *, 2>::const_iterator
2820 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2821 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2823 Instruction *RIP = *RI;
2824 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2825 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2826 NewDelta += PathCount;
2827 NewCount += PathCount;
2830 NewRetains.push_back(NewReleaseRetain);
2834 NewReleases.clear();
2835 if (NewRetains.empty()) break;
2838 // If the pointer is known incremented or nested, we can safely delete the
2839 // pair regardless of what's between them.
2840 if (KnownSafeTD || KnownSafeBU) {
2841 RetainsToMove.ReverseInsertPts.clear();
2842 ReleasesToMove.ReverseInsertPts.clear();
2845 // Determine whether the new insertion points we computed preserve the
2846 // balance of retain and release calls through the program.
2847 // TODO: If the fully aggressive solution isn't valid, try to find a
2848 // less aggressive solution which is.
2853 // Determine whether the original call points are balanced in the retain and
2854 // release calls through the program. If not, conservatively don't touch
2856 // TODO: It's theoretically possible to do code motion in this case, as
2857 // long as the existing imbalances are maintained.
2862 assert(OldCount != 0 && "Unreachable code?");
2863 NumRRs += OldCount - NewCount;
2864 // Set to true if we completely removed any RR pairs.
2865 AnyPairsCompletelyEliminated = NewCount == 0;
2867 // We can move calls!
2871 /// Identify pairings between the retains and releases, and delete and/or move
2874 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2876 MapVector<Value *, RRInfo> &Retains,
2877 DenseMap<Value *, RRInfo> &Releases,
2879 bool AnyPairsCompletelyEliminated = false;
2880 RRInfo RetainsToMove;
2881 RRInfo ReleasesToMove;
2882 SmallVector<Instruction *, 4> NewRetains;
2883 SmallVector<Instruction *, 4> NewReleases;
2884 SmallVector<Instruction *, 8> DeadInsts;
2886 // Visit each retain.
2887 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2888 E = Retains.end(); I != E; ++I) {
2889 Value *V = I->first;
2890 if (!V) continue; // blotted
2892 Instruction *Retain = cast<Instruction>(V);
2894 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
2897 Value *Arg = GetObjCArg(Retain);
2899 // If the object being released is in static or stack storage, we know it's
2900 // not being managed by ObjC reference counting, so we can delete pairs
2901 // regardless of what possible decrements or uses lie between them.
2902 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
2904 // A constant pointer can't be pointing to an object on the heap. It may
2905 // be reference-counted, but it won't be deleted.
2906 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2907 if (const GlobalVariable *GV =
2908 dyn_cast<GlobalVariable>(
2909 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2910 if (GV->isConstant())
2913 // Connect the dots between the top-down-collected RetainsToMove and
2914 // bottom-up-collected ReleasesToMove to form sets of related calls.
2915 NewRetains.push_back(Retain);
2916 bool PerformMoveCalls =
2917 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
2918 NewReleases, DeadInsts, RetainsToMove,
2919 ReleasesToMove, Arg, KnownSafe,
2920 AnyPairsCompletelyEliminated);
2922 if (PerformMoveCalls) {
2923 // Ok, everything checks out and we're all set. Let's move/delete some
2925 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
2926 Retains, Releases, DeadInsts, M);
2929 // Clean up state for next retain.
2930 NewReleases.clear();
2932 RetainsToMove.clear();
2933 ReleasesToMove.clear();
2936 // Now that we're done moving everything, we can delete the newly dead
2937 // instructions, as we no longer need them as insert points.
2938 while (!DeadInsts.empty())
2939 EraseInstruction(DeadInsts.pop_back_val());
2941 return AnyPairsCompletelyEliminated;
2944 /// Weak pointer optimizations.
2945 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2946 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2947 // itself because it uses AliasAnalysis and we need to do provenance
2949 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2950 Instruction *Inst = &*I++;
2952 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
2955 InstructionClass Class = GetBasicInstructionClass(Inst);
2956 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2959 // Delete objc_loadWeak calls with no users.
2960 if (Class == IC_LoadWeak && Inst->use_empty()) {
2961 Inst->eraseFromParent();
2965 // TODO: For now, just look for an earlier available version of this value
2966 // within the same block. Theoretically, we could do memdep-style non-local
2967 // analysis too, but that would want caching. A better approach would be to
2968 // use the technique that EarlyCSE uses.
2969 inst_iterator Current = llvm::prior(I);
2970 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2971 for (BasicBlock::iterator B = CurrentBB->begin(),
2972 J = Current.getInstructionIterator();
2974 Instruction *EarlierInst = &*llvm::prior(J);
2975 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2976 switch (EarlierClass) {
2978 case IC_LoadWeakRetained: {
2979 // If this is loading from the same pointer, replace this load's value
2981 CallInst *Call = cast<CallInst>(Inst);
2982 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2983 Value *Arg = Call->getArgOperand(0);
2984 Value *EarlierArg = EarlierCall->getArgOperand(0);
2985 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2986 case AliasAnalysis::MustAlias:
2988 // If the load has a builtin retain, insert a plain retain for it.
2989 if (Class == IC_LoadWeakRetained) {
2991 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2995 // Zap the fully redundant load.
2996 Call->replaceAllUsesWith(EarlierCall);
2997 Call->eraseFromParent();
2999 case AliasAnalysis::MayAlias:
3000 case AliasAnalysis::PartialAlias:
3002 case AliasAnalysis::NoAlias:
3009 // If this is storing to the same pointer and has the same size etc.
3010 // replace this load's value with the stored value.
3011 CallInst *Call = cast<CallInst>(Inst);
3012 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3013 Value *Arg = Call->getArgOperand(0);
3014 Value *EarlierArg = EarlierCall->getArgOperand(0);
3015 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3016 case AliasAnalysis::MustAlias:
3018 // If the load has a builtin retain, insert a plain retain for it.
3019 if (Class == IC_LoadWeakRetained) {
3021 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3025 // Zap the fully redundant load.
3026 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3027 Call->eraseFromParent();
3029 case AliasAnalysis::MayAlias:
3030 case AliasAnalysis::PartialAlias:
3032 case AliasAnalysis::NoAlias:
3039 // TOOD: Grab the copied value.
3041 case IC_AutoreleasepoolPush:
3044 // Weak pointers are only modified through the weak entry points
3045 // (and arbitrary calls, which could call the weak entry points).
3048 // Anything else could modify the weak pointer.
3055 // Then, for each destroyWeak with an alloca operand, check to see if
3056 // the alloca and all its users can be zapped.
3057 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3058 Instruction *Inst = &*I++;
3059 InstructionClass Class = GetBasicInstructionClass(Inst);
3060 if (Class != IC_DestroyWeak)
3063 CallInst *Call = cast<CallInst>(Inst);
3064 Value *Arg = Call->getArgOperand(0);
3065 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3066 for (Value::use_iterator UI = Alloca->use_begin(),
3067 UE = Alloca->use_end(); UI != UE; ++UI) {
3068 const Instruction *UserInst = cast<Instruction>(*UI);
3069 switch (GetBasicInstructionClass(UserInst)) {
3072 case IC_DestroyWeak:
3079 for (Value::use_iterator UI = Alloca->use_begin(),
3080 UE = Alloca->use_end(); UI != UE; ) {
3081 CallInst *UserInst = cast<CallInst>(*UI++);
3082 switch (GetBasicInstructionClass(UserInst)) {
3085 // These functions return their second argument.
3086 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3088 case IC_DestroyWeak:
3092 llvm_unreachable("alloca really is used!");
3094 UserInst->eraseFromParent();
3096 Alloca->eraseFromParent();
3101 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
3105 /// Identify program paths which execute sequences of retains and releases which
3106 /// can be eliminated.
3107 bool ObjCARCOpt::OptimizeSequences(Function &F) {
3108 /// Releases, Retains - These are used to store the results of the main flow
3109 /// analysis. These use Value* as the key instead of Instruction* so that the
3110 /// map stays valid when we get around to rewriting code and calls get
3111 /// replaced by arguments.
3112 DenseMap<Value *, RRInfo> Releases;
3113 MapVector<Value *, RRInfo> Retains;
3115 /// This is used during the traversal of the function to track the
3116 /// states for each identified object at each block.
3117 DenseMap<const BasicBlock *, BBState> BBStates;
3119 // Analyze the CFG of the function, and all instructions.
3120 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3123 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3127 /// Look for this pattern:
3129 /// %call = call i8* @something(...)
3130 /// %2 = call i8* @objc_retain(i8* %call)
3131 /// %3 = call i8* @objc_autorelease(i8* %2)
3134 /// And delete the retain and autorelease.
3136 /// Otherwise if it's just this:
3138 /// %3 = call i8* @objc_autorelease(i8* %2)
3141 /// convert the autorelease to autoreleaseRV.
3142 void ObjCARCOpt::OptimizeReturns(Function &F) {
3143 if (!F.getReturnType()->isPointerTy())
3146 SmallPtrSet<Instruction *, 4> DependingInstructions;
3147 SmallPtrSet<const BasicBlock *, 4> Visited;
3148 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3149 BasicBlock *BB = FI;
3150 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3152 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
3156 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3157 FindDependencies(NeedsPositiveRetainCount, Arg,
3158 BB, Ret, DependingInstructions, Visited, PA);
3159 if (DependingInstructions.size() != 1)
3163 CallInst *Autorelease =
3164 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3167 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3168 if (!IsAutorelease(AutoreleaseClass))
3170 if (GetObjCArg(Autorelease) != Arg)
3173 DependingInstructions.clear();
3176 // Check that there is nothing that can affect the reference
3177 // count between the autorelease and the retain.
3178 FindDependencies(CanChangeRetainCount, Arg,
3179 BB, Autorelease, DependingInstructions, Visited, PA);
3180 if (DependingInstructions.size() != 1)
3185 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3187 // Check that we found a retain with the same argument.
3189 !IsRetain(GetBasicInstructionClass(Retain)) ||
3190 GetObjCArg(Retain) != Arg)
3193 DependingInstructions.clear();
3196 // Convert the autorelease to an autoreleaseRV, since it's
3197 // returning the value.
3198 if (AutoreleaseClass == IC_Autorelease) {
3199 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
3200 "=> autoreleaseRV since it's returning a value.\n"
3201 " In: " << *Autorelease
3203 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3204 DEBUG(dbgs() << " Out: " << *Autorelease
3206 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
3207 AutoreleaseClass = IC_AutoreleaseRV;
3210 // Check that there is nothing that can affect the reference
3211 // count between the retain and the call.
3212 // Note that Retain need not be in BB.
3213 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3214 DependingInstructions, Visited, PA);
3215 if (DependingInstructions.size() != 1)
3220 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3222 // Check that the pointer is the return value of the call.
3223 if (!Call || Arg != Call)
3226 // Check that the call is a regular call.
3227 InstructionClass Class = GetBasicInstructionClass(Call);
3228 if (Class != IC_CallOrUser && Class != IC_Call)
3231 // If so, we can zap the retain and autorelease.
3234 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
3236 << *Autorelease << "\n");
3237 EraseInstruction(Retain);
3238 EraseInstruction(Autorelease);
3244 DependingInstructions.clear();
3248 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
3252 bool ObjCARCOpt::doInitialization(Module &M) {
3256 // If nothing in the Module uses ARC, don't do anything.
3257 Run = ModuleHasARC(M);
3261 // Identify the imprecise release metadata kind.
3262 ImpreciseReleaseMDKind =
3263 M.getContext().getMDKindID("clang.imprecise_release");
3264 CopyOnEscapeMDKind =
3265 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3266 NoObjCARCExceptionsMDKind =
3267 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3269 // Intuitively, objc_retain and others are nocapture, however in practice
3270 // they are not, because they return their argument value. And objc_release
3271 // calls finalizers which can have arbitrary side effects.
3273 // These are initialized lazily.
3275 AutoreleaseRVCallee = 0;
3278 RetainBlockCallee = 0;
3279 AutoreleaseCallee = 0;
3284 bool ObjCARCOpt::runOnFunction(Function &F) {
3288 // If nothing in the Module uses ARC, don't do anything.
3294 DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
3296 PA.setAA(&getAnalysis<AliasAnalysis>());
3298 // This pass performs several distinct transformations. As a compile-time aid
3299 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3300 // library functions aren't declared.
3302 // Preliminary optimizations. This also computs UsedInThisFunction.
3303 OptimizeIndividualCalls(F);
3305 // Optimizations for weak pointers.
3306 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3307 (1 << IC_LoadWeakRetained) |
3308 (1 << IC_StoreWeak) |
3309 (1 << IC_InitWeak) |
3310 (1 << IC_CopyWeak) |
3311 (1 << IC_MoveWeak) |
3312 (1 << IC_DestroyWeak)))
3313 OptimizeWeakCalls(F);
3315 // Optimizations for retain+release pairs.
3316 if (UsedInThisFunction & ((1 << IC_Retain) |
3317 (1 << IC_RetainRV) |
3318 (1 << IC_RetainBlock)))
3319 if (UsedInThisFunction & (1 << IC_Release))
3320 // Run OptimizeSequences until it either stops making changes or
3321 // no retain+release pair nesting is detected.
3322 while (OptimizeSequences(F)) {}
3324 // Optimizations if objc_autorelease is used.
3325 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3326 (1 << IC_AutoreleaseRV)))
3329 DEBUG(dbgs() << "\n");
3334 void ObjCARCOpt::releaseMemory() {
3340 /// \defgroup ARCContract ARC Contraction.
3343 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
3344 // dominated by single calls.
3346 #include "llvm/Analysis/Dominators.h"
3347 #include "llvm/IR/InlineAsm.h"
3348 #include "llvm/IR/Operator.h"
3350 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3353 /// \brief Late ARC optimizations
3355 /// These change the IR in a way that makes it difficult to be analyzed by
3356 /// ObjCARCOpt, so it's run late.
3357 class ObjCARCContract : public FunctionPass {
3361 ProvenanceAnalysis PA;
3363 /// A flag indicating whether this optimization pass should run.
3366 /// Declarations for ObjC runtime functions, for use in creating calls to
3367 /// them. These are initialized lazily to avoid cluttering up the Module
3368 /// with unused declarations.
3370 /// Declaration for objc_storeStrong().
3371 Constant *StoreStrongCallee;
3372 /// Declaration for objc_retainAutorelease().
3373 Constant *RetainAutoreleaseCallee;
3374 /// Declaration for objc_retainAutoreleaseReturnValue().
3375 Constant *RetainAutoreleaseRVCallee;
3377 /// The inline asm string to insert between calls and RetainRV calls to make
3378 /// the optimization work on targets which need it.
3379 const MDString *RetainRVMarker;
3381 /// The set of inserted objc_storeStrong calls. If at the end of walking the
3382 /// function we have found no alloca instructions, these calls can be marked
3384 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
3386 Constant *getStoreStrongCallee(Module *M);
3387 Constant *getRetainAutoreleaseCallee(Module *M);
3388 Constant *getRetainAutoreleaseRVCallee(Module *M);
3390 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3391 InstructionClass Class,
3392 SmallPtrSet<Instruction *, 4>
3393 &DependingInstructions,
3394 SmallPtrSet<const BasicBlock *, 4>
3397 void ContractRelease(Instruction *Release,
3398 inst_iterator &Iter);
3400 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3401 virtual bool doInitialization(Module &M);
3402 virtual bool runOnFunction(Function &F);
3406 ObjCARCContract() : FunctionPass(ID) {
3407 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3412 char ObjCARCContract::ID = 0;
3413 INITIALIZE_PASS_BEGIN(ObjCARCContract,
3414 "objc-arc-contract", "ObjC ARC contraction", false, false)
3415 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3416 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3417 INITIALIZE_PASS_END(ObjCARCContract,
3418 "objc-arc-contract", "ObjC ARC contraction", false, false)
3420 Pass *llvm::createObjCARCContractPass() {
3421 return new ObjCARCContract();
3424 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3425 AU.addRequired<AliasAnalysis>();
3426 AU.addRequired<DominatorTree>();
3427 AU.setPreservesCFG();
3430 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3431 if (!StoreStrongCallee) {
3432 LLVMContext &C = M->getContext();
3433 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3434 Type *I8XX = PointerType::getUnqual(I8X);
3435 Type *Params[] = { I8XX, I8X };
3437 AttributeSet Attr = AttributeSet()
3438 .addAttribute(M->getContext(), AttributeSet::FunctionIndex,
3439 Attribute::NoUnwind)
3440 .addAttribute(M->getContext(), 1, Attribute::NoCapture);
3443 M->getOrInsertFunction(
3445 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3448 return StoreStrongCallee;
3451 Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3452 if (!RetainAutoreleaseCallee) {
3453 LLVMContext &C = M->getContext();
3454 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3455 Type *Params[] = { I8X };
3456 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
3457 AttributeSet Attribute =
3458 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
3459 Attribute::NoUnwind);
3460 RetainAutoreleaseCallee =
3461 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
3463 return RetainAutoreleaseCallee;
3466 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3467 if (!RetainAutoreleaseRVCallee) {
3468 LLVMContext &C = M->getContext();
3469 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3470 Type *Params[] = { I8X };
3471 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
3472 AttributeSet Attribute =
3473 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
3474 Attribute::NoUnwind);
3475 RetainAutoreleaseRVCallee =
3476 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3479 return RetainAutoreleaseRVCallee;
3482 /// Merge an autorelease with a retain into a fused call.
3484 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3485 InstructionClass Class,
3486 SmallPtrSet<Instruction *, 4>
3487 &DependingInstructions,
3488 SmallPtrSet<const BasicBlock *, 4>
3490 const Value *Arg = GetObjCArg(Autorelease);
3492 // Check that there are no instructions between the retain and the autorelease
3493 // (such as an autorelease_pop) which may change the count.
3494 CallInst *Retain = 0;
3495 if (Class == IC_AutoreleaseRV)
3496 FindDependencies(RetainAutoreleaseRVDep, Arg,
3497 Autorelease->getParent(), Autorelease,
3498 DependingInstructions, Visited, PA);
3500 FindDependencies(RetainAutoreleaseDep, Arg,
3501 Autorelease->getParent(), Autorelease,
3502 DependingInstructions, Visited, PA);
3505 if (DependingInstructions.size() != 1) {
3506 DependingInstructions.clear();
3510 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3511 DependingInstructions.clear();
3514 GetBasicInstructionClass(Retain) != IC_Retain ||
3515 GetObjCArg(Retain) != Arg)
3521 DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing "
3522 "retain/autorelease. Erasing: " << *Autorelease << "\n"
3524 << *Retain << "\n");
3526 if (Class == IC_AutoreleaseRV)
3527 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3529 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3531 DEBUG(dbgs() << " New Retain: "
3532 << *Retain << "\n");
3534 EraseInstruction(Autorelease);
3538 /// Attempt to merge an objc_release with a store, load, and objc_retain to form
3539 /// an objc_storeStrong. This can be a little tricky because the instructions
3540 /// don't always appear in order, and there may be unrelated intervening
3542 void ObjCARCContract::ContractRelease(Instruction *Release,
3543 inst_iterator &Iter) {
3544 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
3545 if (!Load || !Load->isSimple()) return;
3547 // For now, require everything to be in one basic block.
3548 BasicBlock *BB = Release->getParent();
3549 if (Load->getParent() != BB) return;
3551 // Walk down to find the store and the release, which may be in either order.
3552 BasicBlock::iterator I = Load, End = BB->end();
3554 AliasAnalysis::Location Loc = AA->getLocation(Load);
3555 StoreInst *Store = 0;
3556 bool SawRelease = false;
3557 for (; !Store || !SawRelease; ++I) {
3561 Instruction *Inst = I;
3562 if (Inst == Release) {
3567 InstructionClass Class = GetBasicInstructionClass(Inst);
3569 // Unrelated retains are harmless.
3570 if (IsRetain(Class))
3574 // The store is the point where we're going to put the objc_storeStrong,
3575 // so make sure there are no uses after it.
3576 if (CanUse(Inst, Load, PA, Class))
3578 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
3579 // We are moving the load down to the store, so check for anything
3580 // else which writes to the memory between the load and the store.
3581 Store = dyn_cast<StoreInst>(Inst);
3582 if (!Store || !Store->isSimple()) return;
3583 if (Store->getPointerOperand() != Loc.Ptr) return;
3587 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3589 // Walk up to find the retain.
3591 BasicBlock::iterator Begin = BB->begin();
3592 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3594 Instruction *Retain = I;
3595 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3596 if (GetObjCArg(Retain) != New) return;
3601 LLVMContext &C = Release->getContext();
3602 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3603 Type *I8XX = PointerType::getUnqual(I8X);
3605 Value *Args[] = { Load->getPointerOperand(), New };
3606 if (Args[0]->getType() != I8XX)
3607 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3608 if (Args[1]->getType() != I8X)
3609 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3610 CallInst *StoreStrong =
3611 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
3613 StoreStrong->setDoesNotThrow();
3614 StoreStrong->setDebugLoc(Store->getDebugLoc());
3616 // We can't set the tail flag yet, because we haven't yet determined
3617 // whether there are any escaping allocas. Remember this call, so that
3618 // we can set the tail flag once we know it's safe.
3619 StoreStrongCalls.insert(StoreStrong);
3621 if (&*Iter == Store) ++Iter;
3622 Store->eraseFromParent();
3623 Release->eraseFromParent();
3624 EraseInstruction(Retain);
3625 if (Load->use_empty())
3626 Load->eraseFromParent();
3629 bool ObjCARCContract::doInitialization(Module &M) {
3630 // If nothing in the Module uses ARC, don't do anything.
3631 Run = ModuleHasARC(M);
3635 // These are initialized lazily.
3636 StoreStrongCallee = 0;
3637 RetainAutoreleaseCallee = 0;
3638 RetainAutoreleaseRVCallee = 0;
3640 // Initialize RetainRVMarker.
3642 if (NamedMDNode *NMD =
3643 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3644 if (NMD->getNumOperands() == 1) {
3645 const MDNode *N = NMD->getOperand(0);
3646 if (N->getNumOperands() == 1)
3647 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
3654 bool ObjCARCContract::runOnFunction(Function &F) {
3658 // If nothing in the Module uses ARC, don't do anything.
3663 AA = &getAnalysis<AliasAnalysis>();
3664 DT = &getAnalysis<DominatorTree>();
3666 PA.setAA(&getAnalysis<AliasAnalysis>());
3668 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
3669 // keyword. Be conservative if the function has variadic arguments.
3670 // It seems that functions which "return twice" are also unsafe for the
3671 // "tail" argument, because they are setjmp, which could need to
3672 // return to an earlier stack state.
3673 bool TailOkForStoreStrongs = !F.isVarArg() &&
3674 !F.callsFunctionThatReturnsTwice();
3676 // For ObjC library calls which return their argument, replace uses of the
3677 // argument with uses of the call return value, if it dominates the use. This
3678 // reduces register pressure.
3679 SmallPtrSet<Instruction *, 4> DependingInstructions;
3680 SmallPtrSet<const BasicBlock *, 4> Visited;
3681 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3682 Instruction *Inst = &*I++;
3684 DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
3686 // Only these library routines return their argument. In particular,
3687 // objc_retainBlock does not necessarily return its argument.
3688 InstructionClass Class = GetBasicInstructionClass(Inst);
3691 case IC_FusedRetainAutorelease:
3692 case IC_FusedRetainAutoreleaseRV:
3694 case IC_Autorelease:
3695 case IC_AutoreleaseRV:
3696 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
3700 // If we're compiling for a target which needs a special inline-asm
3701 // marker to do the retainAutoreleasedReturnValue optimization,
3703 if (!RetainRVMarker)
3705 BasicBlock::iterator BBI = Inst;
3706 BasicBlock *InstParent = Inst->getParent();
3708 // Step up to see if the call immediately precedes the RetainRV call.
3709 // If it's an invoke, we have to cross a block boundary. And we have
3710 // to carefully dodge no-op instructions.
3712 if (&*BBI == InstParent->begin()) {
3713 BasicBlock *Pred = InstParent->getSinglePredecessor();
3715 goto decline_rv_optimization;
3716 BBI = Pred->getTerminator();
3720 } while (isNoopInstruction(BBI));
3722 if (&*BBI == GetObjCArg(Inst)) {
3723 DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
3724 "retainAutoreleasedReturnValue optimization.\n");
3727 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
3728 /*isVarArg=*/false),
3729 RetainRVMarker->getString(),
3730 /*Constraints=*/"", /*hasSideEffects=*/true);
3731 CallInst::Create(IA, "", Inst);
3733 decline_rv_optimization:
3737 // objc_initWeak(p, null) => *p = null
3738 CallInst *CI = cast<CallInst>(Inst);
3739 if (isNullOrUndef(CI->getArgOperand(1))) {
3741 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
3743 new StoreInst(Null, CI->getArgOperand(0), CI);
3745 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
3746 << " New = " << *Null << "\n");
3748 CI->replaceAllUsesWith(Null);
3749 CI->eraseFromParent();
3754 ContractRelease(Inst, I);
3757 // Be conservative if the function has any alloca instructions.
3758 // Technically we only care about escaping alloca instructions,
3759 // but this is sufficient to handle some interesting cases.
3760 if (isa<AllocaInst>(Inst))
3761 TailOkForStoreStrongs = false;
3767 DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n");
3769 // Don't use GetObjCArg because we don't want to look through bitcasts
3770 // and such; to do the replacement, the argument must have type i8*.
3771 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
3773 // If we're compiling bugpointed code, don't get in trouble.
3774 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
3776 // Look through the uses of the pointer.
3777 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
3779 Use &U = UI.getUse();
3780 unsigned OperandNo = UI.getOperandNo();
3781 ++UI; // Increment UI now, because we may unlink its element.
3783 // If the call's return value dominates a use of the call's argument
3784 // value, rewrite the use to use the return value. We check for
3785 // reachability here because an unreachable call is considered to
3786 // trivially dominate itself, which would lead us to rewriting its
3787 // argument in terms of its return value, which would lead to
3788 // infinite loops in GetObjCArg.
3789 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
3791 Instruction *Replacement = Inst;
3792 Type *UseTy = U.get()->getType();
3793 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
3794 // For PHI nodes, insert the bitcast in the predecessor block.
3795 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
3796 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
3797 if (Replacement->getType() != UseTy)
3798 Replacement = new BitCastInst(Replacement, UseTy, "",
3800 // While we're here, rewrite all edges for this PHI, rather
3801 // than just one use at a time, to minimize the number of
3802 // bitcasts we emit.
3803 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
3804 if (PHI->getIncomingBlock(i) == BB) {
3805 // Keep the UI iterator valid.
3806 if (&PHI->getOperandUse(
3807 PHINode::getOperandNumForIncomingValue(i)) ==
3810 PHI->setIncomingValue(i, Replacement);
3813 if (Replacement->getType() != UseTy)
3814 Replacement = new BitCastInst(Replacement, UseTy, "",
3815 cast<Instruction>(U.getUser()));
3821 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
3822 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
3823 Arg = BI->getOperand(0);
3824 else if (isa<GEPOperator>(Arg) &&
3825 cast<GEPOperator>(Arg)->hasAllZeroIndices())
3826 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
3827 else if (isa<GlobalAlias>(Arg) &&
3828 !cast<GlobalAlias>(Arg)->mayBeOverridden())
3829 Arg = cast<GlobalAlias>(Arg)->getAliasee();
3835 // If this function has no escaping allocas or suspicious vararg usage,
3836 // objc_storeStrong calls can be marked with the "tail" keyword.
3837 if (TailOkForStoreStrongs)
3838 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
3839 E = StoreStrongCalls.end(); I != E; ++I)
3840 (*I)->setTailCall();
3841 StoreStrongCalls.clear();