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"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/STLExtras.h"
39 using namespace llvm::objcarc;
41 /// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
45 /// \brief An associative container with fast insertion-order (deterministic)
46 /// iteration over its elements. Plus the special blot operation.
47 template<class KeyT, class ValueT>
49 /// Map keys to indices in Vector.
50 typedef DenseMap<KeyT, size_t> MapTy;
53 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
58 typedef typename VectorTy::iterator iterator;
59 typedef typename VectorTy::const_iterator const_iterator;
60 iterator begin() { return Vector.begin(); }
61 iterator end() { return Vector.end(); }
62 const_iterator begin() const { return Vector.begin(); }
63 const_iterator end() const { return Vector.end(); }
67 assert(Vector.size() >= Map.size()); // May differ due to blotting.
68 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
70 assert(I->second < Vector.size());
71 assert(Vector[I->second].first == I->first);
73 for (typename VectorTy::const_iterator I = Vector.begin(),
74 E = Vector.end(); I != E; ++I)
76 (Map.count(I->first) &&
77 Map[I->first] == size_t(I - Vector.begin())));
81 ValueT &operator[](const KeyT &Arg) {
82 std::pair<typename MapTy::iterator, bool> Pair =
83 Map.insert(std::make_pair(Arg, size_t(0)));
85 size_t Num = Vector.size();
86 Pair.first->second = Num;
87 Vector.push_back(std::make_pair(Arg, ValueT()));
88 return Vector[Num].second;
90 return Vector[Pair.first->second].second;
93 std::pair<iterator, bool>
94 insert(const std::pair<KeyT, ValueT> &InsertPair) {
95 std::pair<typename MapTy::iterator, bool> Pair =
96 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
98 size_t Num = Vector.size();
99 Pair.first->second = Num;
100 Vector.push_back(InsertPair);
101 return std::make_pair(Vector.begin() + Num, true);
103 return std::make_pair(Vector.begin() + Pair.first->second, false);
106 const_iterator find(const KeyT &Key) const {
107 typename MapTy::const_iterator It = Map.find(Key);
108 if (It == Map.end()) return Vector.end();
109 return Vector.begin() + It->second;
112 /// This is similar to erase, but instead of removing the element from the
113 /// vector, it just zeros out the key in the vector. This leaves iterators
114 /// intact, but clients must be prepared for zeroed-out keys when iterating.
115 void blot(const KeyT &Key) {
116 typename MapTy::iterator It = Map.find(Key);
117 if (It == Map.end()) return;
118 Vector[It->second].first = KeyT();
131 /// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
134 #include "llvm/Analysis/ValueTracking.h"
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 Test if the given class is objc_retain or equivalent.
264 static bool IsRetain(InstructionClass Class) {
265 return Class == IC_Retain ||
266 Class == IC_RetainRV;
269 /// \brief Test if the given class is objc_autorelease or equivalent.
270 static bool IsAutorelease(InstructionClass Class) {
271 return Class == IC_Autorelease ||
272 Class == IC_AutoreleaseRV;
275 /// \brief Test if the given class represents instructions which return their
276 /// argument verbatim.
277 static bool IsForwarding(InstructionClass Class) {
278 // objc_retainBlock technically doesn't always return its argument
279 // verbatim, but it doesn't matter for our purposes here.
280 return Class == IC_Retain ||
281 Class == IC_RetainRV ||
282 Class == IC_Autorelease ||
283 Class == IC_AutoreleaseRV ||
284 Class == IC_RetainBlock ||
285 Class == IC_NoopCast;
288 /// \brief Test if the given class represents instructions which do nothing if
289 /// passed a null pointer.
290 static bool IsNoopOnNull(InstructionClass Class) {
291 return Class == IC_Retain ||
292 Class == IC_RetainRV ||
293 Class == IC_Release ||
294 Class == IC_Autorelease ||
295 Class == IC_AutoreleaseRV ||
296 Class == IC_RetainBlock;
299 /// \brief Test if the given class represents instructions which are always safe
300 /// to mark with the "tail" keyword.
301 static bool IsAlwaysTail(InstructionClass Class) {
302 // IC_RetainBlock may be given a stack argument.
303 return Class == IC_Retain ||
304 Class == IC_RetainRV ||
305 Class == IC_AutoreleaseRV;
308 /// \brief Test if the given class represents instructions which are never safe
309 /// to mark with the "tail" keyword.
310 static bool IsNeverTail(InstructionClass Class) {
311 /// It is never safe to tail call objc_autorelease since by tail calling
312 /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
313 /// fast autoreleasing causing our object to be potentially reclaimed from the
314 /// autorelease pool which violates the semantics of __autoreleasing types in
316 return Class == IC_Autorelease;
319 /// \brief Test if the given class represents instructions which are always safe
320 /// to mark with the nounwind attribute.
321 static bool IsNoThrow(InstructionClass Class) {
322 // objc_retainBlock is not nounwind because it calls user copy constructors
323 // which could theoretically throw.
324 return Class == IC_Retain ||
325 Class == IC_RetainRV ||
326 Class == IC_Release ||
327 Class == IC_Autorelease ||
328 Class == IC_AutoreleaseRV ||
329 Class == IC_AutoreleasepoolPush ||
330 Class == IC_AutoreleasepoolPop;
333 /// \brief Erase the given instruction.
335 /// Many ObjC calls return their argument verbatim,
336 /// so if it's such a call and the return value has users, replace them with the
339 static void EraseInstruction(Instruction *CI) {
340 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
342 bool Unused = CI->use_empty();
345 // Replace the return value with the argument.
346 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
347 "Can't delete non-forwarding instruction with users!");
348 CI->replaceAllUsesWith(OldArg);
351 CI->eraseFromParent();
354 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
357 /// \brief This is a wrapper around getUnderlyingObject which also knows how to
358 /// look through objc_retain and objc_autorelease calls, which we know to return
359 /// their argument verbatim.
360 static const Value *GetUnderlyingObjCPtr(const Value *V) {
362 V = GetUnderlyingObject(V);
363 if (!IsForwarding(GetBasicInstructionClass(V)))
365 V = cast<CallInst>(V)->getArgOperand(0);
371 /// \brief This is a wrapper around Value::stripPointerCasts which also knows
372 /// how to look through objc_retain and objc_autorelease calls, which we know to
373 /// return their argument verbatim.
374 static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
376 V = V->stripPointerCasts();
377 if (!IsForwarding(GetBasicInstructionClass(V)))
379 V = cast<CallInst>(V)->getArgOperand(0);
384 /// \brief This is a wrapper around Value::stripPointerCasts which also knows
385 /// how to look through objc_retain and objc_autorelease calls, which we know to
386 /// return their argument verbatim.
387 static Value *StripPointerCastsAndObjCCalls(Value *V) {
389 V = V->stripPointerCasts();
390 if (!IsForwarding(GetBasicInstructionClass(V)))
392 V = cast<CallInst>(V)->getArgOperand(0);
397 /// \brief Assuming the given instruction is one of the special calls such as
398 /// objc_retain or objc_release, return the argument value, stripped of no-op
399 /// casts and forwarding calls.
400 static Value *GetObjCArg(Value *Inst) {
401 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
404 /// \brief Return true if this value refers to a distinct and identifiable
407 /// This is similar to AliasAnalysis's isIdentifiedObject, except that it uses
408 /// special knowledge of ObjC conventions.
409 static bool IsObjCIdentifiedObject(const Value *V) {
410 // Assume that call results and arguments have their own "provenance".
411 // Constants (including GlobalVariables) and Allocas are never
412 // reference-counted.
413 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
414 isa<Argument>(V) || isa<Constant>(V) ||
418 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
419 const Value *Pointer =
420 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
421 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
422 // A constant pointer can't be pointing to an object on the heap. It may
423 // be reference-counted, but it won't be deleted.
424 if (GV->isConstant())
426 StringRef Name = GV->getName();
427 // These special variables are known to hold values which are not
428 // reference-counted pointers.
429 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
430 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
431 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
432 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
433 Name.startswith("\01l_objc_msgSend_fixup_"))
441 /// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
442 /// as it finds a value with multiple uses.
443 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
444 if (Arg->hasOneUse()) {
445 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
446 return FindSingleUseIdentifiedObject(BC->getOperand(0));
447 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
448 if (GEP->hasAllZeroIndices())
449 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
450 if (IsForwarding(GetBasicInstructionClass(Arg)))
451 return FindSingleUseIdentifiedObject(
452 cast<CallInst>(Arg)->getArgOperand(0));
453 if (!IsObjCIdentifiedObject(Arg))
458 // If we found an identifiable object but it has multiple uses, but they are
459 // trivial uses, we can still consider this to be a single-use value.
460 if (IsObjCIdentifiedObject(Arg)) {
461 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
464 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
474 /// \brief Test whether the given pointer, which is an Objective C block
475 /// pointer, does not "escape".
477 /// This differs from regular escape analysis in that a use as an
478 /// argument to a call is not considered an escape.
480 static bool DoesObjCBlockEscape(const Value *BlockPtr) {
482 DEBUG(dbgs() << "DoesObjCBlockEscape: Target: " << *BlockPtr << "\n");
484 // Walk the def-use chains.
485 SmallVector<const Value *, 4> Worklist;
486 Worklist.push_back(BlockPtr);
488 // Ensure we do not visit any value twice.
489 SmallPtrSet<const Value *, 4> VisitedSet;
492 const Value *V = Worklist.pop_back_val();
494 DEBUG(dbgs() << "DoesObjCBlockEscape: Visiting: " << *V << "\n");
496 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
498 const User *UUser = *UI;
500 DEBUG(dbgs() << "DoesObjCBlockEscape: User: " << *UUser << "\n");
502 // Special - Use by a call (callee or argument) is not considered
504 switch (GetBasicInstructionClass(UUser)) {
509 case IC_AutoreleaseRV: {
510 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies pointer arguments. "
512 // These special functions make copies of their pointer arguments.
517 // Use by an instruction which copies the value is an escape if the
518 // result is an escape.
519 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
520 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
522 if (!VisitedSet.insert(UUser)) {
523 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies value. Escapes "
524 "if result escapes. Adding to list.\n");
525 Worklist.push_back(UUser);
527 DEBUG(dbgs() << "DoesObjCBlockEscape: Already visited node.\n");
531 // Use by a load is not an escape.
532 if (isa<LoadInst>(UUser))
534 // Use by a store is not an escape if the use is the address.
535 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
536 if (V != SI->getValueOperand())
540 // Regular calls and other stuff are not considered escapes.
543 // Otherwise, conservatively assume an escape.
544 DEBUG(dbgs() << "DoesObjCBlockEscape: Assuming block escapes.\n");
547 } while (!Worklist.empty());
550 DEBUG(dbgs() << "DoesObjCBlockEscape: Block does not escape.\n");
556 /// \defgroup ARCAA Extends alias analysis using ObjC specific knowledge.
560 /// \brief This is a simple alias analysis implementation that uses knowledge
561 /// of ARC constructs to answer queries.
563 /// TODO: This class could be generalized to know about other ObjC-specific
564 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
565 /// even though their offsets are dynamic.
566 class ObjCARCAliasAnalysis : public ImmutablePass,
567 public AliasAnalysis {
569 static char ID; // Class identification, replacement for typeinfo
570 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
571 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
575 virtual void initializePass() {
576 InitializeAliasAnalysis(this);
579 /// This method is used when a pass implements an analysis interface through
580 /// multiple inheritance. If needed, it should override this to adjust the
581 /// this pointer as needed for the specified pass info.
582 virtual void *getAdjustedAnalysisPointer(const void *PI) {
583 if (PI == &AliasAnalysis::ID)
584 return static_cast<AliasAnalysis *>(this);
588 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
589 virtual AliasResult alias(const Location &LocA, const Location &LocB);
590 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
591 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
592 virtual ModRefBehavior getModRefBehavior(const Function *F);
593 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
594 const Location &Loc);
595 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
596 ImmutableCallSite CS2);
598 } // End of anonymous namespace
600 // Register this pass...
601 char ObjCARCAliasAnalysis::ID = 0;
602 INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
603 "ObjC-ARC-Based Alias Analysis", false, true, false)
605 ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
606 return new ObjCARCAliasAnalysis();
610 ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
611 AU.setPreservesAll();
612 AliasAnalysis::getAnalysisUsage(AU);
615 AliasAnalysis::AliasResult
616 ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
618 return AliasAnalysis::alias(LocA, LocB);
620 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
621 // precise alias query.
622 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
623 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
625 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
626 Location(SB, LocB.Size, LocB.TBAATag));
627 if (Result != MayAlias)
630 // If that failed, climb to the underlying object, including climbing through
631 // ObjC-specific no-ops, and try making an imprecise alias query.
632 const Value *UA = GetUnderlyingObjCPtr(SA);
633 const Value *UB = GetUnderlyingObjCPtr(SB);
634 if (UA != SA || UB != SB) {
635 Result = AliasAnalysis::alias(Location(UA), Location(UB));
636 // We can't use MustAlias or PartialAlias results here because
637 // GetUnderlyingObjCPtr may return an offsetted pointer value.
638 if (Result == NoAlias)
642 // If that failed, fail. We don't need to chain here, since that's covered
643 // by the earlier precise query.
648 ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
651 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
653 // First, strip off no-ops, including ObjC-specific no-ops, and try making
654 // a precise alias query.
655 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
656 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
660 // If that failed, climb to the underlying object, including climbing through
661 // ObjC-specific no-ops, and try making an imprecise alias query.
662 const Value *U = GetUnderlyingObjCPtr(S);
664 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
666 // If that failed, fail. We don't need to chain here, since that's covered
667 // by the earlier precise query.
671 AliasAnalysis::ModRefBehavior
672 ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
673 // We have nothing to do. Just chain to the next AliasAnalysis.
674 return AliasAnalysis::getModRefBehavior(CS);
677 AliasAnalysis::ModRefBehavior
678 ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
680 return AliasAnalysis::getModRefBehavior(F);
682 switch (GetFunctionClass(F)) {
684 return DoesNotAccessMemory;
689 return AliasAnalysis::getModRefBehavior(F);
692 AliasAnalysis::ModRefResult
693 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
695 return AliasAnalysis::getModRefInfo(CS, Loc);
697 switch (GetBasicInstructionClass(CS.getInstruction())) {
701 case IC_AutoreleaseRV:
703 case IC_AutoreleasepoolPush:
704 case IC_FusedRetainAutorelease:
705 case IC_FusedRetainAutoreleaseRV:
706 // These functions don't access any memory visible to the compiler.
707 // Note that this doesn't include objc_retainBlock, because it updates
708 // pointers when it copies block data.
714 return AliasAnalysis::getModRefInfo(CS, Loc);
717 AliasAnalysis::ModRefResult
718 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
719 ImmutableCallSite CS2) {
720 // TODO: Theoretically we could check for dependencies between objc_* calls
721 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
722 return AliasAnalysis::getModRefInfo(CS1, CS2);
727 /// \defgroup ARCOpt ARC Optimization.
730 // TODO: On code like this:
733 // stuff_that_cannot_release()
734 // objc_autorelease(%x)
735 // stuff_that_cannot_release()
737 // stuff_that_cannot_release()
738 // objc_autorelease(%x)
740 // The second retain and autorelease can be deleted.
742 // TODO: It should be possible to delete
743 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
744 // pairs if nothing is actually autoreleased between them. Also, autorelease
745 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
746 // after inlining) can be turned into plain release calls.
748 // TODO: Critical-edge splitting. If the optimial insertion point is
749 // a critical edge, the current algorithm has to fail, because it doesn't
750 // know how to split edges. It should be possible to make the optimizer
751 // think in terms of edges, rather than blocks, and then split critical
754 // TODO: OptimizeSequences could generalized to be Interprocedural.
756 // TODO: Recognize that a bunch of other objc runtime calls have
757 // non-escaping arguments and non-releasing arguments, and may be
758 // non-autoreleasing.
760 // TODO: Sink autorelease calls as far as possible. Unfortunately we
761 // usually can't sink them past other calls, which would be the main
762 // case where it would be useful.
764 // TODO: The pointer returned from objc_loadWeakRetained is retained.
766 // TODO: Delete release+retain pairs (rare).
768 #include "llvm/ADT/SmallPtrSet.h"
769 #include "llvm/ADT/Statistic.h"
770 #include "llvm/IR/LLVMContext.h"
771 #include "llvm/Support/CFG.h"
773 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
774 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
775 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
776 STATISTIC(NumRets, "Number of return value forwarding "
777 "retain+autoreleaes eliminated");
778 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
779 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
782 /// \brief This is similar to BasicAliasAnalysis, and it uses many of the same
783 /// techniques, except it uses special ObjC-specific reasoning about pointer
786 /// In this context ``Provenance'' is defined as the history of an object's
787 /// ownership. Thus ``Provenance Analysis'' is defined by using the notion of
788 /// an ``independent provenance source'' of a pointer to determine whether or
789 /// not two pointers have the same provenance source and thus could
790 /// potentially be related.
791 class ProvenanceAnalysis {
794 typedef std::pair<const Value *, const Value *> ValuePairTy;
795 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
796 CachedResultsTy CachedResults;
798 bool relatedCheck(const Value *A, const Value *B);
799 bool relatedSelect(const SelectInst *A, const Value *B);
800 bool relatedPHI(const PHINode *A, const Value *B);
802 void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
803 ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
806 ProvenanceAnalysis() {}
808 void setAA(AliasAnalysis *aa) { AA = aa; }
810 AliasAnalysis *getAA() const { return AA; }
812 bool related(const Value *A, const Value *B);
815 CachedResults.clear();
820 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
821 // If the values are Selects with the same condition, we can do a more precise
822 // check: just check for relations between the values on corresponding arms.
823 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
824 if (A->getCondition() == SB->getCondition())
825 return related(A->getTrueValue(), SB->getTrueValue()) ||
826 related(A->getFalseValue(), SB->getFalseValue());
828 // Check both arms of the Select node individually.
829 return related(A->getTrueValue(), B) ||
830 related(A->getFalseValue(), B);
833 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
834 // If the values are PHIs in the same block, we can do a more precise as well
835 // as efficient check: just check for relations between the values on
836 // corresponding edges.
837 if (const PHINode *PNB = dyn_cast<PHINode>(B))
838 if (PNB->getParent() == A->getParent()) {
839 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
840 if (related(A->getIncomingValue(i),
841 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
846 // Check each unique source of the PHI node against B.
847 SmallPtrSet<const Value *, 4> UniqueSrc;
848 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
849 const Value *PV1 = A->getIncomingValue(i);
850 if (UniqueSrc.insert(PV1) && related(PV1, B))
854 // All of the arms checked out.
858 /// Test if the value of P, or any value covered by its provenance, is ever
859 /// stored within the function (not counting callees).
860 static bool isStoredObjCPointer(const Value *P) {
861 SmallPtrSet<const Value *, 8> Visited;
862 SmallVector<const Value *, 8> Worklist;
863 Worklist.push_back(P);
866 P = Worklist.pop_back_val();
867 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
869 const User *Ur = *UI;
870 if (isa<StoreInst>(Ur)) {
871 if (UI.getOperandNo() == 0)
872 // The pointer is stored.
874 // The pointed is stored through.
877 if (isa<CallInst>(Ur))
878 // The pointer is passed as an argument, ignore this.
880 if (isa<PtrToIntInst>(P))
883 if (Visited.insert(Ur))
884 Worklist.push_back(Ur);
886 } while (!Worklist.empty());
888 // Everything checked out.
892 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
893 // Skip past provenance pass-throughs.
894 A = GetUnderlyingObjCPtr(A);
895 B = GetUnderlyingObjCPtr(B);
901 // Ask regular AliasAnalysis, for a first approximation.
902 switch (AA->alias(A, B)) {
903 case AliasAnalysis::NoAlias:
905 case AliasAnalysis::MustAlias:
906 case AliasAnalysis::PartialAlias:
908 case AliasAnalysis::MayAlias:
912 bool AIsIdentified = IsObjCIdentifiedObject(A);
913 bool BIsIdentified = IsObjCIdentifiedObject(B);
915 // An ObjC-Identified object can't alias a load if it is never locally stored.
917 // Check for an obvious escape.
918 if (isa<LoadInst>(B))
919 return isStoredObjCPointer(A);
921 // Check for an obvious escape.
922 if (isa<LoadInst>(A))
923 return isStoredObjCPointer(B);
924 // Both pointers are identified and escapes aren't an evident problem.
927 } else if (BIsIdentified) {
928 // Check for an obvious escape.
929 if (isa<LoadInst>(A))
930 return isStoredObjCPointer(B);
933 // Special handling for PHI and Select.
934 if (const PHINode *PN = dyn_cast<PHINode>(A))
935 return relatedPHI(PN, B);
936 if (const PHINode *PN = dyn_cast<PHINode>(B))
937 return relatedPHI(PN, A);
938 if (const SelectInst *S = dyn_cast<SelectInst>(A))
939 return relatedSelect(S, B);
940 if (const SelectInst *S = dyn_cast<SelectInst>(B))
941 return relatedSelect(S, A);
947 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
948 // Begin by inserting a conservative value into the map. If the insertion
949 // fails, we have the answer already. If it succeeds, leave it there until we
950 // compute the real answer to guard against recursive queries.
951 if (A > B) std::swap(A, B);
952 std::pair<CachedResultsTy::iterator, bool> Pair =
953 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
955 return Pair.first->second;
957 bool Result = relatedCheck(A, B);
958 CachedResults[ValuePairTy(A, B)] = Result;
965 /// \brief A sequence of states that a pointer may go through in which an
966 /// objc_retain and objc_release are actually needed.
969 S_Retain, ///< objc_retain(x)
970 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
971 S_Use, ///< any use of x
972 S_Stop, ///< like S_Release, but code motion is stopped
973 S_Release, ///< objc_release(x)
974 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
978 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
982 if (A == S_None || B == S_None)
985 if (A > B) std::swap(A, B);
987 // Choose the side which is further along in the sequence.
988 if ((A == S_Retain || A == S_CanRelease) &&
989 (B == S_CanRelease || B == S_Use))
992 // Choose the side which is further along in the sequence.
993 if ((A == S_Use || A == S_CanRelease) &&
994 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
996 // If both sides are releases, choose the more conservative one.
997 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
999 if (A == S_Release && B == S_MovableRelease)
1007 /// \brief Unidirectional information about either a
1008 /// retain-decrement-use-release sequence or release-use-decrement-retain
1009 /// reverese sequence.
1011 /// After an objc_retain, the reference count of the referenced
1012 /// object is known to be positive. Similarly, before an objc_release, the
1013 /// reference count of the referenced object is known to be positive. If
1014 /// there are retain-release pairs in code regions where the retain count
1015 /// is known to be positive, they can be eliminated, regardless of any side
1016 /// effects between them.
1018 /// Also, a retain+release pair nested within another retain+release
1019 /// pair all on the known same pointer value can be eliminated, regardless
1020 /// of any intervening side effects.
1022 /// KnownSafe is true when either of these conditions is satisfied.
1025 /// True if the Calls are objc_retainBlock calls (as opposed to objc_retain
1029 /// True of the objc_release calls are all marked with the "tail" keyword.
1030 bool IsTailCallRelease;
1032 /// If the Calls are objc_release calls and they all have a
1033 /// clang.imprecise_release tag, this is the metadata tag.
1034 MDNode *ReleaseMetadata;
1036 /// For a top-down sequence, the set of objc_retains or
1037 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1038 SmallPtrSet<Instruction *, 2> Calls;
1040 /// The set of optimal insert positions for moving calls in the opposite
1042 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1045 KnownSafe(false), IsRetainBlock(false),
1046 IsTailCallRelease(false),
1047 ReleaseMetadata(0) {}
1053 void RRInfo::clear() {
1055 IsRetainBlock = false;
1056 IsTailCallRelease = false;
1057 ReleaseMetadata = 0;
1059 ReverseInsertPts.clear();
1063 /// \brief This class summarizes several per-pointer runtime properties which
1064 /// are propogated through the flow graph.
1066 /// True if the reference count is known to be incremented.
1067 bool KnownPositiveRefCount;
1069 /// True of we've seen an opportunity for partial RR elimination, such as
1070 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
1073 /// The current position in the sequence.
1077 /// Unidirectional information about the current sequence.
1079 /// TODO: Encapsulate this better.
1082 PtrState() : KnownPositiveRefCount(false), Partial(false),
1085 void SetKnownPositiveRefCount() {
1086 KnownPositiveRefCount = true;
1089 void ClearRefCount() {
1090 KnownPositiveRefCount = false;
1093 bool IsKnownIncremented() const {
1094 return KnownPositiveRefCount;
1097 void SetSeq(Sequence NewSeq) {
1101 Sequence GetSeq() const {
1105 void ClearSequenceProgress() {
1106 ResetSequenceProgress(S_None);
1109 void ResetSequenceProgress(Sequence NewSeq) {
1115 void Merge(const PtrState &Other, bool TopDown);
1120 PtrState::Merge(const PtrState &Other, bool TopDown) {
1121 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1122 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
1124 // We can't merge a plain objc_retain with an objc_retainBlock.
1125 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1128 // If we're not in a sequence (anymore), drop all associated state.
1129 if (Seq == S_None) {
1132 } else if (Partial || Other.Partial) {
1133 // If we're doing a merge on a path that's previously seen a partial
1134 // merge, conservatively drop the sequence, to avoid doing partial
1135 // RR elimination. If the branch predicates for the two merge differ,
1136 // mixing them is unsafe.
1137 ClearSequenceProgress();
1139 // Conservatively merge the ReleaseMetadata information.
1140 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1141 RRI.ReleaseMetadata = 0;
1143 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
1144 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1145 Other.RRI.IsTailCallRelease;
1146 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1148 // Merge the insert point sets. If there are any differences,
1149 // that makes this a partial merge.
1150 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
1151 for (SmallPtrSet<Instruction *, 2>::const_iterator
1152 I = Other.RRI.ReverseInsertPts.begin(),
1153 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1154 Partial |= RRI.ReverseInsertPts.insert(*I);
1159 /// \brief Per-BasicBlock state.
1161 /// The number of unique control paths from the entry which can reach this
1163 unsigned TopDownPathCount;
1165 /// The number of unique control paths to exits from this block.
1166 unsigned BottomUpPathCount;
1168 /// A type for PerPtrTopDown and PerPtrBottomUp.
1169 typedef MapVector<const Value *, PtrState> MapTy;
1171 /// The top-down traversal uses this to record information known about a
1172 /// pointer at the bottom of each block.
1173 MapTy PerPtrTopDown;
1175 /// The bottom-up traversal uses this to record information known about a
1176 /// pointer at the top of each block.
1177 MapTy PerPtrBottomUp;
1179 /// Effective predecessors of the current block ignoring ignorable edges and
1180 /// ignored backedges.
1181 SmallVector<BasicBlock *, 2> Preds;
1182 /// Effective successors of the current block ignoring ignorable edges and
1183 /// ignored backedges.
1184 SmallVector<BasicBlock *, 2> Succs;
1187 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1189 typedef MapTy::iterator ptr_iterator;
1190 typedef MapTy::const_iterator ptr_const_iterator;
1192 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1193 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1194 ptr_const_iterator top_down_ptr_begin() const {
1195 return PerPtrTopDown.begin();
1197 ptr_const_iterator top_down_ptr_end() const {
1198 return PerPtrTopDown.end();
1201 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1202 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1203 ptr_const_iterator bottom_up_ptr_begin() const {
1204 return PerPtrBottomUp.begin();
1206 ptr_const_iterator bottom_up_ptr_end() const {
1207 return PerPtrBottomUp.end();
1210 /// Mark this block as being an entry block, which has one path from the
1211 /// entry by definition.
1212 void SetAsEntry() { TopDownPathCount = 1; }
1214 /// Mark this block as being an exit block, which has one path to an exit by
1216 void SetAsExit() { BottomUpPathCount = 1; }
1218 PtrState &getPtrTopDownState(const Value *Arg) {
1219 return PerPtrTopDown[Arg];
1222 PtrState &getPtrBottomUpState(const Value *Arg) {
1223 return PerPtrBottomUp[Arg];
1226 void clearBottomUpPointers() {
1227 PerPtrBottomUp.clear();
1230 void clearTopDownPointers() {
1231 PerPtrTopDown.clear();
1234 void InitFromPred(const BBState &Other);
1235 void InitFromSucc(const BBState &Other);
1236 void MergePred(const BBState &Other);
1237 void MergeSucc(const BBState &Other);
1239 /// Return the number of possible unique paths from an entry to an exit
1240 /// which pass through this block. This is only valid after both the
1241 /// top-down and bottom-up traversals are complete.
1242 unsigned GetAllPathCount() const {
1243 assert(TopDownPathCount != 0);
1244 assert(BottomUpPathCount != 0);
1245 return TopDownPathCount * BottomUpPathCount;
1248 // Specialized CFG utilities.
1249 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
1250 edge_iterator pred_begin() { return Preds.begin(); }
1251 edge_iterator pred_end() { return Preds.end(); }
1252 edge_iterator succ_begin() { return Succs.begin(); }
1253 edge_iterator succ_end() { return Succs.end(); }
1255 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1256 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1258 bool isExit() const { return Succs.empty(); }
1262 void BBState::InitFromPred(const BBState &Other) {
1263 PerPtrTopDown = Other.PerPtrTopDown;
1264 TopDownPathCount = Other.TopDownPathCount;
1267 void BBState::InitFromSucc(const BBState &Other) {
1268 PerPtrBottomUp = Other.PerPtrBottomUp;
1269 BottomUpPathCount = Other.BottomUpPathCount;
1272 /// The top-down traversal uses this to merge information about predecessors to
1273 /// form the initial state for a new block.
1274 void BBState::MergePred(const BBState &Other) {
1275 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1276 // loop backedge. Loop backedges are special.
1277 TopDownPathCount += Other.TopDownPathCount;
1279 // Check for overflow. If we have overflow, fall back to conservative
1281 if (TopDownPathCount < Other.TopDownPathCount) {
1282 clearTopDownPointers();
1286 // For each entry in the other set, if our set has an entry with the same key,
1287 // merge the entries. Otherwise, copy the entry and merge it with an empty
1289 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1290 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1291 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1292 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1296 // For each entry in our set, if the other set doesn't have an entry with the
1297 // same key, force it to merge with an empty entry.
1298 for (ptr_iterator MI = top_down_ptr_begin(),
1299 ME = top_down_ptr_end(); MI != ME; ++MI)
1300 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1301 MI->second.Merge(PtrState(), /*TopDown=*/true);
1304 /// The bottom-up traversal uses this to merge information about successors to
1305 /// form the initial state for a new block.
1306 void BBState::MergeSucc(const BBState &Other) {
1307 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1308 // loop backedge. Loop backedges are special.
1309 BottomUpPathCount += Other.BottomUpPathCount;
1311 // Check for overflow. If we have overflow, fall back to conservative
1313 if (BottomUpPathCount < Other.BottomUpPathCount) {
1314 clearBottomUpPointers();
1318 // For each entry in the other set, if our set has an entry with the
1319 // same key, merge the entries. Otherwise, copy the entry and merge
1320 // it with an empty entry.
1321 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1322 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1323 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1324 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1328 // For each entry in our set, if the other set doesn't have an entry
1329 // with the same key, force it to merge with an empty entry.
1330 for (ptr_iterator MI = bottom_up_ptr_begin(),
1331 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1332 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1333 MI->second.Merge(PtrState(), /*TopDown=*/false);
1337 /// \brief The main ARC optimization pass.
1338 class ObjCARCOpt : public FunctionPass {
1340 ProvenanceAnalysis PA;
1342 /// A flag indicating whether this optimization pass should run.
1345 /// Declarations for ObjC runtime functions, for use in creating calls to
1346 /// them. These are initialized lazily to avoid cluttering up the Module
1347 /// with unused declarations.
1349 /// Declaration for ObjC runtime function
1350 /// objc_retainAutoreleasedReturnValue.
1351 Constant *RetainRVCallee;
1352 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1353 Constant *AutoreleaseRVCallee;
1354 /// Declaration for ObjC runtime function objc_release.
1355 Constant *ReleaseCallee;
1356 /// Declaration for ObjC runtime function objc_retain.
1357 Constant *RetainCallee;
1358 /// Declaration for ObjC runtime function objc_retainBlock.
1359 Constant *RetainBlockCallee;
1360 /// Declaration for ObjC runtime function objc_autorelease.
1361 Constant *AutoreleaseCallee;
1363 /// Flags which determine whether each of the interesting runtine functions
1364 /// is in fact used in the current function.
1365 unsigned UsedInThisFunction;
1367 /// The Metadata Kind for clang.imprecise_release metadata.
1368 unsigned ImpreciseReleaseMDKind;
1370 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
1371 unsigned CopyOnEscapeMDKind;
1373 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
1374 unsigned NoObjCARCExceptionsMDKind;
1376 Constant *getRetainRVCallee(Module *M);
1377 Constant *getAutoreleaseRVCallee(Module *M);
1378 Constant *getReleaseCallee(Module *M);
1379 Constant *getRetainCallee(Module *M);
1380 Constant *getRetainBlockCallee(Module *M);
1381 Constant *getAutoreleaseCallee(Module *M);
1383 bool IsRetainBlockOptimizable(const Instruction *Inst);
1385 void OptimizeRetainCall(Function &F, Instruction *Retain);
1386 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1387 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1388 InstructionClass &Class);
1389 void OptimizeIndividualCalls(Function &F);
1391 void CheckForCFGHazards(const BasicBlock *BB,
1392 DenseMap<const BasicBlock *, BBState> &BBStates,
1393 BBState &MyStates) const;
1394 bool VisitInstructionBottomUp(Instruction *Inst,
1396 MapVector<Value *, RRInfo> &Retains,
1398 bool VisitBottomUp(BasicBlock *BB,
1399 DenseMap<const BasicBlock *, BBState> &BBStates,
1400 MapVector<Value *, RRInfo> &Retains);
1401 bool VisitInstructionTopDown(Instruction *Inst,
1402 DenseMap<Value *, RRInfo> &Releases,
1404 bool VisitTopDown(BasicBlock *BB,
1405 DenseMap<const BasicBlock *, BBState> &BBStates,
1406 DenseMap<Value *, RRInfo> &Releases);
1407 bool Visit(Function &F,
1408 DenseMap<const BasicBlock *, BBState> &BBStates,
1409 MapVector<Value *, RRInfo> &Retains,
1410 DenseMap<Value *, RRInfo> &Releases);
1412 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1413 MapVector<Value *, RRInfo> &Retains,
1414 DenseMap<Value *, RRInfo> &Releases,
1415 SmallVectorImpl<Instruction *> &DeadInsts,
1418 bool ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState> &BBStates,
1419 MapVector<Value *, RRInfo> &Retains,
1420 DenseMap<Value *, RRInfo> &Releases,
1422 SmallVector<Instruction *, 4> &NewRetains,
1423 SmallVector<Instruction *, 4> &NewReleases,
1424 SmallVector<Instruction *, 8> &DeadInsts,
1425 RRInfo &RetainsToMove,
1426 RRInfo &ReleasesToMove,
1429 bool &AnyPairsCompletelyEliminated);
1431 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1432 MapVector<Value *, RRInfo> &Retains,
1433 DenseMap<Value *, RRInfo> &Releases,
1436 void OptimizeWeakCalls(Function &F);
1438 bool OptimizeSequences(Function &F);
1440 void OptimizeReturns(Function &F);
1442 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1443 virtual bool doInitialization(Module &M);
1444 virtual bool runOnFunction(Function &F);
1445 virtual void releaseMemory();
1449 ObjCARCOpt() : FunctionPass(ID) {
1450 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1455 char ObjCARCOpt::ID = 0;
1456 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1457 "objc-arc", "ObjC ARC optimization", false, false)
1458 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1459 INITIALIZE_PASS_END(ObjCARCOpt,
1460 "objc-arc", "ObjC ARC optimization", false, false)
1462 Pass *llvm::createObjCARCOptPass() {
1463 return new ObjCARCOpt();
1466 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1467 AU.addRequired<ObjCARCAliasAnalysis>();
1468 AU.addRequired<AliasAnalysis>();
1469 // ARC optimization doesn't currently split critical edges.
1470 AU.setPreservesCFG();
1473 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1474 // Without the magic metadata tag, we have to assume this might be an
1475 // objc_retainBlock call inserted to convert a block pointer to an id,
1476 // in which case it really is needed.
1477 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1480 // If the pointer "escapes" (not including being used in a call),
1481 // the copy may be needed.
1482 if (DoesObjCBlockEscape(Inst))
1485 // Otherwise, it's not needed.
1489 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1490 if (!RetainRVCallee) {
1491 LLVMContext &C = M->getContext();
1492 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1493 Type *Params[] = { I8X };
1494 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1495 AttributeSet Attribute =
1496 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1497 Attribute::NoUnwind);
1499 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1502 return RetainRVCallee;
1505 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1506 if (!AutoreleaseRVCallee) {
1507 LLVMContext &C = M->getContext();
1508 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1509 Type *Params[] = { I8X };
1510 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1511 AttributeSet Attribute =
1512 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1513 Attribute::NoUnwind);
1514 AutoreleaseRVCallee =
1515 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1518 return AutoreleaseRVCallee;
1521 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1522 if (!ReleaseCallee) {
1523 LLVMContext &C = M->getContext();
1524 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1525 AttributeSet Attribute =
1526 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1527 Attribute::NoUnwind);
1529 M->getOrInsertFunction(
1531 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1534 return ReleaseCallee;
1537 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1538 if (!RetainCallee) {
1539 LLVMContext &C = M->getContext();
1540 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1541 AttributeSet Attribute =
1542 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1543 Attribute::NoUnwind);
1545 M->getOrInsertFunction(
1547 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1550 return RetainCallee;
1553 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1554 if (!RetainBlockCallee) {
1555 LLVMContext &C = M->getContext();
1556 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1557 // objc_retainBlock is not nounwind because it calls user copy constructors
1558 // which could theoretically throw.
1560 M->getOrInsertFunction(
1562 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1565 return RetainBlockCallee;
1568 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1569 if (!AutoreleaseCallee) {
1570 LLVMContext &C = M->getContext();
1571 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1572 AttributeSet Attribute =
1573 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
1574 Attribute::NoUnwind);
1576 M->getOrInsertFunction(
1578 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1581 return AutoreleaseCallee;
1584 /// Test whether the given value is possible a reference-counted pointer,
1585 /// including tests which utilize AliasAnalysis.
1586 static bool IsPotentialRetainableObjPtr(const Value *Op, AliasAnalysis &AA) {
1587 // First make the rudimentary check.
1588 if (!IsPotentialRetainableObjPtr(Op))
1591 // Objects in constant memory are not reference-counted.
1592 if (AA.pointsToConstantMemory(Op))
1595 // Pointers in constant memory are not pointing to reference-counted objects.
1596 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1597 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1600 // Otherwise assume the worst.
1604 /// Test whether the given instruction can result in a reference count
1605 /// modification (positive or negative) for the pointer's object.
1607 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1608 ProvenanceAnalysis &PA, InstructionClass Class) {
1610 case IC_Autorelease:
1611 case IC_AutoreleaseRV:
1613 // These operations never directly modify a reference count.
1618 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1619 assert(CS && "Only calls can alter reference counts!");
1621 // See if AliasAnalysis can help us with the call.
1622 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1623 if (AliasAnalysis::onlyReadsMemory(MRB))
1625 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1626 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1628 const Value *Op = *I;
1629 if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op))
1635 // Assume the worst.
1639 /// Test whether the given instruction can "use" the given pointer's object in a
1640 /// way that requires the reference count to be positive.
1642 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1643 InstructionClass Class) {
1644 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1645 if (Class == IC_Call)
1648 // Consider various instructions which may have pointer arguments which are
1650 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1651 // Comparing a pointer with null, or any other constant, isn't really a use,
1652 // because we don't care what the pointer points to, or about the values
1653 // of any other dynamic reference-counted pointers.
1654 if (!IsPotentialRetainableObjPtr(ICI->getOperand(1), *PA.getAA()))
1656 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1657 // For calls, just check the arguments (and not the callee operand).
1658 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1659 OE = CS.arg_end(); OI != OE; ++OI) {
1660 const Value *Op = *OI;
1661 if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op))
1665 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1666 // Special-case stores, because we don't care about the stored value, just
1667 // the store address.
1668 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1669 // If we can't tell what the underlying object was, assume there is a
1671 return IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Op, Ptr);
1674 // Check each operand for a match.
1675 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1677 const Value *Op = *OI;
1678 if (IsPotentialRetainableObjPtr(Op, *PA.getAA()) && PA.related(Ptr, Op))
1684 /// Test whether the given instruction can autorelease any pointer or cause an
1685 /// autoreleasepool pop.
1687 CanInterruptRV(InstructionClass Class) {
1689 case IC_AutoreleasepoolPop:
1692 case IC_Autorelease:
1693 case IC_AutoreleaseRV:
1694 case IC_FusedRetainAutorelease:
1695 case IC_FusedRetainAutoreleaseRV:
1703 /// \enum DependenceKind
1704 /// \brief Defines different dependence kinds among various ARC constructs.
1706 /// There are several kinds of dependence-like concepts in use here.
1708 enum DependenceKind {
1709 NeedsPositiveRetainCount,
1710 AutoreleasePoolBoundary,
1711 CanChangeRetainCount,
1712 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1713 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1714 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1718 /// Test if there can be dependencies on Inst through Arg. This function only
1719 /// tests dependencies relevant for removing pairs of calls.
1721 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1722 ProvenanceAnalysis &PA) {
1723 // If we've reached the definition of Arg, stop.
1728 case NeedsPositiveRetainCount: {
1729 InstructionClass Class = GetInstructionClass(Inst);
1731 case IC_AutoreleasepoolPop:
1732 case IC_AutoreleasepoolPush:
1736 return CanUse(Inst, Arg, PA, Class);
1740 case AutoreleasePoolBoundary: {
1741 InstructionClass Class = GetInstructionClass(Inst);
1743 case IC_AutoreleasepoolPop:
1744 case IC_AutoreleasepoolPush:
1745 // These mark the end and begin of an autorelease pool scope.
1748 // Nothing else does this.
1753 case CanChangeRetainCount: {
1754 InstructionClass Class = GetInstructionClass(Inst);
1756 case IC_AutoreleasepoolPop:
1757 // Conservatively assume this can decrement any count.
1759 case IC_AutoreleasepoolPush:
1763 return CanAlterRefCount(Inst, Arg, PA, Class);
1767 case RetainAutoreleaseDep:
1768 switch (GetBasicInstructionClass(Inst)) {
1769 case IC_AutoreleasepoolPop:
1770 case IC_AutoreleasepoolPush:
1771 // Don't merge an objc_autorelease with an objc_retain inside a different
1772 // autoreleasepool scope.
1776 // Check for a retain of the same pointer for merging.
1777 return GetObjCArg(Inst) == Arg;
1779 // Nothing else matters for objc_retainAutorelease formation.
1783 case RetainAutoreleaseRVDep: {
1784 InstructionClass Class = GetBasicInstructionClass(Inst);
1788 // Check for a retain of the same pointer for merging.
1789 return GetObjCArg(Inst) == Arg;
1791 // Anything that can autorelease interrupts
1792 // retainAutoreleaseReturnValue formation.
1793 return CanInterruptRV(Class);
1798 return CanInterruptRV(GetBasicInstructionClass(Inst));
1801 llvm_unreachable("Invalid dependence flavor");
1804 /// Walk up the CFG from StartPos (which is in StartBB) and find local and
1805 /// non-local dependencies on Arg.
1807 /// TODO: Cache results?
1809 FindDependencies(DependenceKind Flavor,
1811 BasicBlock *StartBB, Instruction *StartInst,
1812 SmallPtrSet<Instruction *, 4> &DependingInstructions,
1813 SmallPtrSet<const BasicBlock *, 4> &Visited,
1814 ProvenanceAnalysis &PA) {
1815 BasicBlock::iterator StartPos = StartInst;
1817 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
1818 Worklist.push_back(std::make_pair(StartBB, StartPos));
1820 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
1821 Worklist.pop_back_val();
1822 BasicBlock *LocalStartBB = Pair.first;
1823 BasicBlock::iterator LocalStartPos = Pair.second;
1824 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
1826 if (LocalStartPos == StartBBBegin) {
1827 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
1829 // If we've reached the function entry, produce a null dependence.
1830 DependingInstructions.insert(0);
1832 // Add the predecessors to the worklist.
1834 BasicBlock *PredBB = *PI;
1835 if (Visited.insert(PredBB))
1836 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
1837 } while (++PI != PE);
1841 Instruction *Inst = --LocalStartPos;
1842 if (Depends(Flavor, Inst, Arg, PA)) {
1843 DependingInstructions.insert(Inst);
1847 } while (!Worklist.empty());
1849 // Determine whether the original StartBB post-dominates all of the blocks we
1850 // visited. If not, insert a sentinal indicating that most optimizations are
1852 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
1853 E = Visited.end(); I != E; ++I) {
1854 const BasicBlock *BB = *I;
1857 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1858 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
1859 const BasicBlock *Succ = *SI;
1860 if (Succ != StartBB && !Visited.count(Succ)) {
1861 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
1868 static bool isNullOrUndef(const Value *V) {
1869 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
1872 static bool isNoopInstruction(const Instruction *I) {
1873 return isa<BitCastInst>(I) ||
1874 (isa<GetElementPtrInst>(I) &&
1875 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
1878 /// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
1881 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
1882 ImmutableCallSite CS(GetObjCArg(Retain));
1883 const Instruction *Call = CS.getInstruction();
1885 if (Call->getParent() != Retain->getParent()) return;
1887 // Check that the call is next to the retain.
1888 BasicBlock::const_iterator I = Call;
1890 while (isNoopInstruction(I)) ++I;
1894 // Turn it to an objc_retainAutoreleasedReturnValue..
1898 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
1899 "objc_retain => objc_retainAutoreleasedReturnValue"
1900 " since the operand is a return value.\n"
1902 << *Retain << "\n");
1904 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
1906 DEBUG(dbgs() << " New: "
1907 << *Retain << "\n");
1910 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
1911 /// not a return value. Or, if it can be paired with an
1912 /// objc_autoreleaseReturnValue, delete the pair and return true.
1914 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1915 // Check for the argument being from an immediately preceding call or invoke.
1916 const Value *Arg = GetObjCArg(RetainRV);
1917 ImmutableCallSite CS(Arg);
1918 if (const Instruction *Call = CS.getInstruction()) {
1919 if (Call->getParent() == RetainRV->getParent()) {
1920 BasicBlock::const_iterator I = Call;
1922 while (isNoopInstruction(I)) ++I;
1923 if (&*I == RetainRV)
1925 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
1926 BasicBlock *RetainRVParent = RetainRV->getParent();
1927 if (II->getNormalDest() == RetainRVParent) {
1928 BasicBlock::const_iterator I = RetainRVParent->begin();
1929 while (isNoopInstruction(I)) ++I;
1930 if (&*I == RetainRV)
1936 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1937 // pointer. In this case, we can delete the pair.
1938 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1940 do --I; while (I != Begin && isNoopInstruction(I));
1941 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1942 GetObjCArg(I) == Arg) {
1946 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
1947 << " Erasing " << *RetainRV
1950 EraseInstruction(I);
1951 EraseInstruction(RetainRV);
1956 // Turn it to a plain objc_retain.
1960 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
1961 "objc_retainAutoreleasedReturnValue => "
1962 "objc_retain since the operand is not a return value.\n"
1964 << *RetainRV << "\n");
1966 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
1968 DEBUG(dbgs() << " New: "
1969 << *RetainRV << "\n");
1974 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
1975 /// used as a return value.
1977 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1978 InstructionClass &Class) {
1979 // Check for a return of the pointer value.
1980 const Value *Ptr = GetObjCArg(AutoreleaseRV);
1981 SmallVector<const Value *, 2> Users;
1982 Users.push_back(Ptr);
1984 Ptr = Users.pop_back_val();
1985 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1987 const User *I = *UI;
1988 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1990 if (isa<BitCastInst>(I))
1993 } while (!Users.empty());
1998 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
1999 "objc_autoreleaseReturnValue => "
2000 "objc_autorelease since its operand is not used as a return "
2003 << *AutoreleaseRV << "\n");
2005 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
2007 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2008 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
2009 Class = IC_Autorelease;
2011 DEBUG(dbgs() << " New: "
2012 << *AutoreleaseRV << "\n");
2016 /// Visit each call, one at a time, and make simplifications without doing any
2017 /// additional analysis.
2018 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2019 // Reset all the flags in preparation for recomputing them.
2020 UsedInThisFunction = 0;
2022 // Visit all objc_* calls in F.
2023 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2024 Instruction *Inst = &*I++;
2026 InstructionClass Class = GetBasicInstructionClass(Inst);
2028 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: Class: "
2029 << Class << "; " << *Inst << "\n");
2034 // Delete no-op casts. These function calls have special semantics, but
2035 // the semantics are entirely implemented via lowering in the front-end,
2036 // so by the time they reach the optimizer, they are just no-op calls
2037 // which return their argument.
2039 // There are gray areas here, as the ability to cast reference-counted
2040 // pointers to raw void* and back allows code to break ARC assumptions,
2041 // however these are currently considered to be unimportant.
2045 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
2046 " " << *Inst << "\n");
2047 EraseInstruction(Inst);
2050 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2053 case IC_LoadWeakRetained:
2055 case IC_DestroyWeak: {
2056 CallInst *CI = cast<CallInst>(Inst);
2057 if (isNullOrUndef(CI->getArgOperand(0))) {
2059 Type *Ty = CI->getArgOperand(0)->getType();
2060 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2061 Constant::getNullValue(Ty),
2063 llvm::Value *NewValue = UndefValue::get(CI->getType());
2064 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2065 "pointer-to-weak-pointer is undefined behavior.\n"
2069 CI->replaceAllUsesWith(NewValue);
2070 CI->eraseFromParent();
2077 CallInst *CI = cast<CallInst>(Inst);
2078 if (isNullOrUndef(CI->getArgOperand(0)) ||
2079 isNullOrUndef(CI->getArgOperand(1))) {
2081 Type *Ty = CI->getArgOperand(0)->getType();
2082 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2083 Constant::getNullValue(Ty),
2086 llvm::Value *NewValue = UndefValue::get(CI->getType());
2087 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2088 "pointer-to-weak-pointer is undefined behavior.\n"
2093 CI->replaceAllUsesWith(NewValue);
2094 CI->eraseFromParent();
2100 OptimizeRetainCall(F, Inst);
2103 if (OptimizeRetainRVCall(F, Inst))
2106 case IC_AutoreleaseRV:
2107 OptimizeAutoreleaseRVCall(F, Inst, Class);
2111 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2112 if (IsAutorelease(Class) && Inst->use_empty()) {
2113 CallInst *Call = cast<CallInst>(Inst);
2114 const Value *Arg = Call->getArgOperand(0);
2115 Arg = FindSingleUseIdentifiedObject(Arg);
2120 // Create the declaration lazily.
2121 LLVMContext &C = Inst->getContext();
2123 CallInst::Create(getReleaseCallee(F.getParent()),
2124 Call->getArgOperand(0), "", Call);
2125 NewCall->setMetadata(ImpreciseReleaseMDKind,
2126 MDNode::get(C, ArrayRef<Value *>()));
2128 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
2129 "objc_autorelease(x) with objc_release(x) since x is "
2130 "otherwise unused.\n"
2131 " Old: " << *Call <<
2135 EraseInstruction(Call);
2141 // For functions which can never be passed stack arguments, add
2143 if (IsAlwaysTail(Class)) {
2145 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
2146 " to function since it can never be passed stack args: " << *Inst <<
2148 cast<CallInst>(Inst)->setTailCall();
2151 // Ensure that functions that can never have a "tail" keyword due to the
2152 // semantics of ARC truly do not do so.
2153 if (IsNeverTail(Class)) {
2155 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail "
2156 "keyword from function: " << *Inst <<
2158 cast<CallInst>(Inst)->setTailCall(false);
2161 // Set nounwind as needed.
2162 if (IsNoThrow(Class)) {
2164 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
2165 " class. Setting nounwind on: " << *Inst << "\n");
2166 cast<CallInst>(Inst)->setDoesNotThrow();
2169 if (!IsNoopOnNull(Class)) {
2170 UsedInThisFunction |= 1 << Class;
2174 const Value *Arg = GetObjCArg(Inst);
2176 // ARC calls with null are no-ops. Delete them.
2177 if (isNullOrUndef(Arg)) {
2180 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
2181 " null are no-ops. Erasing: " << *Inst << "\n");
2182 EraseInstruction(Inst);
2186 // Keep track of which of retain, release, autorelease, and retain_block
2187 // are actually present in this function.
2188 UsedInThisFunction |= 1 << Class;
2190 // If Arg is a PHI, and one or more incoming values to the
2191 // PHI are null, and the call is control-equivalent to the PHI, and there
2192 // are no relevant side effects between the PHI and the call, the call
2193 // could be pushed up to just those paths with non-null incoming values.
2194 // For now, don't bother splitting critical edges for this.
2195 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2196 Worklist.push_back(std::make_pair(Inst, Arg));
2198 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2202 const PHINode *PN = dyn_cast<PHINode>(Arg);
2205 // Determine if the PHI has any null operands, or any incoming
2207 bool HasNull = false;
2208 bool HasCriticalEdges = false;
2209 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2211 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2212 if (isNullOrUndef(Incoming))
2214 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2215 .getNumSuccessors() != 1) {
2216 HasCriticalEdges = true;
2220 // If we have null operands and no critical edges, optimize.
2221 if (!HasCriticalEdges && HasNull) {
2222 SmallPtrSet<Instruction *, 4> DependingInstructions;
2223 SmallPtrSet<const BasicBlock *, 4> Visited;
2225 // Check that there is nothing that cares about the reference
2226 // count between the call and the phi.
2229 case IC_RetainBlock:
2230 // These can always be moved up.
2233 // These can't be moved across things that care about the retain
2235 FindDependencies(NeedsPositiveRetainCount, Arg,
2236 Inst->getParent(), Inst,
2237 DependingInstructions, Visited, PA);
2239 case IC_Autorelease:
2240 // These can't be moved across autorelease pool scope boundaries.
2241 FindDependencies(AutoreleasePoolBoundary, Arg,
2242 Inst->getParent(), Inst,
2243 DependingInstructions, Visited, PA);
2246 case IC_AutoreleaseRV:
2247 // Don't move these; the RV optimization depends on the autoreleaseRV
2248 // being tail called, and the retainRV being immediately after a call
2249 // (which might still happen if we get lucky with codegen layout, but
2250 // it's not worth taking the chance).
2253 llvm_unreachable("Invalid dependence flavor");
2256 if (DependingInstructions.size() == 1 &&
2257 *DependingInstructions.begin() == PN) {
2260 // Clone the call into each predecessor that has a non-null value.
2261 CallInst *CInst = cast<CallInst>(Inst);
2262 Type *ParamTy = CInst->getArgOperand(0)->getType();
2263 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2265 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2266 if (!isNullOrUndef(Incoming)) {
2267 CallInst *Clone = cast<CallInst>(CInst->clone());
2268 Value *Op = PN->getIncomingValue(i);
2269 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2270 if (Op->getType() != ParamTy)
2271 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2272 Clone->setArgOperand(0, Op);
2273 Clone->insertBefore(InsertPos);
2275 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
2278 "clone at " << *InsertPos << "\n");
2279 Worklist.push_back(std::make_pair(Clone, Incoming));
2282 // Erase the original call.
2283 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
2284 EraseInstruction(CInst);
2288 } while (!Worklist.empty());
2290 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
2293 /// Check for critical edges, loop boundaries, irreducible control flow, or
2294 /// other CFG structures where moving code across the edge would result in it
2295 /// being executed more.
2297 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2298 DenseMap<const BasicBlock *, BBState> &BBStates,
2299 BBState &MyStates) const {
2300 // If any top-down local-use or possible-dec has a succ which is earlier in
2301 // the sequence, forget it.
2302 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
2303 E = MyStates.top_down_ptr_end(); I != E; ++I)
2304 switch (I->second.GetSeq()) {
2307 const Value *Arg = I->first;
2308 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2309 bool SomeSuccHasSame = false;
2310 bool AllSuccsHaveSame = true;
2311 PtrState &S = I->second;
2312 succ_const_iterator SI(TI), SE(TI, false);
2314 for (; SI != SE; ++SI) {
2315 Sequence SuccSSeq = S_None;
2316 bool SuccSRRIKnownSafe = false;
2317 // If VisitBottomUp has pointer information for this successor, take
2318 // what we know about it.
2319 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2321 assert(BBI != BBStates.end());
2322 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2323 SuccSSeq = SuccS.GetSeq();
2324 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2327 case S_CanRelease: {
2328 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2329 S.ClearSequenceProgress();
2335 SomeSuccHasSame = true;
2339 case S_MovableRelease:
2340 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2341 AllSuccsHaveSame = false;
2344 llvm_unreachable("bottom-up pointer in retain state!");
2347 // If the state at the other end of any of the successor edges
2348 // matches the current state, require all edges to match. This
2349 // guards against loops in the middle of a sequence.
2350 if (SomeSuccHasSame && !AllSuccsHaveSame)
2351 S.ClearSequenceProgress();
2354 case S_CanRelease: {
2355 const Value *Arg = I->first;
2356 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2357 bool SomeSuccHasSame = false;
2358 bool AllSuccsHaveSame = true;
2359 PtrState &S = I->second;
2360 succ_const_iterator SI(TI), SE(TI, false);
2362 for (; SI != SE; ++SI) {
2363 Sequence SuccSSeq = S_None;
2364 bool SuccSRRIKnownSafe = false;
2365 // If VisitBottomUp has pointer information for this successor, take
2366 // what we know about it.
2367 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2369 assert(BBI != BBStates.end());
2370 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2371 SuccSSeq = SuccS.GetSeq();
2372 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2375 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2376 S.ClearSequenceProgress();
2382 SomeSuccHasSame = true;
2386 case S_MovableRelease:
2388 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2389 AllSuccsHaveSame = false;
2392 llvm_unreachable("bottom-up pointer in retain state!");
2395 // If the state at the other end of any of the successor edges
2396 // matches the current state, require all edges to match. This
2397 // guards against loops in the middle of a sequence.
2398 if (SomeSuccHasSame && !AllSuccsHaveSame)
2399 S.ClearSequenceProgress();
2406 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
2408 MapVector<Value *, RRInfo> &Retains,
2409 BBState &MyStates) {
2410 bool NestingDetected = false;
2411 InstructionClass Class = GetInstructionClass(Inst);
2412 const Value *Arg = 0;
2416 Arg = GetObjCArg(Inst);
2418 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2420 // If we see two releases in a row on the same pointer. If so, make
2421 // a note, and we'll cicle back to revisit it after we've
2422 // hopefully eliminated the second release, which may allow us to
2423 // eliminate the first release too.
2424 // Theoretically we could implement removal of nested retain+release
2425 // pairs by making PtrState hold a stack of states, but this is
2426 // simple and avoids adding overhead for the non-nested case.
2427 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
2428 DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested "
2429 "releases (i.e. a release pair)\n");
2430 NestingDetected = true;
2433 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2434 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
2435 S.RRI.ReleaseMetadata = ReleaseMetadata;
2436 S.RRI.KnownSafe = S.IsKnownIncremented();
2437 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2438 S.RRI.Calls.insert(Inst);
2440 S.SetKnownPositiveRefCount();
2443 case IC_RetainBlock:
2444 // An objc_retainBlock call with just a use may need to be kept,
2445 // because it may be copying a block from the stack to the heap.
2446 if (!IsRetainBlockOptimizable(Inst))
2451 Arg = GetObjCArg(Inst);
2453 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2454 S.SetKnownPositiveRefCount();
2456 switch (S.GetSeq()) {
2459 case S_MovableRelease:
2461 S.RRI.ReverseInsertPts.clear();
2464 // Don't do retain+release tracking for IC_RetainRV, because it's
2465 // better to let it remain as the first instruction after a call.
2466 if (Class != IC_RetainRV) {
2467 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2468 Retains[Inst] = S.RRI;
2470 S.ClearSequenceProgress();
2475 llvm_unreachable("bottom-up pointer in retain state!");
2477 return NestingDetected;
2479 case IC_AutoreleasepoolPop:
2480 // Conservatively, clear MyStates for all known pointers.
2481 MyStates.clearBottomUpPointers();
2482 return NestingDetected;
2483 case IC_AutoreleasepoolPush:
2485 // These are irrelevant.
2486 return NestingDetected;
2491 // Consider any other possible effects of this instruction on each
2492 // pointer being tracked.
2493 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2494 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2495 const Value *Ptr = MI->first;
2497 continue; // Handled above.
2498 PtrState &S = MI->second;
2499 Sequence Seq = S.GetSeq();
2501 // Check for possible releases.
2502 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2506 S.SetSeq(S_CanRelease);
2510 case S_MovableRelease:
2515 llvm_unreachable("bottom-up pointer in retain state!");
2519 // Check for possible direct uses.
2522 case S_MovableRelease:
2523 if (CanUse(Inst, Ptr, PA, Class)) {
2524 assert(S.RRI.ReverseInsertPts.empty());
2525 // If this is an invoke instruction, we're scanning it as part of
2526 // one of its successor blocks, since we can't insert code after it
2527 // in its own block, and we don't want to split critical edges.
2528 if (isa<InvokeInst>(Inst))
2529 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2531 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2533 } else if (Seq == S_Release &&
2534 (Class == IC_User || Class == IC_CallOrUser)) {
2535 // Non-movable releases depend on any possible objc pointer use.
2537 assert(S.RRI.ReverseInsertPts.empty());
2538 // As above; handle invoke specially.
2539 if (isa<InvokeInst>(Inst))
2540 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2542 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2546 if (CanUse(Inst, Ptr, PA, Class))
2554 llvm_unreachable("bottom-up pointer in retain state!");
2558 return NestingDetected;
2562 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2563 DenseMap<const BasicBlock *, BBState> &BBStates,
2564 MapVector<Value *, RRInfo> &Retains) {
2565 bool NestingDetected = false;
2566 BBState &MyStates = BBStates[BB];
2568 // Merge the states from each successor to compute the initial state
2569 // for the current block.
2570 BBState::edge_iterator SI(MyStates.succ_begin()),
2571 SE(MyStates.succ_end());
2573 const BasicBlock *Succ = *SI;
2574 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2575 assert(I != BBStates.end());
2576 MyStates.InitFromSucc(I->second);
2578 for (; SI != SE; ++SI) {
2580 I = BBStates.find(Succ);
2581 assert(I != BBStates.end());
2582 MyStates.MergeSucc(I->second);
2586 // Visit all the instructions, bottom-up.
2587 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2588 Instruction *Inst = llvm::prior(I);
2590 // Invoke instructions are visited as part of their successors (below).
2591 if (isa<InvokeInst>(Inst))
2594 DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n");
2596 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2599 // If there's a predecessor with an invoke, visit the invoke as if it were
2600 // part of this block, since we can't insert code after an invoke in its own
2601 // block, and we don't want to split critical edges.
2602 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2603 PE(MyStates.pred_end()); PI != PE; ++PI) {
2604 BasicBlock *Pred = *PI;
2605 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2606 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
2609 return NestingDetected;
2613 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2614 DenseMap<Value *, RRInfo> &Releases,
2615 BBState &MyStates) {
2616 bool NestingDetected = false;
2617 InstructionClass Class = GetInstructionClass(Inst);
2618 const Value *Arg = 0;
2621 case IC_RetainBlock:
2622 // An objc_retainBlock call with just a use may need to be kept,
2623 // because it may be copying a block from the stack to the heap.
2624 if (!IsRetainBlockOptimizable(Inst))
2629 Arg = GetObjCArg(Inst);
2631 PtrState &S = MyStates.getPtrTopDownState(Arg);
2633 // Don't do retain+release tracking for IC_RetainRV, because it's
2634 // better to let it remain as the first instruction after a call.
2635 if (Class != IC_RetainRV) {
2636 // If we see two retains in a row on the same pointer. If so, make
2637 // a note, and we'll cicle back to revisit it after we've
2638 // hopefully eliminated the second retain, which may allow us to
2639 // eliminate the first retain too.
2640 // Theoretically we could implement removal of nested retain+release
2641 // pairs by making PtrState hold a stack of states, but this is
2642 // simple and avoids adding overhead for the non-nested case.
2643 if (S.GetSeq() == S_Retain)
2644 NestingDetected = true;
2646 S.ResetSequenceProgress(S_Retain);
2647 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2648 S.RRI.KnownSafe = S.IsKnownIncremented();
2649 S.RRI.Calls.insert(Inst);
2652 S.SetKnownPositiveRefCount();
2654 // A retain can be a potential use; procede to the generic checking
2659 Arg = GetObjCArg(Inst);
2661 PtrState &S = MyStates.getPtrTopDownState(Arg);
2664 switch (S.GetSeq()) {
2667 S.RRI.ReverseInsertPts.clear();
2670 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2671 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2672 Releases[Inst] = S.RRI;
2673 S.ClearSequenceProgress();
2679 case S_MovableRelease:
2680 llvm_unreachable("top-down pointer in release state!");
2684 case IC_AutoreleasepoolPop:
2685 // Conservatively, clear MyStates for all known pointers.
2686 MyStates.clearTopDownPointers();
2687 return NestingDetected;
2688 case IC_AutoreleasepoolPush:
2690 // These are irrelevant.
2691 return NestingDetected;
2696 // Consider any other possible effects of this instruction on each
2697 // pointer being tracked.
2698 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2699 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2700 const Value *Ptr = MI->first;
2702 continue; // Handled above.
2703 PtrState &S = MI->second;
2704 Sequence Seq = S.GetSeq();
2706 // Check for possible releases.
2707 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2711 S.SetSeq(S_CanRelease);
2712 assert(S.RRI.ReverseInsertPts.empty());
2713 S.RRI.ReverseInsertPts.insert(Inst);
2715 // One call can't cause a transition from S_Retain to S_CanRelease
2716 // and S_CanRelease to S_Use. If we've made the first transition,
2725 case S_MovableRelease:
2726 llvm_unreachable("top-down pointer in release state!");
2730 // Check for possible direct uses.
2733 if (CanUse(Inst, Ptr, PA, Class))
2742 case S_MovableRelease:
2743 llvm_unreachable("top-down pointer in release state!");
2747 return NestingDetected;
2751 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2752 DenseMap<const BasicBlock *, BBState> &BBStates,
2753 DenseMap<Value *, RRInfo> &Releases) {
2754 bool NestingDetected = false;
2755 BBState &MyStates = BBStates[BB];
2757 // Merge the states from each predecessor to compute the initial state
2758 // for the current block.
2759 BBState::edge_iterator PI(MyStates.pred_begin()),
2760 PE(MyStates.pred_end());
2762 const BasicBlock *Pred = *PI;
2763 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2764 assert(I != BBStates.end());
2765 MyStates.InitFromPred(I->second);
2767 for (; PI != PE; ++PI) {
2769 I = BBStates.find(Pred);
2770 assert(I != BBStates.end());
2771 MyStates.MergePred(I->second);
2775 // Visit all the instructions, top-down.
2776 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2777 Instruction *Inst = I;
2779 DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n");
2781 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
2784 CheckForCFGHazards(BB, BBStates, MyStates);
2785 return NestingDetected;
2789 ComputePostOrders(Function &F,
2790 SmallVectorImpl<BasicBlock *> &PostOrder,
2791 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2792 unsigned NoObjCARCExceptionsMDKind,
2793 DenseMap<const BasicBlock *, BBState> &BBStates) {
2794 /// The visited set, for doing DFS walks.
2795 SmallPtrSet<BasicBlock *, 16> Visited;
2797 // Do DFS, computing the PostOrder.
2798 SmallPtrSet<BasicBlock *, 16> OnStack;
2799 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2801 // Functions always have exactly one entry block, and we don't have
2802 // any other block that we treat like an entry block.
2803 BasicBlock *EntryBB = &F.getEntryBlock();
2804 BBState &MyStates = BBStates[EntryBB];
2805 MyStates.SetAsEntry();
2806 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2807 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
2808 Visited.insert(EntryBB);
2809 OnStack.insert(EntryBB);
2812 BasicBlock *CurrBB = SuccStack.back().first;
2813 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2814 succ_iterator SE(TI, false);
2816 while (SuccStack.back().second != SE) {
2817 BasicBlock *SuccBB = *SuccStack.back().second++;
2818 if (Visited.insert(SuccBB)) {
2819 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
2820 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
2821 BBStates[CurrBB].addSucc(SuccBB);
2822 BBState &SuccStates = BBStates[SuccBB];
2823 SuccStates.addPred(CurrBB);
2824 OnStack.insert(SuccBB);
2828 if (!OnStack.count(SuccBB)) {
2829 BBStates[CurrBB].addSucc(SuccBB);
2830 BBStates[SuccBB].addPred(CurrBB);
2833 OnStack.erase(CurrBB);
2834 PostOrder.push_back(CurrBB);
2835 SuccStack.pop_back();
2836 } while (!SuccStack.empty());
2840 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2841 // Functions may have many exits, and there also blocks which we treat
2842 // as exits due to ignored edges.
2843 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
2844 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2845 BasicBlock *ExitBB = I;
2846 BBState &MyStates = BBStates[ExitBB];
2847 if (!MyStates.isExit())
2850 MyStates.SetAsExit();
2852 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
2853 Visited.insert(ExitBB);
2854 while (!PredStack.empty()) {
2855 reverse_dfs_next_succ:
2856 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
2857 while (PredStack.back().second != PE) {
2858 BasicBlock *BB = *PredStack.back().second++;
2859 if (Visited.insert(BB)) {
2860 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
2861 goto reverse_dfs_next_succ;
2864 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2869 // Visit the function both top-down and bottom-up.
2871 ObjCARCOpt::Visit(Function &F,
2872 DenseMap<const BasicBlock *, BBState> &BBStates,
2873 MapVector<Value *, RRInfo> &Retains,
2874 DenseMap<Value *, RRInfo> &Releases) {
2876 // Use reverse-postorder traversals, because we magically know that loops
2877 // will be well behaved, i.e. they won't repeatedly call retain on a single
2878 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2879 // class here because we want the reverse-CFG postorder to consider each
2880 // function exit point, and we want to ignore selected cycle edges.
2881 SmallVector<BasicBlock *, 16> PostOrder;
2882 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2883 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
2884 NoObjCARCExceptionsMDKind,
2887 // Use reverse-postorder on the reverse CFG for bottom-up.
2888 bool BottomUpNestingDetected = false;
2889 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2890 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2892 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
2894 // Use reverse-postorder for top-down.
2895 bool TopDownNestingDetected = false;
2896 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2897 PostOrder.rbegin(), E = PostOrder.rend();
2899 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
2901 return TopDownNestingDetected && BottomUpNestingDetected;
2904 /// Move the calls in RetainsToMove and ReleasesToMove.
2905 void ObjCARCOpt::MoveCalls(Value *Arg,
2906 RRInfo &RetainsToMove,
2907 RRInfo &ReleasesToMove,
2908 MapVector<Value *, RRInfo> &Retains,
2909 DenseMap<Value *, RRInfo> &Releases,
2910 SmallVectorImpl<Instruction *> &DeadInsts,
2912 Type *ArgTy = Arg->getType();
2913 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2915 // Insert the new retain and release calls.
2916 for (SmallPtrSet<Instruction *, 2>::const_iterator
2917 PI = ReleasesToMove.ReverseInsertPts.begin(),
2918 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2919 Instruction *InsertPt = *PI;
2920 Value *MyArg = ArgTy == ParamTy ? Arg :
2921 new BitCastInst(Arg, ParamTy, "", InsertPt);
2923 CallInst::Create(RetainsToMove.IsRetainBlock ?
2924 getRetainBlockCallee(M) : getRetainCallee(M),
2925 MyArg, "", InsertPt);
2926 Call->setDoesNotThrow();
2927 if (RetainsToMove.IsRetainBlock)
2928 Call->setMetadata(CopyOnEscapeMDKind,
2929 MDNode::get(M->getContext(), ArrayRef<Value *>()));
2931 Call->setTailCall();
2933 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
2935 " At insertion point: " << *InsertPt
2938 for (SmallPtrSet<Instruction *, 2>::const_iterator
2939 PI = RetainsToMove.ReverseInsertPts.begin(),
2940 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2941 Instruction *InsertPt = *PI;
2942 Value *MyArg = ArgTy == ParamTy ? Arg :
2943 new BitCastInst(Arg, ParamTy, "", InsertPt);
2944 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2946 // Attach a clang.imprecise_release metadata tag, if appropriate.
2947 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2948 Call->setMetadata(ImpreciseReleaseMDKind, M);
2949 Call->setDoesNotThrow();
2950 if (ReleasesToMove.IsTailCallRelease)
2951 Call->setTailCall();
2953 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
2955 " At insertion point: " << *InsertPt
2959 // Delete the original retain and release calls.
2960 for (SmallPtrSet<Instruction *, 2>::const_iterator
2961 AI = RetainsToMove.Calls.begin(),
2962 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2963 Instruction *OrigRetain = *AI;
2964 Retains.blot(OrigRetain);
2965 DeadInsts.push_back(OrigRetain);
2966 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
2969 for (SmallPtrSet<Instruction *, 2>::const_iterator
2970 AI = ReleasesToMove.Calls.begin(),
2971 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2972 Instruction *OrigRelease = *AI;
2973 Releases.erase(OrigRelease);
2974 DeadInsts.push_back(OrigRelease);
2975 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
2981 ObjCARCOpt::ConnectTDBUTraversals(DenseMap<const BasicBlock *, BBState>
2983 MapVector<Value *, RRInfo> &Retains,
2984 DenseMap<Value *, RRInfo> &Releases,
2986 SmallVector<Instruction *, 4> &NewRetains,
2987 SmallVector<Instruction *, 4> &NewReleases,
2988 SmallVector<Instruction *, 8> &DeadInsts,
2989 RRInfo &RetainsToMove,
2990 RRInfo &ReleasesToMove,
2993 bool &AnyPairsCompletelyEliminated) {
2994 // If a pair happens in a region where it is known that the reference count
2995 // is already incremented, we can similarly ignore possible decrements.
2996 bool KnownSafeTD = true, KnownSafeBU = true;
2998 // Connect the dots between the top-down-collected RetainsToMove and
2999 // bottom-up-collected ReleasesToMove to form sets of related calls.
3000 // This is an iterative process so that we connect multiple releases
3001 // to multiple retains if needed.
3002 unsigned OldDelta = 0;
3003 unsigned NewDelta = 0;
3004 unsigned OldCount = 0;
3005 unsigned NewCount = 0;
3006 bool FirstRelease = true;
3007 bool FirstRetain = true;
3009 for (SmallVectorImpl<Instruction *>::const_iterator
3010 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3011 Instruction *NewRetain = *NI;
3012 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3013 assert(It != Retains.end());
3014 const RRInfo &NewRetainRRI = It->second;
3015 KnownSafeTD &= NewRetainRRI.KnownSafe;
3016 for (SmallPtrSet<Instruction *, 2>::const_iterator
3017 LI = NewRetainRRI.Calls.begin(),
3018 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3019 Instruction *NewRetainRelease = *LI;
3020 DenseMap<Value *, RRInfo>::const_iterator Jt =
3021 Releases.find(NewRetainRelease);
3022 if (Jt == Releases.end())
3024 const RRInfo &NewRetainReleaseRRI = Jt->second;
3025 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3026 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3028 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3030 // Merge the ReleaseMetadata and IsTailCallRelease values.
3032 ReleasesToMove.ReleaseMetadata =
3033 NewRetainReleaseRRI.ReleaseMetadata;
3034 ReleasesToMove.IsTailCallRelease =
3035 NewRetainReleaseRRI.IsTailCallRelease;
3036 FirstRelease = false;
3038 if (ReleasesToMove.ReleaseMetadata !=
3039 NewRetainReleaseRRI.ReleaseMetadata)
3040 ReleasesToMove.ReleaseMetadata = 0;
3041 if (ReleasesToMove.IsTailCallRelease !=
3042 NewRetainReleaseRRI.IsTailCallRelease)
3043 ReleasesToMove.IsTailCallRelease = false;
3046 // Collect the optimal insertion points.
3048 for (SmallPtrSet<Instruction *, 2>::const_iterator
3049 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3050 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3052 Instruction *RIP = *RI;
3053 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3054 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3056 NewReleases.push_back(NewRetainRelease);
3061 if (NewReleases.empty()) break;
3063 // Back the other way.
3064 for (SmallVectorImpl<Instruction *>::const_iterator
3065 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3066 Instruction *NewRelease = *NI;
3067 DenseMap<Value *, RRInfo>::const_iterator It =
3068 Releases.find(NewRelease);
3069 assert(It != Releases.end());
3070 const RRInfo &NewReleaseRRI = It->second;
3071 KnownSafeBU &= NewReleaseRRI.KnownSafe;
3072 for (SmallPtrSet<Instruction *, 2>::const_iterator
3073 LI = NewReleaseRRI.Calls.begin(),
3074 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3075 Instruction *NewReleaseRetain = *LI;
3076 MapVector<Value *, RRInfo>::const_iterator Jt =
3077 Retains.find(NewReleaseRetain);
3078 if (Jt == Retains.end())
3080 const RRInfo &NewReleaseRetainRRI = Jt->second;
3081 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3082 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3083 unsigned PathCount =
3084 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3085 OldDelta += PathCount;
3086 OldCount += PathCount;
3088 // Merge the IsRetainBlock values.
3090 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3091 FirstRetain = false;
3092 } else if (ReleasesToMove.IsRetainBlock !=
3093 NewReleaseRetainRRI.IsRetainBlock)
3094 // It's not possible to merge the sequences if one uses
3095 // objc_retain and the other uses objc_retainBlock.
3098 // Collect the optimal insertion points.
3100 for (SmallPtrSet<Instruction *, 2>::const_iterator
3101 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3102 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3104 Instruction *RIP = *RI;
3105 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3106 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3107 NewDelta += PathCount;
3108 NewCount += PathCount;
3111 NewRetains.push_back(NewReleaseRetain);
3115 NewReleases.clear();
3116 if (NewRetains.empty()) break;
3119 // If the pointer is known incremented or nested, we can safely delete the
3120 // pair regardless of what's between them.
3121 if (KnownSafeTD || KnownSafeBU) {
3122 RetainsToMove.ReverseInsertPts.clear();
3123 ReleasesToMove.ReverseInsertPts.clear();
3126 // Determine whether the new insertion points we computed preserve the
3127 // balance of retain and release calls through the program.
3128 // TODO: If the fully aggressive solution isn't valid, try to find a
3129 // less aggressive solution which is.
3134 // Determine whether the original call points are balanced in the retain and
3135 // release calls through the program. If not, conservatively don't touch
3137 // TODO: It's theoretically possible to do code motion in this case, as
3138 // long as the existing imbalances are maintained.
3143 assert(OldCount != 0 && "Unreachable code?");
3144 NumRRs += OldCount - NewCount;
3145 // Set to true if we completely removed any RR pairs.
3146 AnyPairsCompletelyEliminated = NewCount == 0;
3148 // We can move calls!
3152 /// Identify pairings between the retains and releases, and delete and/or move
3155 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3157 MapVector<Value *, RRInfo> &Retains,
3158 DenseMap<Value *, RRInfo> &Releases,
3160 bool AnyPairsCompletelyEliminated = false;
3161 RRInfo RetainsToMove;
3162 RRInfo ReleasesToMove;
3163 SmallVector<Instruction *, 4> NewRetains;
3164 SmallVector<Instruction *, 4> NewReleases;
3165 SmallVector<Instruction *, 8> DeadInsts;
3167 // Visit each retain.
3168 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
3169 E = Retains.end(); I != E; ++I) {
3170 Value *V = I->first;
3171 if (!V) continue; // blotted
3173 Instruction *Retain = cast<Instruction>(V);
3175 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
3178 Value *Arg = GetObjCArg(Retain);
3180 // If the object being released is in static or stack storage, we know it's
3181 // not being managed by ObjC reference counting, so we can delete pairs
3182 // regardless of what possible decrements or uses lie between them.
3183 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
3185 // A constant pointer can't be pointing to an object on the heap. It may
3186 // be reference-counted, but it won't be deleted.
3187 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3188 if (const GlobalVariable *GV =
3189 dyn_cast<GlobalVariable>(
3190 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3191 if (GV->isConstant())
3194 // Connect the dots between the top-down-collected RetainsToMove and
3195 // bottom-up-collected ReleasesToMove to form sets of related calls.
3196 NewRetains.push_back(Retain);
3197 bool PerformMoveCalls =
3198 ConnectTDBUTraversals(BBStates, Retains, Releases, M, NewRetains,
3199 NewReleases, DeadInsts, RetainsToMove,
3200 ReleasesToMove, Arg, KnownSafe,
3201 AnyPairsCompletelyEliminated);
3203 if (PerformMoveCalls) {
3204 // Ok, everything checks out and we're all set. Let's move/delete some
3206 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3207 Retains, Releases, DeadInsts, M);
3210 // Clean up state for next retain.
3211 NewReleases.clear();
3213 RetainsToMove.clear();
3214 ReleasesToMove.clear();
3217 // Now that we're done moving everything, we can delete the newly dead
3218 // instructions, as we no longer need them as insert points.
3219 while (!DeadInsts.empty())
3220 EraseInstruction(DeadInsts.pop_back_val());
3222 return AnyPairsCompletelyEliminated;
3225 /// Weak pointer optimizations.
3226 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3227 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3228 // itself because it uses AliasAnalysis and we need to do provenance
3230 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3231 Instruction *Inst = &*I++;
3233 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
3236 InstructionClass Class = GetBasicInstructionClass(Inst);
3237 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3240 // Delete objc_loadWeak calls with no users.
3241 if (Class == IC_LoadWeak && Inst->use_empty()) {
3242 Inst->eraseFromParent();
3246 // TODO: For now, just look for an earlier available version of this value
3247 // within the same block. Theoretically, we could do memdep-style non-local
3248 // analysis too, but that would want caching. A better approach would be to
3249 // use the technique that EarlyCSE uses.
3250 inst_iterator Current = llvm::prior(I);
3251 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3252 for (BasicBlock::iterator B = CurrentBB->begin(),
3253 J = Current.getInstructionIterator();
3255 Instruction *EarlierInst = &*llvm::prior(J);
3256 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3257 switch (EarlierClass) {
3259 case IC_LoadWeakRetained: {
3260 // If this is loading from the same pointer, replace this load's value
3262 CallInst *Call = cast<CallInst>(Inst);
3263 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3264 Value *Arg = Call->getArgOperand(0);
3265 Value *EarlierArg = EarlierCall->getArgOperand(0);
3266 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3267 case AliasAnalysis::MustAlias:
3269 // If the load has a builtin retain, insert a plain retain for it.
3270 if (Class == IC_LoadWeakRetained) {
3272 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3276 // Zap the fully redundant load.
3277 Call->replaceAllUsesWith(EarlierCall);
3278 Call->eraseFromParent();
3280 case AliasAnalysis::MayAlias:
3281 case AliasAnalysis::PartialAlias:
3283 case AliasAnalysis::NoAlias:
3290 // If this is storing to the same pointer and has the same size etc.
3291 // replace this load's value with the stored value.
3292 CallInst *Call = cast<CallInst>(Inst);
3293 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3294 Value *Arg = Call->getArgOperand(0);
3295 Value *EarlierArg = EarlierCall->getArgOperand(0);
3296 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3297 case AliasAnalysis::MustAlias:
3299 // If the load has a builtin retain, insert a plain retain for it.
3300 if (Class == IC_LoadWeakRetained) {
3302 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3306 // Zap the fully redundant load.
3307 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3308 Call->eraseFromParent();
3310 case AliasAnalysis::MayAlias:
3311 case AliasAnalysis::PartialAlias:
3313 case AliasAnalysis::NoAlias:
3320 // TOOD: Grab the copied value.
3322 case IC_AutoreleasepoolPush:
3325 // Weak pointers are only modified through the weak entry points
3326 // (and arbitrary calls, which could call the weak entry points).
3329 // Anything else could modify the weak pointer.
3336 // Then, for each destroyWeak with an alloca operand, check to see if
3337 // the alloca and all its users can be zapped.
3338 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3339 Instruction *Inst = &*I++;
3340 InstructionClass Class = GetBasicInstructionClass(Inst);
3341 if (Class != IC_DestroyWeak)
3344 CallInst *Call = cast<CallInst>(Inst);
3345 Value *Arg = Call->getArgOperand(0);
3346 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3347 for (Value::use_iterator UI = Alloca->use_begin(),
3348 UE = Alloca->use_end(); UI != UE; ++UI) {
3349 const Instruction *UserInst = cast<Instruction>(*UI);
3350 switch (GetBasicInstructionClass(UserInst)) {
3353 case IC_DestroyWeak:
3360 for (Value::use_iterator UI = Alloca->use_begin(),
3361 UE = Alloca->use_end(); UI != UE; ) {
3362 CallInst *UserInst = cast<CallInst>(*UI++);
3363 switch (GetBasicInstructionClass(UserInst)) {
3366 // These functions return their second argument.
3367 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3369 case IC_DestroyWeak:
3373 llvm_unreachable("alloca really is used!");
3375 UserInst->eraseFromParent();
3377 Alloca->eraseFromParent();
3382 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
3386 /// Identify program paths which execute sequences of retains and releases which
3387 /// can be eliminated.
3388 bool ObjCARCOpt::OptimizeSequences(Function &F) {
3389 /// Releases, Retains - These are used to store the results of the main flow
3390 /// analysis. These use Value* as the key instead of Instruction* so that the
3391 /// map stays valid when we get around to rewriting code and calls get
3392 /// replaced by arguments.
3393 DenseMap<Value *, RRInfo> Releases;
3394 MapVector<Value *, RRInfo> Retains;
3396 /// This is used during the traversal of the function to track the
3397 /// states for each identified object at each block.
3398 DenseMap<const BasicBlock *, BBState> BBStates;
3400 // Analyze the CFG of the function, and all instructions.
3401 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3404 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3408 /// Look for this pattern:
3410 /// %call = call i8* @something(...)
3411 /// %2 = call i8* @objc_retain(i8* %call)
3412 /// %3 = call i8* @objc_autorelease(i8* %2)
3415 /// And delete the retain and autorelease.
3417 /// Otherwise if it's just this:
3419 /// %3 = call i8* @objc_autorelease(i8* %2)
3422 /// convert the autorelease to autoreleaseRV.
3423 void ObjCARCOpt::OptimizeReturns(Function &F) {
3424 if (!F.getReturnType()->isPointerTy())
3427 SmallPtrSet<Instruction *, 4> DependingInstructions;
3428 SmallPtrSet<const BasicBlock *, 4> Visited;
3429 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3430 BasicBlock *BB = FI;
3431 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3433 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
3437 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3438 FindDependencies(NeedsPositiveRetainCount, Arg,
3439 BB, Ret, DependingInstructions, Visited, PA);
3440 if (DependingInstructions.size() != 1)
3444 CallInst *Autorelease =
3445 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3448 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3449 if (!IsAutorelease(AutoreleaseClass))
3451 if (GetObjCArg(Autorelease) != Arg)
3454 DependingInstructions.clear();
3457 // Check that there is nothing that can affect the reference
3458 // count between the autorelease and the retain.
3459 FindDependencies(CanChangeRetainCount, Arg,
3460 BB, Autorelease, DependingInstructions, Visited, PA);
3461 if (DependingInstructions.size() != 1)
3466 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3468 // Check that we found a retain with the same argument.
3470 !IsRetain(GetBasicInstructionClass(Retain)) ||
3471 GetObjCArg(Retain) != Arg)
3474 DependingInstructions.clear();
3477 // Convert the autorelease to an autoreleaseRV, since it's
3478 // returning the value.
3479 if (AutoreleaseClass == IC_Autorelease) {
3480 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
3481 "=> autoreleaseRV since it's returning a value.\n"
3482 " In: " << *Autorelease
3484 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3485 DEBUG(dbgs() << " Out: " << *Autorelease
3487 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
3488 AutoreleaseClass = IC_AutoreleaseRV;
3491 // Check that there is nothing that can affect the reference
3492 // count between the retain and the call.
3493 // Note that Retain need not be in BB.
3494 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3495 DependingInstructions, Visited, PA);
3496 if (DependingInstructions.size() != 1)
3501 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3503 // Check that the pointer is the return value of the call.
3504 if (!Call || Arg != Call)
3507 // Check that the call is a regular call.
3508 InstructionClass Class = GetBasicInstructionClass(Call);
3509 if (Class != IC_CallOrUser && Class != IC_Call)
3512 // If so, we can zap the retain and autorelease.
3515 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
3517 << *Autorelease << "\n");
3518 EraseInstruction(Retain);
3519 EraseInstruction(Autorelease);
3525 DependingInstructions.clear();
3529 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
3533 bool ObjCARCOpt::doInitialization(Module &M) {
3537 // If nothing in the Module uses ARC, don't do anything.
3538 Run = ModuleHasARC(M);
3542 // Identify the imprecise release metadata kind.
3543 ImpreciseReleaseMDKind =
3544 M.getContext().getMDKindID("clang.imprecise_release");
3545 CopyOnEscapeMDKind =
3546 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3547 NoObjCARCExceptionsMDKind =
3548 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3550 // Intuitively, objc_retain and others are nocapture, however in practice
3551 // they are not, because they return their argument value. And objc_release
3552 // calls finalizers which can have arbitrary side effects.
3554 // These are initialized lazily.
3556 AutoreleaseRVCallee = 0;
3559 RetainBlockCallee = 0;
3560 AutoreleaseCallee = 0;
3565 bool ObjCARCOpt::runOnFunction(Function &F) {
3569 // If nothing in the Module uses ARC, don't do anything.
3575 DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
3577 PA.setAA(&getAnalysis<AliasAnalysis>());
3579 // This pass performs several distinct transformations. As a compile-time aid
3580 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3581 // library functions aren't declared.
3583 // Preliminary optimizations. This also computs UsedInThisFunction.
3584 OptimizeIndividualCalls(F);
3586 // Optimizations for weak pointers.
3587 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3588 (1 << IC_LoadWeakRetained) |
3589 (1 << IC_StoreWeak) |
3590 (1 << IC_InitWeak) |
3591 (1 << IC_CopyWeak) |
3592 (1 << IC_MoveWeak) |
3593 (1 << IC_DestroyWeak)))
3594 OptimizeWeakCalls(F);
3596 // Optimizations for retain+release pairs.
3597 if (UsedInThisFunction & ((1 << IC_Retain) |
3598 (1 << IC_RetainRV) |
3599 (1 << IC_RetainBlock)))
3600 if (UsedInThisFunction & (1 << IC_Release))
3601 // Run OptimizeSequences until it either stops making changes or
3602 // no retain+release pair nesting is detected.
3603 while (OptimizeSequences(F)) {}
3605 // Optimizations if objc_autorelease is used.
3606 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3607 (1 << IC_AutoreleaseRV)))
3610 DEBUG(dbgs() << "\n");
3615 void ObjCARCOpt::releaseMemory() {
3621 /// \defgroup ARCContract ARC Contraction.
3624 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
3625 // dominated by single calls.
3627 #include "llvm/Analysis/Dominators.h"
3628 #include "llvm/IR/InlineAsm.h"
3629 #include "llvm/IR/Operator.h"
3631 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3634 /// \brief Late ARC optimizations
3636 /// These change the IR in a way that makes it difficult to be analyzed by
3637 /// ObjCARCOpt, so it's run late.
3638 class ObjCARCContract : public FunctionPass {
3642 ProvenanceAnalysis PA;
3644 /// A flag indicating whether this optimization pass should run.
3647 /// Declarations for ObjC runtime functions, for use in creating calls to
3648 /// them. These are initialized lazily to avoid cluttering up the Module
3649 /// with unused declarations.
3651 /// Declaration for objc_storeStrong().
3652 Constant *StoreStrongCallee;
3653 /// Declaration for objc_retainAutorelease().
3654 Constant *RetainAutoreleaseCallee;
3655 /// Declaration for objc_retainAutoreleaseReturnValue().
3656 Constant *RetainAutoreleaseRVCallee;
3658 /// The inline asm string to insert between calls and RetainRV calls to make
3659 /// the optimization work on targets which need it.
3660 const MDString *RetainRVMarker;
3662 /// The set of inserted objc_storeStrong calls. If at the end of walking the
3663 /// function we have found no alloca instructions, these calls can be marked
3665 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
3667 Constant *getStoreStrongCallee(Module *M);
3668 Constant *getRetainAutoreleaseCallee(Module *M);
3669 Constant *getRetainAutoreleaseRVCallee(Module *M);
3671 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3672 InstructionClass Class,
3673 SmallPtrSet<Instruction *, 4>
3674 &DependingInstructions,
3675 SmallPtrSet<const BasicBlock *, 4>
3678 void ContractRelease(Instruction *Release,
3679 inst_iterator &Iter);
3681 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3682 virtual bool doInitialization(Module &M);
3683 virtual bool runOnFunction(Function &F);
3687 ObjCARCContract() : FunctionPass(ID) {
3688 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3693 char ObjCARCContract::ID = 0;
3694 INITIALIZE_PASS_BEGIN(ObjCARCContract,
3695 "objc-arc-contract", "ObjC ARC contraction", false, false)
3696 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3697 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3698 INITIALIZE_PASS_END(ObjCARCContract,
3699 "objc-arc-contract", "ObjC ARC contraction", false, false)
3701 Pass *llvm::createObjCARCContractPass() {
3702 return new ObjCARCContract();
3705 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3706 AU.addRequired<AliasAnalysis>();
3707 AU.addRequired<DominatorTree>();
3708 AU.setPreservesCFG();
3711 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3712 if (!StoreStrongCallee) {
3713 LLVMContext &C = M->getContext();
3714 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3715 Type *I8XX = PointerType::getUnqual(I8X);
3716 Type *Params[] = { I8XX, I8X };
3718 AttributeSet Attr = AttributeSet()
3719 .addAttribute(M->getContext(), AttributeSet::FunctionIndex,
3720 Attribute::NoUnwind)
3721 .addAttribute(M->getContext(), 1, Attribute::NoCapture);
3724 M->getOrInsertFunction(
3726 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3729 return StoreStrongCallee;
3732 Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3733 if (!RetainAutoreleaseCallee) {
3734 LLVMContext &C = M->getContext();
3735 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3736 Type *Params[] = { I8X };
3737 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
3738 AttributeSet Attribute =
3739 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
3740 Attribute::NoUnwind);
3741 RetainAutoreleaseCallee =
3742 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
3744 return RetainAutoreleaseCallee;
3747 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3748 if (!RetainAutoreleaseRVCallee) {
3749 LLVMContext &C = M->getContext();
3750 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3751 Type *Params[] = { I8X };
3752 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
3753 AttributeSet Attribute =
3754 AttributeSet().addAttribute(M->getContext(), AttributeSet::FunctionIndex,
3755 Attribute::NoUnwind);
3756 RetainAutoreleaseRVCallee =
3757 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3760 return RetainAutoreleaseRVCallee;
3763 /// Merge an autorelease with a retain into a fused call.
3765 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3766 InstructionClass Class,
3767 SmallPtrSet<Instruction *, 4>
3768 &DependingInstructions,
3769 SmallPtrSet<const BasicBlock *, 4>
3771 const Value *Arg = GetObjCArg(Autorelease);
3773 // Check that there are no instructions between the retain and the autorelease
3774 // (such as an autorelease_pop) which may change the count.
3775 CallInst *Retain = 0;
3776 if (Class == IC_AutoreleaseRV)
3777 FindDependencies(RetainAutoreleaseRVDep, Arg,
3778 Autorelease->getParent(), Autorelease,
3779 DependingInstructions, Visited, PA);
3781 FindDependencies(RetainAutoreleaseDep, Arg,
3782 Autorelease->getParent(), Autorelease,
3783 DependingInstructions, Visited, PA);
3786 if (DependingInstructions.size() != 1) {
3787 DependingInstructions.clear();
3791 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3792 DependingInstructions.clear();
3795 GetBasicInstructionClass(Retain) != IC_Retain ||
3796 GetObjCArg(Retain) != Arg)
3802 DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing "
3803 "retain/autorelease. Erasing: " << *Autorelease << "\n"
3805 << *Retain << "\n");
3807 if (Class == IC_AutoreleaseRV)
3808 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3810 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3812 DEBUG(dbgs() << " New Retain: "
3813 << *Retain << "\n");
3815 EraseInstruction(Autorelease);
3819 /// Attempt to merge an objc_release with a store, load, and objc_retain to form
3820 /// an objc_storeStrong. This can be a little tricky because the instructions
3821 /// don't always appear in order, and there may be unrelated intervening
3823 void ObjCARCContract::ContractRelease(Instruction *Release,
3824 inst_iterator &Iter) {
3825 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
3826 if (!Load || !Load->isSimple()) return;
3828 // For now, require everything to be in one basic block.
3829 BasicBlock *BB = Release->getParent();
3830 if (Load->getParent() != BB) return;
3832 // Walk down to find the store and the release, which may be in either order.
3833 BasicBlock::iterator I = Load, End = BB->end();
3835 AliasAnalysis::Location Loc = AA->getLocation(Load);
3836 StoreInst *Store = 0;
3837 bool SawRelease = false;
3838 for (; !Store || !SawRelease; ++I) {
3842 Instruction *Inst = I;
3843 if (Inst == Release) {
3848 InstructionClass Class = GetBasicInstructionClass(Inst);
3850 // Unrelated retains are harmless.
3851 if (IsRetain(Class))
3855 // The store is the point where we're going to put the objc_storeStrong,
3856 // so make sure there are no uses after it.
3857 if (CanUse(Inst, Load, PA, Class))
3859 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
3860 // We are moving the load down to the store, so check for anything
3861 // else which writes to the memory between the load and the store.
3862 Store = dyn_cast<StoreInst>(Inst);
3863 if (!Store || !Store->isSimple()) return;
3864 if (Store->getPointerOperand() != Loc.Ptr) return;
3868 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3870 // Walk up to find the retain.
3872 BasicBlock::iterator Begin = BB->begin();
3873 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3875 Instruction *Retain = I;
3876 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3877 if (GetObjCArg(Retain) != New) return;
3882 LLVMContext &C = Release->getContext();
3883 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3884 Type *I8XX = PointerType::getUnqual(I8X);
3886 Value *Args[] = { Load->getPointerOperand(), New };
3887 if (Args[0]->getType() != I8XX)
3888 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3889 if (Args[1]->getType() != I8X)
3890 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3891 CallInst *StoreStrong =
3892 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
3894 StoreStrong->setDoesNotThrow();
3895 StoreStrong->setDebugLoc(Store->getDebugLoc());
3897 // We can't set the tail flag yet, because we haven't yet determined
3898 // whether there are any escaping allocas. Remember this call, so that
3899 // we can set the tail flag once we know it's safe.
3900 StoreStrongCalls.insert(StoreStrong);
3902 if (&*Iter == Store) ++Iter;
3903 Store->eraseFromParent();
3904 Release->eraseFromParent();
3905 EraseInstruction(Retain);
3906 if (Load->use_empty())
3907 Load->eraseFromParent();
3910 bool ObjCARCContract::doInitialization(Module &M) {
3911 // If nothing in the Module uses ARC, don't do anything.
3912 Run = ModuleHasARC(M);
3916 // These are initialized lazily.
3917 StoreStrongCallee = 0;
3918 RetainAutoreleaseCallee = 0;
3919 RetainAutoreleaseRVCallee = 0;
3921 // Initialize RetainRVMarker.
3923 if (NamedMDNode *NMD =
3924 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3925 if (NMD->getNumOperands() == 1) {
3926 const MDNode *N = NMD->getOperand(0);
3927 if (N->getNumOperands() == 1)
3928 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
3935 bool ObjCARCContract::runOnFunction(Function &F) {
3939 // If nothing in the Module uses ARC, don't do anything.
3944 AA = &getAnalysis<AliasAnalysis>();
3945 DT = &getAnalysis<DominatorTree>();
3947 PA.setAA(&getAnalysis<AliasAnalysis>());
3949 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
3950 // keyword. Be conservative if the function has variadic arguments.
3951 // It seems that functions which "return twice" are also unsafe for the
3952 // "tail" argument, because they are setjmp, which could need to
3953 // return to an earlier stack state.
3954 bool TailOkForStoreStrongs = !F.isVarArg() &&
3955 !F.callsFunctionThatReturnsTwice();
3957 // For ObjC library calls which return their argument, replace uses of the
3958 // argument with uses of the call return value, if it dominates the use. This
3959 // reduces register pressure.
3960 SmallPtrSet<Instruction *, 4> DependingInstructions;
3961 SmallPtrSet<const BasicBlock *, 4> Visited;
3962 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3963 Instruction *Inst = &*I++;
3965 DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
3967 // Only these library routines return their argument. In particular,
3968 // objc_retainBlock does not necessarily return its argument.
3969 InstructionClass Class = GetBasicInstructionClass(Inst);
3972 case IC_FusedRetainAutorelease:
3973 case IC_FusedRetainAutoreleaseRV:
3975 case IC_Autorelease:
3976 case IC_AutoreleaseRV:
3977 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
3981 // If we're compiling for a target which needs a special inline-asm
3982 // marker to do the retainAutoreleasedReturnValue optimization,
3984 if (!RetainRVMarker)
3986 BasicBlock::iterator BBI = Inst;
3987 BasicBlock *InstParent = Inst->getParent();
3989 // Step up to see if the call immediately precedes the RetainRV call.
3990 // If it's an invoke, we have to cross a block boundary. And we have
3991 // to carefully dodge no-op instructions.
3993 if (&*BBI == InstParent->begin()) {
3994 BasicBlock *Pred = InstParent->getSinglePredecessor();
3996 goto decline_rv_optimization;
3997 BBI = Pred->getTerminator();
4001 } while (isNoopInstruction(BBI));
4003 if (&*BBI == GetObjCArg(Inst)) {
4004 DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
4005 "retainAutoreleasedReturnValue optimization.\n");
4008 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4009 /*isVarArg=*/false),
4010 RetainRVMarker->getString(),
4011 /*Constraints=*/"", /*hasSideEffects=*/true);
4012 CallInst::Create(IA, "", Inst);
4014 decline_rv_optimization:
4018 // objc_initWeak(p, null) => *p = null
4019 CallInst *CI = cast<CallInst>(Inst);
4020 if (isNullOrUndef(CI->getArgOperand(1))) {
4022 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4024 new StoreInst(Null, CI->getArgOperand(0), CI);
4026 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
4027 << " New = " << *Null << "\n");
4029 CI->replaceAllUsesWith(Null);
4030 CI->eraseFromParent();
4035 ContractRelease(Inst, I);
4038 // Be conservative if the function has any alloca instructions.
4039 // Technically we only care about escaping alloca instructions,
4040 // but this is sufficient to handle some interesting cases.
4041 if (isa<AllocaInst>(Inst))
4042 TailOkForStoreStrongs = false;
4048 DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n");
4050 // Don't use GetObjCArg because we don't want to look through bitcasts
4051 // and such; to do the replacement, the argument must have type i8*.
4052 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4054 // If we're compiling bugpointed code, don't get in trouble.
4055 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4057 // Look through the uses of the pointer.
4058 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4060 Use &U = UI.getUse();
4061 unsigned OperandNo = UI.getOperandNo();
4062 ++UI; // Increment UI now, because we may unlink its element.
4064 // If the call's return value dominates a use of the call's argument
4065 // value, rewrite the use to use the return value. We check for
4066 // reachability here because an unreachable call is considered to
4067 // trivially dominate itself, which would lead us to rewriting its
4068 // argument in terms of its return value, which would lead to
4069 // infinite loops in GetObjCArg.
4070 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
4072 Instruction *Replacement = Inst;
4073 Type *UseTy = U.get()->getType();
4074 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
4075 // For PHI nodes, insert the bitcast in the predecessor block.
4076 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4077 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
4078 if (Replacement->getType() != UseTy)
4079 Replacement = new BitCastInst(Replacement, UseTy, "",
4081 // While we're here, rewrite all edges for this PHI, rather
4082 // than just one use at a time, to minimize the number of
4083 // bitcasts we emit.
4084 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4085 if (PHI->getIncomingBlock(i) == BB) {
4086 // Keep the UI iterator valid.
4087 if (&PHI->getOperandUse(
4088 PHINode::getOperandNumForIncomingValue(i)) ==
4091 PHI->setIncomingValue(i, Replacement);
4094 if (Replacement->getType() != UseTy)
4095 Replacement = new BitCastInst(Replacement, UseTy, "",
4096 cast<Instruction>(U.getUser()));
4102 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
4103 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4104 Arg = BI->getOperand(0);
4105 else if (isa<GEPOperator>(Arg) &&
4106 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4107 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4108 else if (isa<GlobalAlias>(Arg) &&
4109 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4110 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4116 // If this function has no escaping allocas or suspicious vararg usage,
4117 // objc_storeStrong calls can be marked with the "tail" keyword.
4118 if (TailOkForStoreStrongs)
4119 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
4120 E = StoreStrongCalls.end(); I != E; ++I)
4121 (*I)->setTailCall();
4122 StoreStrongCalls.clear();