1 //===- ObjCARC.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"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
39 /// \brief A handy option to enable/disable all optimizations in this file.
40 static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
42 /// \defgroup MiscUtils Miscellaneous utilities that are not ARC specific.
46 /// \brief An associative container with fast insertion-order (deterministic)
47 /// iteration over its elements. Plus the special blot operation.
48 template<class KeyT, class ValueT>
50 /// Map keys to indices in Vector.
51 typedef DenseMap<KeyT, size_t> MapTy;
54 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
59 typedef typename VectorTy::iterator iterator;
60 typedef typename VectorTy::const_iterator const_iterator;
61 iterator begin() { return Vector.begin(); }
62 iterator end() { return Vector.end(); }
63 const_iterator begin() const { return Vector.begin(); }
64 const_iterator end() const { return Vector.end(); }
68 assert(Vector.size() >= Map.size()); // May differ due to blotting.
69 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
71 assert(I->second < Vector.size());
72 assert(Vector[I->second].first == I->first);
74 for (typename VectorTy::const_iterator I = Vector.begin(),
75 E = Vector.end(); I != E; ++I)
77 (Map.count(I->first) &&
78 Map[I->first] == size_t(I - Vector.begin())));
82 ValueT &operator[](const KeyT &Arg) {
83 std::pair<typename MapTy::iterator, bool> Pair =
84 Map.insert(std::make_pair(Arg, size_t(0)));
86 size_t Num = Vector.size();
87 Pair.first->second = Num;
88 Vector.push_back(std::make_pair(Arg, ValueT()));
89 return Vector[Num].second;
91 return Vector[Pair.first->second].second;
94 std::pair<iterator, bool>
95 insert(const std::pair<KeyT, ValueT> &InsertPair) {
96 std::pair<typename MapTy::iterator, bool> Pair =
97 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
99 size_t Num = Vector.size();
100 Pair.first->second = Num;
101 Vector.push_back(InsertPair);
102 return std::make_pair(Vector.begin() + Num, true);
104 return std::make_pair(Vector.begin() + Pair.first->second, false);
107 const_iterator find(const KeyT &Key) const {
108 typename MapTy::const_iterator It = Map.find(Key);
109 if (It == Map.end()) return Vector.end();
110 return Vector.begin() + It->second;
113 /// This is similar to erase, but instead of removing the element from the
114 /// vector, it just zeros out the key in the vector. This leaves iterators
115 /// intact, but clients must be prepared for zeroed-out keys when iterating.
116 void blot(const KeyT &Key) {
117 typename MapTy::iterator It = Map.find(Key);
118 if (It == Map.end()) return;
119 Vector[It->second].first = KeyT();
132 /// \defgroup ARCUtilities Utility declarations/definitions specific to ARC.
135 #include "llvm/ADT/StringSwitch.h"
136 #include "llvm/Analysis/ValueTracking.h"
137 #include "llvm/IR/Intrinsics.h"
138 #include "llvm/IR/Module.h"
139 #include "llvm/Support/CallSite.h"
140 #include "llvm/Transforms/Utils/Local.h"
143 /// \enum InstructionClass
144 /// \brief A simple classification for instructions.
145 enum InstructionClass {
146 IC_Retain, ///< objc_retain
147 IC_RetainRV, ///< objc_retainAutoreleasedReturnValue
148 IC_RetainBlock, ///< objc_retainBlock
149 IC_Release, ///< objc_release
150 IC_Autorelease, ///< objc_autorelease
151 IC_AutoreleaseRV, ///< objc_autoreleaseReturnValue
152 IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
153 IC_AutoreleasepoolPop, ///< objc_autoreleasePoolPop
154 IC_NoopCast, ///< objc_retainedObject, etc.
155 IC_FusedRetainAutorelease, ///< objc_retainAutorelease
156 IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
157 IC_LoadWeakRetained, ///< objc_loadWeakRetained (primitive)
158 IC_StoreWeak, ///< objc_storeWeak (primitive)
159 IC_InitWeak, ///< objc_initWeak (derived)
160 IC_LoadWeak, ///< objc_loadWeak (derived)
161 IC_MoveWeak, ///< objc_moveWeak (derived)
162 IC_CopyWeak, ///< objc_copyWeak (derived)
163 IC_DestroyWeak, ///< objc_destroyWeak (derived)
164 IC_StoreStrong, ///< objc_storeStrong (derived)
165 IC_CallOrUser, ///< could call objc_release and/or "use" pointers
166 IC_Call, ///< could call objc_release
167 IC_User, ///< could "use" a pointer
168 IC_None ///< anything else
171 raw_ostream &operator<<(raw_ostream &OS, const InstructionClass Class)
173 raw_ostream &operator<<(raw_ostream &OS, const InstructionClass Class) {
176 return OS << "IC_Retain";
178 return OS << "IC_RetainRV";
180 return OS << "IC_RetainBlock";
182 return OS << "IC_Release";
184 return OS << "IC_Autorelease";
185 case IC_AutoreleaseRV:
186 return OS << "IC_AutoreleaseRV";
187 case IC_AutoreleasepoolPush:
188 return OS << "IC_AutoreleasepoolPush";
189 case IC_AutoreleasepoolPop:
190 return OS << "IC_AutoreleasepoolPop";
192 return OS << "IC_NoopCast";
193 case IC_FusedRetainAutorelease:
194 return OS << "IC_FusedRetainAutorelease";
195 case IC_FusedRetainAutoreleaseRV:
196 return OS << "IC_FusedRetainAutoreleaseRV";
197 case IC_LoadWeakRetained:
198 return OS << "IC_LoadWeakRetained";
200 return OS << "IC_StoreWeak";
202 return OS << "IC_InitWeak";
204 return OS << "IC_LoadWeak";
206 return OS << "IC_MoveWeak";
208 return OS << "IC_CopyWeak";
210 return OS << "IC_DestroyWeak";
212 return OS << "IC_StoreStrong";
214 return OS << "IC_CallOrUser";
216 return OS << "IC_Call";
218 return OS << "IC_User";
220 return OS << "IC_None";
225 /// \brief Test whether the given value is possible a reference-counted pointer.
226 static bool IsPotentialUse(const Value *Op) {
227 // Pointers to static or stack storage are not reference-counted pointers.
228 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
230 // Special arguments are not reference-counted.
231 if (const Argument *Arg = dyn_cast<Argument>(Op))
232 if (Arg->hasByValAttr() ||
233 Arg->hasNestAttr() ||
234 Arg->hasStructRetAttr())
236 // Only consider values with pointer types.
237 // It seemes intuitive to exclude function pointer types as well, since
238 // functions are never reference-counted, however clang occasionally
239 // bitcasts reference-counted pointers to function-pointer type
241 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
244 // Conservatively assume anything else is a potential use.
248 /// \brief Helper for GetInstructionClass. Determines what kind of construct CS
250 static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
251 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
253 if (IsPotentialUse(*I))
254 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
256 return CS.onlyReadsMemory() ? IC_None : IC_Call;
259 /// \brief Determine if F is one of the special known Functions. If it isn't,
260 /// return IC_CallOrUser.
261 static InstructionClass GetFunctionClass(const Function *F) {
262 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
266 return StringSwitch<InstructionClass>(F->getName())
267 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
268 .Default(IC_CallOrUser);
271 const Argument *A0 = AI++;
273 // Argument is a pointer.
274 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
275 Type *ETy = PTy->getElementType();
277 if (ETy->isIntegerTy(8))
278 return StringSwitch<InstructionClass>(F->getName())
279 .Case("objc_retain", IC_Retain)
280 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
281 .Case("objc_retainBlock", IC_RetainBlock)
282 .Case("objc_release", IC_Release)
283 .Case("objc_autorelease", IC_Autorelease)
284 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
285 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
286 .Case("objc_retainedObject", IC_NoopCast)
287 .Case("objc_unretainedObject", IC_NoopCast)
288 .Case("objc_unretainedPointer", IC_NoopCast)
289 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
290 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
291 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
292 .Default(IC_CallOrUser);
295 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
296 if (Pte->getElementType()->isIntegerTy(8))
297 return StringSwitch<InstructionClass>(F->getName())
298 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
299 .Case("objc_loadWeak", IC_LoadWeak)
300 .Case("objc_destroyWeak", IC_DestroyWeak)
301 .Default(IC_CallOrUser);
304 // Two arguments, first is i8**.
305 const Argument *A1 = AI++;
307 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
308 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
309 if (Pte->getElementType()->isIntegerTy(8))
310 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
311 Type *ETy1 = PTy1->getElementType();
312 // Second argument is i8*
313 if (ETy1->isIntegerTy(8))
314 return StringSwitch<InstructionClass>(F->getName())
315 .Case("objc_storeWeak", IC_StoreWeak)
316 .Case("objc_initWeak", IC_InitWeak)
317 .Case("objc_storeStrong", IC_StoreStrong)
318 .Default(IC_CallOrUser);
319 // Second argument is i8**.
320 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
321 if (Pte1->getElementType()->isIntegerTy(8))
322 return StringSwitch<InstructionClass>(F->getName())
323 .Case("objc_moveWeak", IC_MoveWeak)
324 .Case("objc_copyWeak", IC_CopyWeak)
325 .Default(IC_CallOrUser);
329 return IC_CallOrUser;
332 /// \brief Determine what kind of construct V is.
333 static InstructionClass GetInstructionClass(const Value *V) {
334 if (const Instruction *I = dyn_cast<Instruction>(V)) {
335 // Any instruction other than bitcast and gep with a pointer operand have a
336 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
337 // to a subsequent use, rather than using it themselves, in this sense.
338 // As a short cut, several other opcodes are known to have no pointer
339 // operands of interest. And ret is never followed by a release, so it's
340 // not interesting to examine.
341 switch (I->getOpcode()) {
342 case Instruction::Call: {
343 const CallInst *CI = cast<CallInst>(I);
344 // Check for calls to special functions.
345 if (const Function *F = CI->getCalledFunction()) {
346 InstructionClass Class = GetFunctionClass(F);
347 if (Class != IC_CallOrUser)
350 // None of the intrinsic functions do objc_release. For intrinsics, the
351 // only question is whether or not they may be users.
352 switch (F->getIntrinsicID()) {
353 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
354 case Intrinsic::stacksave: case Intrinsic::stackrestore:
355 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
356 case Intrinsic::objectsize: case Intrinsic::prefetch:
357 case Intrinsic::stackprotector:
358 case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
359 case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
360 case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
361 case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
362 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
363 case Intrinsic::invariant_start: case Intrinsic::invariant_end:
364 // Don't let dbg info affect our results.
365 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
366 // Short cut: Some intrinsics obviously don't use ObjC pointers.
372 return GetCallSiteClass(CI);
374 case Instruction::Invoke:
375 return GetCallSiteClass(cast<InvokeInst>(I));
376 case Instruction::BitCast:
377 case Instruction::GetElementPtr:
378 case Instruction::Select: case Instruction::PHI:
379 case Instruction::Ret: case Instruction::Br:
380 case Instruction::Switch: case Instruction::IndirectBr:
381 case Instruction::Alloca: case Instruction::VAArg:
382 case Instruction::Add: case Instruction::FAdd:
383 case Instruction::Sub: case Instruction::FSub:
384 case Instruction::Mul: case Instruction::FMul:
385 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
386 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
387 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
388 case Instruction::And: case Instruction::Or: case Instruction::Xor:
389 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
390 case Instruction::IntToPtr: case Instruction::FCmp:
391 case Instruction::FPTrunc: case Instruction::FPExt:
392 case Instruction::FPToUI: case Instruction::FPToSI:
393 case Instruction::UIToFP: case Instruction::SIToFP:
394 case Instruction::InsertElement: case Instruction::ExtractElement:
395 case Instruction::ShuffleVector:
396 case Instruction::ExtractValue:
398 case Instruction::ICmp:
399 // Comparing a pointer with null, or any other constant, isn't an
400 // interesting use, because we don't care what the pointer points to, or
401 // about the values of any other dynamic reference-counted pointers.
402 if (IsPotentialUse(I->getOperand(1)))
406 // For anything else, check all the operands.
407 // Note that this includes both operands of a Store: while the first
408 // operand isn't actually being dereferenced, it is being stored to
409 // memory where we can no longer track who might read it and dereference
410 // it, so we have to consider it potentially used.
411 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
413 if (IsPotentialUse(*OI))
418 // Otherwise, it's totally inert for ARC purposes.
422 /// \brief Determine which objc runtime call instruction class V belongs to.
424 /// This is similar to GetInstructionClass except that it only detects objc
425 /// runtime calls. This allows it to be faster.
427 static InstructionClass GetBasicInstructionClass(const Value *V) {
428 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
429 if (const Function *F = CI->getCalledFunction())
430 return GetFunctionClass(F);
431 // Otherwise, be conservative.
432 return IC_CallOrUser;
435 // Otherwise, be conservative.
436 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
439 /// \brief Test if the given class is objc_retain or equivalent.
440 static bool IsRetain(InstructionClass Class) {
441 return Class == IC_Retain ||
442 Class == IC_RetainRV;
445 /// \brief Test if the given class is objc_autorelease or equivalent.
446 static bool IsAutorelease(InstructionClass Class) {
447 return Class == IC_Autorelease ||
448 Class == IC_AutoreleaseRV;
451 /// \brief Test if the given class represents instructions which return their
452 /// argument verbatim.
453 static bool IsForwarding(InstructionClass Class) {
454 // objc_retainBlock technically doesn't always return its argument
455 // verbatim, but it doesn't matter for our purposes here.
456 return Class == IC_Retain ||
457 Class == IC_RetainRV ||
458 Class == IC_Autorelease ||
459 Class == IC_AutoreleaseRV ||
460 Class == IC_RetainBlock ||
461 Class == IC_NoopCast;
464 /// \brief Test if the given class represents instructions which do nothing if
465 /// passed a null pointer.
466 static bool IsNoopOnNull(InstructionClass Class) {
467 return Class == IC_Retain ||
468 Class == IC_RetainRV ||
469 Class == IC_Release ||
470 Class == IC_Autorelease ||
471 Class == IC_AutoreleaseRV ||
472 Class == IC_RetainBlock;
475 /// \brief Test if the given class represents instructions which are always safe
476 /// to mark with the "tail" keyword.
477 static bool IsAlwaysTail(InstructionClass Class) {
478 // IC_RetainBlock may be given a stack argument.
479 return Class == IC_Retain ||
480 Class == IC_RetainRV ||
481 Class == IC_AutoreleaseRV;
484 /// \brief Test if the given class represents instructions which are never safe
485 /// to mark with the "tail" keyword.
486 static bool IsNeverTail(InstructionClass Class) {
487 /// It is never safe to tail call objc_autorelease since by tail calling
488 /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
489 /// fast autoreleasing causing our object to be potentially reclaimed from the
490 /// autorelease pool which violates the semantics of __autoreleasing types in
492 return Class == IC_Autorelease;
495 /// \brief Test if the given class represents instructions which are always safe
496 /// to mark with the nounwind attribute.
497 static bool IsNoThrow(InstructionClass Class) {
498 // objc_retainBlock is not nounwind because it calls user copy constructors
499 // which could theoretically throw.
500 return Class == IC_Retain ||
501 Class == IC_RetainRV ||
502 Class == IC_Release ||
503 Class == IC_Autorelease ||
504 Class == IC_AutoreleaseRV ||
505 Class == IC_AutoreleasepoolPush ||
506 Class == IC_AutoreleasepoolPop;
509 /// \brief Erase the given instruction.
511 /// Many ObjC calls return their argument verbatim,
512 /// so if it's such a call and the return value has users, replace them with the
515 static void EraseInstruction(Instruction *CI) {
516 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
518 bool Unused = CI->use_empty();
521 // Replace the return value with the argument.
522 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
523 "Can't delete non-forwarding instruction with users!");
524 CI->replaceAllUsesWith(OldArg);
527 CI->eraseFromParent();
530 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
533 /// \brief This is a wrapper around getUnderlyingObject which also knows how to
534 /// look through objc_retain and objc_autorelease calls, which we know to return
535 /// their argument verbatim.
536 static const Value *GetUnderlyingObjCPtr(const Value *V) {
538 V = GetUnderlyingObject(V);
539 if (!IsForwarding(GetBasicInstructionClass(V)))
541 V = cast<CallInst>(V)->getArgOperand(0);
547 /// \brief This is a wrapper around Value::stripPointerCasts which also knows
548 /// how to look through objc_retain and objc_autorelease calls, which we know to
549 /// return their argument verbatim.
550 static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
552 V = V->stripPointerCasts();
553 if (!IsForwarding(GetBasicInstructionClass(V)))
555 V = cast<CallInst>(V)->getArgOperand(0);
560 /// \brief This is a wrapper around Value::stripPointerCasts which also knows
561 /// how to look through objc_retain and objc_autorelease calls, which we know to
562 /// return their argument verbatim.
563 static Value *StripPointerCastsAndObjCCalls(Value *V) {
565 V = V->stripPointerCasts();
566 if (!IsForwarding(GetBasicInstructionClass(V)))
568 V = cast<CallInst>(V)->getArgOperand(0);
573 /// \brief Assuming the given instruction is one of the special calls such as
574 /// objc_retain or objc_release, return the argument value, stripped of no-op
575 /// casts and forwarding calls.
576 static Value *GetObjCArg(Value *Inst) {
577 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
580 /// \brief This is similar to AliasAnalysis's isObjCIdentifiedObject, except
581 /// that it uses special knowledge of ObjC conventions.
582 static bool IsObjCIdentifiedObject(const Value *V) {
583 // Assume that call results and arguments have their own "provenance".
584 // Constants (including GlobalVariables) and Allocas are never
585 // reference-counted.
586 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
587 isa<Argument>(V) || isa<Constant>(V) ||
591 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
592 const Value *Pointer =
593 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
594 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
595 // A constant pointer can't be pointing to an object on the heap. It may
596 // be reference-counted, but it won't be deleted.
597 if (GV->isConstant())
599 StringRef Name = GV->getName();
600 // These special variables are known to hold values which are not
601 // reference-counted pointers.
602 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
603 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
604 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
605 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
606 Name.startswith("\01l_objc_msgSend_fixup_"))
614 /// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
615 /// as it finds a value with multiple uses.
616 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
617 if (Arg->hasOneUse()) {
618 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
619 return FindSingleUseIdentifiedObject(BC->getOperand(0));
620 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
621 if (GEP->hasAllZeroIndices())
622 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
623 if (IsForwarding(GetBasicInstructionClass(Arg)))
624 return FindSingleUseIdentifiedObject(
625 cast<CallInst>(Arg)->getArgOperand(0));
626 if (!IsObjCIdentifiedObject(Arg))
631 // If we found an identifiable object but it has multiple uses, but they are
632 // trivial uses, we can still consider this to be a single-use value.
633 if (IsObjCIdentifiedObject(Arg)) {
634 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
637 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
647 /// \brief Test if the given module looks interesting to run ARC optimization
649 static bool ModuleHasARC(const Module &M) {
651 M.getNamedValue("objc_retain") ||
652 M.getNamedValue("objc_release") ||
653 M.getNamedValue("objc_autorelease") ||
654 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
655 M.getNamedValue("objc_retainBlock") ||
656 M.getNamedValue("objc_autoreleaseReturnValue") ||
657 M.getNamedValue("objc_autoreleasePoolPush") ||
658 M.getNamedValue("objc_loadWeakRetained") ||
659 M.getNamedValue("objc_loadWeak") ||
660 M.getNamedValue("objc_destroyWeak") ||
661 M.getNamedValue("objc_storeWeak") ||
662 M.getNamedValue("objc_initWeak") ||
663 M.getNamedValue("objc_moveWeak") ||
664 M.getNamedValue("objc_copyWeak") ||
665 M.getNamedValue("objc_retainedObject") ||
666 M.getNamedValue("objc_unretainedObject") ||
667 M.getNamedValue("objc_unretainedPointer");
670 /// \brief Test whether the given pointer, which is an Objective C block
671 /// pointer, does not "escape".
673 /// This differs from regular escape analysis in that a use as an
674 /// argument to a call is not considered an escape.
676 static bool DoesObjCBlockEscape(const Value *BlockPtr) {
678 DEBUG(dbgs() << "DoesObjCBlockEscape: Target: " << *BlockPtr << "\n");
680 // Walk the def-use chains.
681 SmallVector<const Value *, 4> Worklist;
682 Worklist.push_back(BlockPtr);
684 // Ensure we do not visit any value twice.
685 SmallPtrSet<const Value *, 4> VisitedSet;
688 const Value *V = Worklist.pop_back_val();
690 DEBUG(dbgs() << "DoesObjCBlockEscape: Visiting: " << *V << "\n");
692 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
694 const User *UUser = *UI;
696 DEBUG(dbgs() << "DoesObjCBlockEscape: User: " << *UUser << "\n");
698 // Special - Use by a call (callee or argument) is not considered
700 switch (GetBasicInstructionClass(UUser)) {
705 case IC_AutoreleaseRV: {
706 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies pointer arguments. "
708 // These special functions make copies of their pointer arguments.
713 // Use by an instruction which copies the value is an escape if the
714 // result is an escape.
715 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
716 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
718 if (!VisitedSet.insert(UUser)) {
719 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies value. Escapes "
720 "if result escapes. Adding to list.\n");
721 Worklist.push_back(UUser);
723 DEBUG(dbgs() << "DoesObjCBlockEscape: Already visited node.\n");
727 // Use by a load is not an escape.
728 if (isa<LoadInst>(UUser))
730 // Use by a store is not an escape if the use is the address.
731 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
732 if (V != SI->getValueOperand())
736 // Regular calls and other stuff are not considered escapes.
739 // Otherwise, conservatively assume an escape.
740 DEBUG(dbgs() << "DoesObjCBlockEscape: Assuming block escapes.\n");
743 } while (!Worklist.empty());
746 DEBUG(dbgs() << "DoesObjCBlockEscape: Block does not escape.\n");
752 /// \defgroup ARCAA Extends alias analysis using ObjC specific knowledge.
755 #include "llvm/Analysis/AliasAnalysis.h"
756 #include "llvm/Analysis/Passes.h"
757 #include "llvm/Pass.h"
760 /// \brief This is a simple alias analysis implementation that uses knowledge
761 /// of ARC constructs to answer queries.
763 /// TODO: This class could be generalized to know about other ObjC-specific
764 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
765 /// even though their offsets are dynamic.
766 class ObjCARCAliasAnalysis : public ImmutablePass,
767 public AliasAnalysis {
769 static char ID; // Class identification, replacement for typeinfo
770 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
771 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
775 virtual void initializePass() {
776 InitializeAliasAnalysis(this);
779 /// This method is used when a pass implements an analysis interface through
780 /// multiple inheritance. If needed, it should override this to adjust the
781 /// this pointer as needed for the specified pass info.
782 virtual void *getAdjustedAnalysisPointer(const void *PI) {
783 if (PI == &AliasAnalysis::ID)
784 return static_cast<AliasAnalysis *>(this);
788 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
789 virtual AliasResult alias(const Location &LocA, const Location &LocB);
790 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
791 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
792 virtual ModRefBehavior getModRefBehavior(const Function *F);
793 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
794 const Location &Loc);
795 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
796 ImmutableCallSite CS2);
798 } // End of anonymous namespace
800 // Register this pass...
801 char ObjCARCAliasAnalysis::ID = 0;
802 INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
803 "ObjC-ARC-Based Alias Analysis", false, true, false)
805 ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
806 return new ObjCARCAliasAnalysis();
810 ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
811 AU.setPreservesAll();
812 AliasAnalysis::getAnalysisUsage(AU);
815 AliasAnalysis::AliasResult
816 ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
818 return AliasAnalysis::alias(LocA, LocB);
820 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
821 // precise alias query.
822 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
823 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
825 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
826 Location(SB, LocB.Size, LocB.TBAATag));
827 if (Result != MayAlias)
830 // If that failed, climb to the underlying object, including climbing through
831 // ObjC-specific no-ops, and try making an imprecise alias query.
832 const Value *UA = GetUnderlyingObjCPtr(SA);
833 const Value *UB = GetUnderlyingObjCPtr(SB);
834 if (UA != SA || UB != SB) {
835 Result = AliasAnalysis::alias(Location(UA), Location(UB));
836 // We can't use MustAlias or PartialAlias results here because
837 // GetUnderlyingObjCPtr may return an offsetted pointer value.
838 if (Result == NoAlias)
842 // If that failed, fail. We don't need to chain here, since that's covered
843 // by the earlier precise query.
848 ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
851 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
853 // First, strip off no-ops, including ObjC-specific no-ops, and try making
854 // a precise alias query.
855 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
856 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
860 // If that failed, climb to the underlying object, including climbing through
861 // ObjC-specific no-ops, and try making an imprecise alias query.
862 const Value *U = GetUnderlyingObjCPtr(S);
864 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
866 // If that failed, fail. We don't need to chain here, since that's covered
867 // by the earlier precise query.
871 AliasAnalysis::ModRefBehavior
872 ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
873 // We have nothing to do. Just chain to the next AliasAnalysis.
874 return AliasAnalysis::getModRefBehavior(CS);
877 AliasAnalysis::ModRefBehavior
878 ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
880 return AliasAnalysis::getModRefBehavior(F);
882 switch (GetFunctionClass(F)) {
884 return DoesNotAccessMemory;
889 return AliasAnalysis::getModRefBehavior(F);
892 AliasAnalysis::ModRefResult
893 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
895 return AliasAnalysis::getModRefInfo(CS, Loc);
897 switch (GetBasicInstructionClass(CS.getInstruction())) {
901 case IC_AutoreleaseRV:
903 case IC_AutoreleasepoolPush:
904 case IC_FusedRetainAutorelease:
905 case IC_FusedRetainAutoreleaseRV:
906 // These functions don't access any memory visible to the compiler.
907 // Note that this doesn't include objc_retainBlock, because it updates
908 // pointers when it copies block data.
914 return AliasAnalysis::getModRefInfo(CS, Loc);
917 AliasAnalysis::ModRefResult
918 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
919 ImmutableCallSite CS2) {
920 // TODO: Theoretically we could check for dependencies between objc_* calls
921 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
922 return AliasAnalysis::getModRefInfo(CS1, CS2);
927 /// \defgroup ARCExpansion Early ARC Optimizations.
930 #include "llvm/Support/InstIterator.h"
931 #include "llvm/Transforms/Scalar.h"
934 /// \brief Early ARC transformations.
935 class ObjCARCExpand : public FunctionPass {
936 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
937 virtual bool doInitialization(Module &M);
938 virtual bool runOnFunction(Function &F);
940 /// A flag indicating whether this optimization pass should run.
945 ObjCARCExpand() : FunctionPass(ID) {
946 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
951 char ObjCARCExpand::ID = 0;
952 INITIALIZE_PASS(ObjCARCExpand,
953 "objc-arc-expand", "ObjC ARC expansion", false, false)
955 Pass *llvm::createObjCARCExpandPass() {
956 return new ObjCARCExpand();
959 void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
960 AU.setPreservesCFG();
963 bool ObjCARCExpand::doInitialization(Module &M) {
964 Run = ModuleHasARC(M);
968 bool ObjCARCExpand::runOnFunction(Function &F) {
972 // If nothing in the Module uses ARC, don't do anything.
976 bool Changed = false;
978 DEBUG(dbgs() << "ObjCARCExpand: Visiting Function: " << F.getName() << "\n");
980 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
981 Instruction *Inst = &*I;
983 DEBUG(dbgs() << "ObjCARCExpand: Visiting: " << *Inst << "\n");
985 switch (GetBasicInstructionClass(Inst)) {
989 case IC_AutoreleaseRV:
990 case IC_FusedRetainAutorelease:
991 case IC_FusedRetainAutoreleaseRV: {
992 // These calls return their argument verbatim, as a low-level
993 // optimization. However, this makes high-level optimizations
994 // harder. Undo any uses of this optimization that the front-end
995 // emitted here. We'll redo them in the contract pass.
997 Value *Value = cast<CallInst>(Inst)->getArgOperand(0);
998 DEBUG(dbgs() << "ObjCARCExpand: Old = " << *Inst << "\n"
999 " New = " << *Value << "\n");
1000 Inst->replaceAllUsesWith(Value);
1008 DEBUG(dbgs() << "ObjCARCExpand: Finished List.\n\n");
1015 /// \defgroup ARCAPElim ARC Autorelease Pool Elimination.
1018 #include "llvm/ADT/STLExtras.h"
1019 #include "llvm/IR/Constants.h"
1022 /// \brief Autorelease pool elimination.
1023 class ObjCARCAPElim : public ModulePass {
1024 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1025 virtual bool runOnModule(Module &M);
1027 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
1028 static bool OptimizeBB(BasicBlock *BB);
1032 ObjCARCAPElim() : ModulePass(ID) {
1033 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
1038 char ObjCARCAPElim::ID = 0;
1039 INITIALIZE_PASS(ObjCARCAPElim,
1041 "ObjC ARC autorelease pool elimination",
1044 Pass *llvm::createObjCARCAPElimPass() {
1045 return new ObjCARCAPElim();
1048 void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
1049 AU.setPreservesCFG();
1052 /// Interprocedurally determine if calls made by the given call site can
1053 /// possibly produce autoreleases.
1054 bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
1055 if (const Function *Callee = CS.getCalledFunction()) {
1056 if (Callee->isDeclaration() || Callee->mayBeOverridden())
1058 for (Function::const_iterator I = Callee->begin(), E = Callee->end();
1060 const BasicBlock *BB = I;
1061 for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
1063 if (ImmutableCallSite JCS = ImmutableCallSite(J))
1064 // This recursion depth limit is arbitrary. It's just great
1065 // enough to cover known interesting testcases.
1067 !JCS.onlyReadsMemory() &&
1068 MayAutorelease(JCS, Depth + 1))
1077 bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
1078 bool Changed = false;
1080 Instruction *Push = 0;
1081 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1082 Instruction *Inst = I++;
1083 switch (GetBasicInstructionClass(Inst)) {
1084 case IC_AutoreleasepoolPush:
1087 case IC_AutoreleasepoolPop:
1088 // If this pop matches a push and nothing in between can autorelease,
1090 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
1092 DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop "
1093 "autorelease pair:\n"
1094 " Pop: " << *Inst << "\n"
1095 << " Push: " << *Push << "\n");
1096 Inst->eraseFromParent();
1097 Push->eraseFromParent();
1102 if (MayAutorelease(ImmutableCallSite(Inst)))
1113 bool ObjCARCAPElim::runOnModule(Module &M) {
1117 // If nothing in the Module uses ARC, don't do anything.
1118 if (!ModuleHasARC(M))
1121 // Find the llvm.global_ctors variable, as the first step in
1122 // identifying the global constructors. In theory, unnecessary autorelease
1123 // pools could occur anywhere, but in practice it's pretty rare. Global
1124 // ctors are a place where autorelease pools get inserted automatically,
1125 // so it's pretty common for them to be unnecessary, and it's pretty
1126 // profitable to eliminate them.
1127 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1131 assert(GV->hasDefinitiveInitializer() &&
1132 "llvm.global_ctors is uncooperative!");
1134 bool Changed = false;
1136 // Dig the constructor functions out of GV's initializer.
1137 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1138 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1141 // llvm.global_ctors is an array of pairs where the second members
1142 // are constructor functions.
1143 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1144 // If the user used a constructor function with the wrong signature and
1145 // it got bitcasted or whatever, look the other way.
1148 // Only look at function definitions.
1149 if (F->isDeclaration())
1151 // Only look at functions with one basic block.
1152 if (llvm::next(F->begin()) != F->end())
1154 // Ok, a single-block constructor function definition. Try to optimize it.
1155 Changed |= OptimizeBB(F->begin());
1163 /// \defgroup ARCOpt ARC Optimization.
1166 // TODO: On code like this:
1169 // stuff_that_cannot_release()
1170 // objc_autorelease(%x)
1171 // stuff_that_cannot_release()
1173 // stuff_that_cannot_release()
1174 // objc_autorelease(%x)
1176 // The second retain and autorelease can be deleted.
1178 // TODO: It should be possible to delete
1179 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
1180 // pairs if nothing is actually autoreleased between them. Also, autorelease
1181 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1182 // after inlining) can be turned into plain release calls.
1184 // TODO: Critical-edge splitting. If the optimial insertion point is
1185 // a critical edge, the current algorithm has to fail, because it doesn't
1186 // know how to split edges. It should be possible to make the optimizer
1187 // think in terms of edges, rather than blocks, and then split critical
1190 // TODO: OptimizeSequences could generalized to be Interprocedural.
1192 // TODO: Recognize that a bunch of other objc runtime calls have
1193 // non-escaping arguments and non-releasing arguments, and may be
1194 // non-autoreleasing.
1196 // TODO: Sink autorelease calls as far as possible. Unfortunately we
1197 // usually can't sink them past other calls, which would be the main
1198 // case where it would be useful.
1200 // TODO: The pointer returned from objc_loadWeakRetained is retained.
1202 // TODO: Delete release+retain pairs (rare).
1204 #include "llvm/ADT/SmallPtrSet.h"
1205 #include "llvm/ADT/Statistic.h"
1206 #include "llvm/IR/LLVMContext.h"
1207 #include "llvm/Support/CFG.h"
1209 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1210 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1211 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1212 STATISTIC(NumRets, "Number of return value forwarding "
1213 "retain+autoreleaes eliminated");
1214 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1215 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1218 /// \brief This is similar to BasicAliasAnalysis, and it uses many of the same
1219 /// techniques, except it uses special ObjC-specific reasoning about pointer
1221 class ProvenanceAnalysis {
1224 typedef std::pair<const Value *, const Value *> ValuePairTy;
1225 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1226 CachedResultsTy CachedResults;
1228 bool relatedCheck(const Value *A, const Value *B);
1229 bool relatedSelect(const SelectInst *A, const Value *B);
1230 bool relatedPHI(const PHINode *A, const Value *B);
1232 void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1233 ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1236 ProvenanceAnalysis() {}
1238 void setAA(AliasAnalysis *aa) { AA = aa; }
1240 AliasAnalysis *getAA() const { return AA; }
1242 bool related(const Value *A, const Value *B);
1245 CachedResults.clear();
1250 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1251 // If the values are Selects with the same condition, we can do a more precise
1252 // check: just check for relations between the values on corresponding arms.
1253 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
1254 if (A->getCondition() == SB->getCondition())
1255 return related(A->getTrueValue(), SB->getTrueValue()) ||
1256 related(A->getFalseValue(), SB->getFalseValue());
1258 // Check both arms of the Select node individually.
1259 return related(A->getTrueValue(), B) ||
1260 related(A->getFalseValue(), B);
1263 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1264 // If the values are PHIs in the same block, we can do a more precise as well
1265 // as efficient check: just check for relations between the values on
1266 // corresponding edges.
1267 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1268 if (PNB->getParent() == A->getParent()) {
1269 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1270 if (related(A->getIncomingValue(i),
1271 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1276 // Check each unique source of the PHI node against B.
1277 SmallPtrSet<const Value *, 4> UniqueSrc;
1278 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1279 const Value *PV1 = A->getIncomingValue(i);
1280 if (UniqueSrc.insert(PV1) && related(PV1, B))
1284 // All of the arms checked out.
1288 /// Test if the value of P, or any value covered by its provenance, is ever
1289 /// stored within the function (not counting callees).
1290 static bool isStoredObjCPointer(const Value *P) {
1291 SmallPtrSet<const Value *, 8> Visited;
1292 SmallVector<const Value *, 8> Worklist;
1293 Worklist.push_back(P);
1296 P = Worklist.pop_back_val();
1297 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1299 const User *Ur = *UI;
1300 if (isa<StoreInst>(Ur)) {
1301 if (UI.getOperandNo() == 0)
1302 // The pointer is stored.
1304 // The pointed is stored through.
1307 if (isa<CallInst>(Ur))
1308 // The pointer is passed as an argument, ignore this.
1310 if (isa<PtrToIntInst>(P))
1311 // Assume the worst.
1313 if (Visited.insert(Ur))
1314 Worklist.push_back(Ur);
1316 } while (!Worklist.empty());
1318 // Everything checked out.
1322 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1323 // Skip past provenance pass-throughs.
1324 A = GetUnderlyingObjCPtr(A);
1325 B = GetUnderlyingObjCPtr(B);
1331 // Ask regular AliasAnalysis, for a first approximation.
1332 switch (AA->alias(A, B)) {
1333 case AliasAnalysis::NoAlias:
1335 case AliasAnalysis::MustAlias:
1336 case AliasAnalysis::PartialAlias:
1338 case AliasAnalysis::MayAlias:
1342 bool AIsIdentified = IsObjCIdentifiedObject(A);
1343 bool BIsIdentified = IsObjCIdentifiedObject(B);
1345 // An ObjC-Identified object can't alias a load if it is never locally stored.
1346 if (AIsIdentified) {
1347 // Check for an obvious escape.
1348 if (isa<LoadInst>(B))
1349 return isStoredObjCPointer(A);
1350 if (BIsIdentified) {
1351 // Check for an obvious escape.
1352 if (isa<LoadInst>(A))
1353 return isStoredObjCPointer(B);
1354 // Both pointers are identified and escapes aren't an evident problem.
1357 } else if (BIsIdentified) {
1358 // Check for an obvious escape.
1359 if (isa<LoadInst>(A))
1360 return isStoredObjCPointer(B);
1363 // Special handling for PHI and Select.
1364 if (const PHINode *PN = dyn_cast<PHINode>(A))
1365 return relatedPHI(PN, B);
1366 if (const PHINode *PN = dyn_cast<PHINode>(B))
1367 return relatedPHI(PN, A);
1368 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1369 return relatedSelect(S, B);
1370 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1371 return relatedSelect(S, A);
1377 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1378 // Begin by inserting a conservative value into the map. If the insertion
1379 // fails, we have the answer already. If it succeeds, leave it there until we
1380 // compute the real answer to guard against recursive queries.
1381 if (A > B) std::swap(A, B);
1382 std::pair<CachedResultsTy::iterator, bool> Pair =
1383 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1385 return Pair.first->second;
1387 bool Result = relatedCheck(A, B);
1388 CachedResults[ValuePairTy(A, B)] = Result;
1395 /// \brief A sequence of states that a pointer may go through in which an
1396 /// objc_retain and objc_release are actually needed.
1399 S_Retain, ///< objc_retain(x)
1400 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1401 S_Use, ///< any use of x
1402 S_Stop, ///< like S_Release, but code motion is stopped
1403 S_Release, ///< objc_release(x)
1404 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1408 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1412 if (A == S_None || B == S_None)
1415 if (A > B) std::swap(A, B);
1417 // Choose the side which is further along in the sequence.
1418 if ((A == S_Retain || A == S_CanRelease) &&
1419 (B == S_CanRelease || B == S_Use))
1422 // Choose the side which is further along in the sequence.
1423 if ((A == S_Use || A == S_CanRelease) &&
1424 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
1426 // If both sides are releases, choose the more conservative one.
1427 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1429 if (A == S_Release && B == S_MovableRelease)
1437 /// \brief Unidirectional information about either a
1438 /// retain-decrement-use-release sequence or release-use-decrement-retain
1439 /// reverese sequence.
1441 /// After an objc_retain, the reference count of the referenced
1442 /// object is known to be positive. Similarly, before an objc_release, the
1443 /// reference count of the referenced object is known to be positive. If
1444 /// there are retain-release pairs in code regions where the retain count
1445 /// is known to be positive, they can be eliminated, regardless of any side
1446 /// effects between them.
1448 /// Also, a retain+release pair nested within another retain+release
1449 /// pair all on the known same pointer value can be eliminated, regardless
1450 /// of any intervening side effects.
1452 /// KnownSafe is true when either of these conditions is satisfied.
1455 /// True if the Calls are objc_retainBlock calls (as opposed to objc_retain
1459 /// True of the objc_release calls are all marked with the "tail" keyword.
1460 bool IsTailCallRelease;
1462 /// If the Calls are objc_release calls and they all have a
1463 /// clang.imprecise_release tag, this is the metadata tag.
1464 MDNode *ReleaseMetadata;
1466 /// For a top-down sequence, the set of objc_retains or
1467 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1468 SmallPtrSet<Instruction *, 2> Calls;
1470 /// The set of optimal insert positions for moving calls in the opposite
1472 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1475 KnownSafe(false), IsRetainBlock(false),
1476 IsTailCallRelease(false),
1477 ReleaseMetadata(0) {}
1483 void RRInfo::clear() {
1485 IsRetainBlock = false;
1486 IsTailCallRelease = false;
1487 ReleaseMetadata = 0;
1489 ReverseInsertPts.clear();
1493 /// \brief This class summarizes several per-pointer runtime properties which
1494 /// are propogated through the flow graph.
1496 /// True if the reference count is known to be incremented.
1497 bool KnownPositiveRefCount;
1499 /// True of we've seen an opportunity for partial RR elimination, such as
1500 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
1503 /// The current position in the sequence.
1507 /// Unidirectional information about the current sequence.
1509 /// TODO: Encapsulate this better.
1512 PtrState() : KnownPositiveRefCount(false), Partial(false),
1515 void SetKnownPositiveRefCount() {
1516 KnownPositiveRefCount = true;
1519 void ClearRefCount() {
1520 KnownPositiveRefCount = false;
1523 bool IsKnownIncremented() const {
1524 return KnownPositiveRefCount;
1527 void SetSeq(Sequence NewSeq) {
1531 Sequence GetSeq() const {
1535 void ClearSequenceProgress() {
1536 ResetSequenceProgress(S_None);
1539 void ResetSequenceProgress(Sequence NewSeq) {
1545 void Merge(const PtrState &Other, bool TopDown);
1550 PtrState::Merge(const PtrState &Other, bool TopDown) {
1551 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1552 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
1554 // We can't merge a plain objc_retain with an objc_retainBlock.
1555 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1558 // If we're not in a sequence (anymore), drop all associated state.
1559 if (Seq == S_None) {
1562 } else if (Partial || Other.Partial) {
1563 // If we're doing a merge on a path that's previously seen a partial
1564 // merge, conservatively drop the sequence, to avoid doing partial
1565 // RR elimination. If the branch predicates for the two merge differ,
1566 // mixing them is unsafe.
1567 ClearSequenceProgress();
1569 // Conservatively merge the ReleaseMetadata information.
1570 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1571 RRI.ReleaseMetadata = 0;
1573 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
1574 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1575 Other.RRI.IsTailCallRelease;
1576 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1578 // Merge the insert point sets. If there are any differences,
1579 // that makes this a partial merge.
1580 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
1581 for (SmallPtrSet<Instruction *, 2>::const_iterator
1582 I = Other.RRI.ReverseInsertPts.begin(),
1583 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1584 Partial |= RRI.ReverseInsertPts.insert(*I);
1589 /// \brief Per-BasicBlock state.
1591 /// The number of unique control paths from the entry which can reach this
1593 unsigned TopDownPathCount;
1595 /// The number of unique control paths to exits from this block.
1596 unsigned BottomUpPathCount;
1598 /// A type for PerPtrTopDown and PerPtrBottomUp.
1599 typedef MapVector<const Value *, PtrState> MapTy;
1601 /// The top-down traversal uses this to record information known about a
1602 /// pointer at the bottom of each block.
1603 MapTy PerPtrTopDown;
1605 /// The bottom-up traversal uses this to record information known about a
1606 /// pointer at the top of each block.
1607 MapTy PerPtrBottomUp;
1609 /// Effective predecessors of the current block ignoring ignorable edges and
1610 /// ignored backedges.
1611 SmallVector<BasicBlock *, 2> Preds;
1612 /// Effective successors of the current block ignoring ignorable edges and
1613 /// ignored backedges.
1614 SmallVector<BasicBlock *, 2> Succs;
1617 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1619 typedef MapTy::iterator ptr_iterator;
1620 typedef MapTy::const_iterator ptr_const_iterator;
1622 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1623 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1624 ptr_const_iterator top_down_ptr_begin() const {
1625 return PerPtrTopDown.begin();
1627 ptr_const_iterator top_down_ptr_end() const {
1628 return PerPtrTopDown.end();
1631 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1632 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1633 ptr_const_iterator bottom_up_ptr_begin() const {
1634 return PerPtrBottomUp.begin();
1636 ptr_const_iterator bottom_up_ptr_end() const {
1637 return PerPtrBottomUp.end();
1640 /// Mark this block as being an entry block, which has one path from the
1641 /// entry by definition.
1642 void SetAsEntry() { TopDownPathCount = 1; }
1644 /// Mark this block as being an exit block, which has one path to an exit by
1646 void SetAsExit() { BottomUpPathCount = 1; }
1648 PtrState &getPtrTopDownState(const Value *Arg) {
1649 return PerPtrTopDown[Arg];
1652 PtrState &getPtrBottomUpState(const Value *Arg) {
1653 return PerPtrBottomUp[Arg];
1656 void clearBottomUpPointers() {
1657 PerPtrBottomUp.clear();
1660 void clearTopDownPointers() {
1661 PerPtrTopDown.clear();
1664 void InitFromPred(const BBState &Other);
1665 void InitFromSucc(const BBState &Other);
1666 void MergePred(const BBState &Other);
1667 void MergeSucc(const BBState &Other);
1669 /// Return the number of possible unique paths from an entry to an exit
1670 /// which pass through this block. This is only valid after both the
1671 /// top-down and bottom-up traversals are complete.
1672 unsigned GetAllPathCount() const {
1673 assert(TopDownPathCount != 0);
1674 assert(BottomUpPathCount != 0);
1675 return TopDownPathCount * BottomUpPathCount;
1678 // Specialized CFG utilities.
1679 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
1680 edge_iterator pred_begin() { return Preds.begin(); }
1681 edge_iterator pred_end() { return Preds.end(); }
1682 edge_iterator succ_begin() { return Succs.begin(); }
1683 edge_iterator succ_end() { return Succs.end(); }
1685 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1686 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1688 bool isExit() const { return Succs.empty(); }
1692 void BBState::InitFromPred(const BBState &Other) {
1693 PerPtrTopDown = Other.PerPtrTopDown;
1694 TopDownPathCount = Other.TopDownPathCount;
1697 void BBState::InitFromSucc(const BBState &Other) {
1698 PerPtrBottomUp = Other.PerPtrBottomUp;
1699 BottomUpPathCount = Other.BottomUpPathCount;
1702 /// The top-down traversal uses this to merge information about predecessors to
1703 /// form the initial state for a new block.
1704 void BBState::MergePred(const BBState &Other) {
1705 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1706 // loop backedge. Loop backedges are special.
1707 TopDownPathCount += Other.TopDownPathCount;
1709 // Check for overflow. If we have overflow, fall back to conservative
1711 if (TopDownPathCount < Other.TopDownPathCount) {
1712 clearTopDownPointers();
1716 // For each entry in the other set, if our set has an entry with the same key,
1717 // merge the entries. Otherwise, copy the entry and merge it with an empty
1719 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1720 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1721 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1722 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1726 // For each entry in our set, if the other set doesn't have an entry with the
1727 // same key, force it to merge with an empty entry.
1728 for (ptr_iterator MI = top_down_ptr_begin(),
1729 ME = top_down_ptr_end(); MI != ME; ++MI)
1730 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1731 MI->second.Merge(PtrState(), /*TopDown=*/true);
1734 /// The bottom-up traversal uses this to merge information about successors to
1735 /// form the initial state for a new block.
1736 void BBState::MergeSucc(const BBState &Other) {
1737 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1738 // loop backedge. Loop backedges are special.
1739 BottomUpPathCount += Other.BottomUpPathCount;
1741 // Check for overflow. If we have overflow, fall back to conservative
1743 if (BottomUpPathCount < Other.BottomUpPathCount) {
1744 clearBottomUpPointers();
1748 // For each entry in the other set, if our set has an entry with the
1749 // same key, merge the entries. Otherwise, copy the entry and merge
1750 // it with an empty entry.
1751 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1752 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1753 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1754 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1758 // For each entry in our set, if the other set doesn't have an entry
1759 // with the same key, force it to merge with an empty entry.
1760 for (ptr_iterator MI = bottom_up_ptr_begin(),
1761 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1762 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1763 MI->second.Merge(PtrState(), /*TopDown=*/false);
1767 /// \brief The main ARC optimization pass.
1768 class ObjCARCOpt : public FunctionPass {
1770 ProvenanceAnalysis PA;
1772 /// A flag indicating whether this optimization pass should run.
1775 /// Declarations for ObjC runtime functions, for use in creating calls to
1776 /// them. These are initialized lazily to avoid cluttering up the Module
1777 /// with unused declarations.
1779 /// Declaration for ObjC runtime function
1780 /// objc_retainAutoreleasedReturnValue.
1781 Constant *RetainRVCallee;
1782 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1783 Constant *AutoreleaseRVCallee;
1784 /// Declaration for ObjC runtime function objc_release.
1785 Constant *ReleaseCallee;
1786 /// Declaration for ObjC runtime function objc_retain.
1787 Constant *RetainCallee;
1788 /// Declaration for ObjC runtime function objc_retainBlock.
1789 Constant *RetainBlockCallee;
1790 /// Declaration for ObjC runtime function objc_autorelease.
1791 Constant *AutoreleaseCallee;
1793 /// Flags which determine whether each of the interesting runtine functions
1794 /// is in fact used in the current function.
1795 unsigned UsedInThisFunction;
1797 /// The Metadata Kind for clang.imprecise_release metadata.
1798 unsigned ImpreciseReleaseMDKind;
1800 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
1801 unsigned CopyOnEscapeMDKind;
1803 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
1804 unsigned NoObjCARCExceptionsMDKind;
1806 Constant *getRetainRVCallee(Module *M);
1807 Constant *getAutoreleaseRVCallee(Module *M);
1808 Constant *getReleaseCallee(Module *M);
1809 Constant *getRetainCallee(Module *M);
1810 Constant *getRetainBlockCallee(Module *M);
1811 Constant *getAutoreleaseCallee(Module *M);
1813 bool IsRetainBlockOptimizable(const Instruction *Inst);
1815 void OptimizeRetainCall(Function &F, Instruction *Retain);
1816 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1817 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1818 InstructionClass &Class);
1819 void OptimizeIndividualCalls(Function &F);
1821 void CheckForCFGHazards(const BasicBlock *BB,
1822 DenseMap<const BasicBlock *, BBState> &BBStates,
1823 BBState &MyStates) const;
1824 bool VisitInstructionBottomUp(Instruction *Inst,
1826 MapVector<Value *, RRInfo> &Retains,
1828 bool VisitBottomUp(BasicBlock *BB,
1829 DenseMap<const BasicBlock *, BBState> &BBStates,
1830 MapVector<Value *, RRInfo> &Retains);
1831 bool VisitInstructionTopDown(Instruction *Inst,
1832 DenseMap<Value *, RRInfo> &Releases,
1834 bool VisitTopDown(BasicBlock *BB,
1835 DenseMap<const BasicBlock *, BBState> &BBStates,
1836 DenseMap<Value *, RRInfo> &Releases);
1837 bool Visit(Function &F,
1838 DenseMap<const BasicBlock *, BBState> &BBStates,
1839 MapVector<Value *, RRInfo> &Retains,
1840 DenseMap<Value *, RRInfo> &Releases);
1842 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1843 MapVector<Value *, RRInfo> &Retains,
1844 DenseMap<Value *, RRInfo> &Releases,
1845 SmallVectorImpl<Instruction *> &DeadInsts,
1848 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1849 MapVector<Value *, RRInfo> &Retains,
1850 DenseMap<Value *, RRInfo> &Releases,
1853 void OptimizeWeakCalls(Function &F);
1855 bool OptimizeSequences(Function &F);
1857 void OptimizeReturns(Function &F);
1859 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1860 virtual bool doInitialization(Module &M);
1861 virtual bool runOnFunction(Function &F);
1862 virtual void releaseMemory();
1866 ObjCARCOpt() : FunctionPass(ID) {
1867 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1872 char ObjCARCOpt::ID = 0;
1873 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1874 "objc-arc", "ObjC ARC optimization", false, false)
1875 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1876 INITIALIZE_PASS_END(ObjCARCOpt,
1877 "objc-arc", "ObjC ARC optimization", false, false)
1879 Pass *llvm::createObjCARCOptPass() {
1880 return new ObjCARCOpt();
1883 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1884 AU.addRequired<ObjCARCAliasAnalysis>();
1885 AU.addRequired<AliasAnalysis>();
1886 // ARC optimization doesn't currently split critical edges.
1887 AU.setPreservesCFG();
1890 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1891 // Without the magic metadata tag, we have to assume this might be an
1892 // objc_retainBlock call inserted to convert a block pointer to an id,
1893 // in which case it really is needed.
1894 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1897 // If the pointer "escapes" (not including being used in a call),
1898 // the copy may be needed.
1899 if (DoesObjCBlockEscape(Inst))
1902 // Otherwise, it's not needed.
1906 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1907 if (!RetainRVCallee) {
1908 LLVMContext &C = M->getContext();
1909 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1910 Type *Params[] = { I8X };
1911 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1912 AttributeSet Attribute =
1913 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1914 Attribute::get(C, Attribute::NoUnwind));
1916 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1919 return RetainRVCallee;
1922 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1923 if (!AutoreleaseRVCallee) {
1924 LLVMContext &C = M->getContext();
1925 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1926 Type *Params[] = { I8X };
1927 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1928 AttributeSet Attribute =
1929 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1930 Attribute::get(C, Attribute::NoUnwind));
1931 AutoreleaseRVCallee =
1932 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1935 return AutoreleaseRVCallee;
1938 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1939 if (!ReleaseCallee) {
1940 LLVMContext &C = M->getContext();
1941 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1942 AttributeSet Attribute =
1943 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1944 Attribute::get(C, Attribute::NoUnwind));
1946 M->getOrInsertFunction(
1948 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1951 return ReleaseCallee;
1954 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1955 if (!RetainCallee) {
1956 LLVMContext &C = M->getContext();
1957 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1958 AttributeSet Attribute =
1959 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1960 Attribute::get(C, Attribute::NoUnwind));
1962 M->getOrInsertFunction(
1964 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1967 return RetainCallee;
1970 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1971 if (!RetainBlockCallee) {
1972 LLVMContext &C = M->getContext();
1973 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1974 // objc_retainBlock is not nounwind because it calls user copy constructors
1975 // which could theoretically throw.
1977 M->getOrInsertFunction(
1979 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1982 return RetainBlockCallee;
1985 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1986 if (!AutoreleaseCallee) {
1987 LLVMContext &C = M->getContext();
1988 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1989 AttributeSet Attribute =
1990 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1991 Attribute::get(C, Attribute::NoUnwind));
1993 M->getOrInsertFunction(
1995 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1998 return AutoreleaseCallee;
2001 /// Test whether the given value is possible a reference-counted pointer,
2002 /// including tests which utilize AliasAnalysis.
2003 static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
2004 // First make the rudimentary check.
2005 if (!IsPotentialUse(Op))
2008 // Objects in constant memory are not reference-counted.
2009 if (AA.pointsToConstantMemory(Op))
2012 // Pointers in constant memory are not pointing to reference-counted objects.
2013 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
2014 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
2017 // Otherwise assume the worst.
2021 /// Test whether the given instruction can result in a reference count
2022 /// modification (positive or negative) for the pointer's object.
2024 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
2025 ProvenanceAnalysis &PA, InstructionClass Class) {
2027 case IC_Autorelease:
2028 case IC_AutoreleaseRV:
2030 // These operations never directly modify a reference count.
2035 ImmutableCallSite CS = static_cast<const Value *>(Inst);
2036 assert(CS && "Only calls can alter reference counts!");
2038 // See if AliasAnalysis can help us with the call.
2039 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
2040 if (AliasAnalysis::onlyReadsMemory(MRB))
2042 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
2043 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
2045 const Value *Op = *I;
2046 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
2052 // Assume the worst.
2056 /// Test whether the given instruction can "use" the given pointer's object in a
2057 /// way that requires the reference count to be positive.
2059 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
2060 InstructionClass Class) {
2061 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
2062 if (Class == IC_Call)
2065 // Consider various instructions which may have pointer arguments which are
2067 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
2068 // Comparing a pointer with null, or any other constant, isn't really a use,
2069 // because we don't care what the pointer points to, or about the values
2070 // of any other dynamic reference-counted pointers.
2071 if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
2073 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
2074 // For calls, just check the arguments (and not the callee operand).
2075 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
2076 OE = CS.arg_end(); OI != OE; ++OI) {
2077 const Value *Op = *OI;
2078 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
2082 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
2083 // Special-case stores, because we don't care about the stored value, just
2084 // the store address.
2085 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
2086 // If we can't tell what the underlying object was, assume there is a
2088 return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
2091 // Check each operand for a match.
2092 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
2094 const Value *Op = *OI;
2095 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
2101 /// Test whether the given instruction can autorelease any pointer or cause an
2102 /// autoreleasepool pop.
2104 CanInterruptRV(InstructionClass Class) {
2106 case IC_AutoreleasepoolPop:
2109 case IC_Autorelease:
2110 case IC_AutoreleaseRV:
2111 case IC_FusedRetainAutorelease:
2112 case IC_FusedRetainAutoreleaseRV:
2120 /// \enum DependenceKind
2121 /// \brief Defines different dependence kinds among various ARC constructs.
2123 /// There are several kinds of dependence-like concepts in use here.
2125 enum DependenceKind {
2126 NeedsPositiveRetainCount,
2127 AutoreleasePoolBoundary,
2128 CanChangeRetainCount,
2129 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
2130 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
2131 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
2135 /// Test if there can be dependencies on Inst through Arg. This function only
2136 /// tests dependencies relevant for removing pairs of calls.
2138 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2139 ProvenanceAnalysis &PA) {
2140 // If we've reached the definition of Arg, stop.
2145 case NeedsPositiveRetainCount: {
2146 InstructionClass Class = GetInstructionClass(Inst);
2148 case IC_AutoreleasepoolPop:
2149 case IC_AutoreleasepoolPush:
2153 return CanUse(Inst, Arg, PA, Class);
2157 case AutoreleasePoolBoundary: {
2158 InstructionClass Class = GetInstructionClass(Inst);
2160 case IC_AutoreleasepoolPop:
2161 case IC_AutoreleasepoolPush:
2162 // These mark the end and begin of an autorelease pool scope.
2165 // Nothing else does this.
2170 case CanChangeRetainCount: {
2171 InstructionClass Class = GetInstructionClass(Inst);
2173 case IC_AutoreleasepoolPop:
2174 // Conservatively assume this can decrement any count.
2176 case IC_AutoreleasepoolPush:
2180 return CanAlterRefCount(Inst, Arg, PA, Class);
2184 case RetainAutoreleaseDep:
2185 switch (GetBasicInstructionClass(Inst)) {
2186 case IC_AutoreleasepoolPop:
2187 case IC_AutoreleasepoolPush:
2188 // Don't merge an objc_autorelease with an objc_retain inside a different
2189 // autoreleasepool scope.
2193 // Check for a retain of the same pointer for merging.
2194 return GetObjCArg(Inst) == Arg;
2196 // Nothing else matters for objc_retainAutorelease formation.
2200 case RetainAutoreleaseRVDep: {
2201 InstructionClass Class = GetBasicInstructionClass(Inst);
2205 // Check for a retain of the same pointer for merging.
2206 return GetObjCArg(Inst) == Arg;
2208 // Anything that can autorelease interrupts
2209 // retainAutoreleaseReturnValue formation.
2210 return CanInterruptRV(Class);
2215 return CanInterruptRV(GetBasicInstructionClass(Inst));
2218 llvm_unreachable("Invalid dependence flavor");
2221 /// Walk up the CFG from StartPos (which is in StartBB) and find local and
2222 /// non-local dependencies on Arg.
2224 /// TODO: Cache results?
2226 FindDependencies(DependenceKind Flavor,
2228 BasicBlock *StartBB, Instruction *StartInst,
2229 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2230 SmallPtrSet<const BasicBlock *, 4> &Visited,
2231 ProvenanceAnalysis &PA) {
2232 BasicBlock::iterator StartPos = StartInst;
2234 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2235 Worklist.push_back(std::make_pair(StartBB, StartPos));
2237 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2238 Worklist.pop_back_val();
2239 BasicBlock *LocalStartBB = Pair.first;
2240 BasicBlock::iterator LocalStartPos = Pair.second;
2241 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2243 if (LocalStartPos == StartBBBegin) {
2244 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2246 // If we've reached the function entry, produce a null dependence.
2247 DependingInstructions.insert(0);
2249 // Add the predecessors to the worklist.
2251 BasicBlock *PredBB = *PI;
2252 if (Visited.insert(PredBB))
2253 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2254 } while (++PI != PE);
2258 Instruction *Inst = --LocalStartPos;
2259 if (Depends(Flavor, Inst, Arg, PA)) {
2260 DependingInstructions.insert(Inst);
2264 } while (!Worklist.empty());
2266 // Determine whether the original StartBB post-dominates all of the blocks we
2267 // visited. If not, insert a sentinal indicating that most optimizations are
2269 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2270 E = Visited.end(); I != E; ++I) {
2271 const BasicBlock *BB = *I;
2274 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2275 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2276 const BasicBlock *Succ = *SI;
2277 if (Succ != StartBB && !Visited.count(Succ)) {
2278 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2285 static bool isNullOrUndef(const Value *V) {
2286 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2289 static bool isNoopInstruction(const Instruction *I) {
2290 return isa<BitCastInst>(I) ||
2291 (isa<GetElementPtrInst>(I) &&
2292 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2295 /// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
2298 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
2299 ImmutableCallSite CS(GetObjCArg(Retain));
2300 const Instruction *Call = CS.getInstruction();
2302 if (Call->getParent() != Retain->getParent()) return;
2304 // Check that the call is next to the retain.
2305 BasicBlock::const_iterator I = Call;
2307 while (isNoopInstruction(I)) ++I;
2311 // Turn it to an objc_retainAutoreleasedReturnValue..
2315 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
2316 "objc_retain => objc_retainAutoreleasedReturnValue"
2317 " since the operand is a return value.\n"
2319 << *Retain << "\n");
2321 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2323 DEBUG(dbgs() << " New: "
2324 << *Retain << "\n");
2327 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
2328 /// not a return value. Or, if it can be paired with an
2329 /// objc_autoreleaseReturnValue, delete the pair and return true.
2331 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
2332 // Check for the argument being from an immediately preceding call or invoke.
2333 const Value *Arg = GetObjCArg(RetainRV);
2334 ImmutableCallSite CS(Arg);
2335 if (const Instruction *Call = CS.getInstruction()) {
2336 if (Call->getParent() == RetainRV->getParent()) {
2337 BasicBlock::const_iterator I = Call;
2339 while (isNoopInstruction(I)) ++I;
2340 if (&*I == RetainRV)
2342 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
2343 BasicBlock *RetainRVParent = RetainRV->getParent();
2344 if (II->getNormalDest() == RetainRVParent) {
2345 BasicBlock::const_iterator I = RetainRVParent->begin();
2346 while (isNoopInstruction(I)) ++I;
2347 if (&*I == RetainRV)
2353 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2354 // pointer. In this case, we can delete the pair.
2355 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2357 do --I; while (I != Begin && isNoopInstruction(I));
2358 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2359 GetObjCArg(I) == Arg) {
2363 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
2364 << " Erasing " << *RetainRV
2367 EraseInstruction(I);
2368 EraseInstruction(RetainRV);
2373 // Turn it to a plain objc_retain.
2377 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
2378 "objc_retainAutoreleasedReturnValue => "
2379 "objc_retain since the operand is not a return value.\n"
2381 << *RetainRV << "\n");
2383 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2385 DEBUG(dbgs() << " New: "
2386 << *RetainRV << "\n");
2391 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
2392 /// used as a return value.
2394 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
2395 InstructionClass &Class) {
2396 // Check for a return of the pointer value.
2397 const Value *Ptr = GetObjCArg(AutoreleaseRV);
2398 SmallVector<const Value *, 2> Users;
2399 Users.push_back(Ptr);
2401 Ptr = Users.pop_back_val();
2402 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2404 const User *I = *UI;
2405 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2407 if (isa<BitCastInst>(I))
2410 } while (!Users.empty());
2415 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
2416 "objc_autoreleaseReturnValue => "
2417 "objc_autorelease since its operand is not used as a return "
2420 << *AutoreleaseRV << "\n");
2422 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
2424 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2425 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
2426 Class = IC_Autorelease;
2428 DEBUG(dbgs() << " New: "
2429 << *AutoreleaseRV << "\n");
2433 /// Visit each call, one at a time, and make simplifications without doing any
2434 /// additional analysis.
2435 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2436 // Reset all the flags in preparation for recomputing them.
2437 UsedInThisFunction = 0;
2439 // Visit all objc_* calls in F.
2440 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2441 Instruction *Inst = &*I++;
2443 InstructionClass Class = GetBasicInstructionClass(Inst);
2445 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: Class: "
2446 << Class << "; " << *Inst << "\n");
2451 // Delete no-op casts. These function calls have special semantics, but
2452 // the semantics are entirely implemented via lowering in the front-end,
2453 // so by the time they reach the optimizer, they are just no-op calls
2454 // which return their argument.
2456 // There are gray areas here, as the ability to cast reference-counted
2457 // pointers to raw void* and back allows code to break ARC assumptions,
2458 // however these are currently considered to be unimportant.
2462 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
2463 " " << *Inst << "\n");
2464 EraseInstruction(Inst);
2467 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2470 case IC_LoadWeakRetained:
2472 case IC_DestroyWeak: {
2473 CallInst *CI = cast<CallInst>(Inst);
2474 if (isNullOrUndef(CI->getArgOperand(0))) {
2476 Type *Ty = CI->getArgOperand(0)->getType();
2477 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2478 Constant::getNullValue(Ty),
2480 llvm::Value *NewValue = UndefValue::get(CI->getType());
2481 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2482 "pointer-to-weak-pointer is undefined behavior.\n"
2486 CI->replaceAllUsesWith(NewValue);
2487 CI->eraseFromParent();
2494 CallInst *CI = cast<CallInst>(Inst);
2495 if (isNullOrUndef(CI->getArgOperand(0)) ||
2496 isNullOrUndef(CI->getArgOperand(1))) {
2498 Type *Ty = CI->getArgOperand(0)->getType();
2499 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2500 Constant::getNullValue(Ty),
2503 llvm::Value *NewValue = UndefValue::get(CI->getType());
2504 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2505 "pointer-to-weak-pointer is undefined behavior.\n"
2510 CI->replaceAllUsesWith(NewValue);
2511 CI->eraseFromParent();
2517 OptimizeRetainCall(F, Inst);
2520 if (OptimizeRetainRVCall(F, Inst))
2523 case IC_AutoreleaseRV:
2524 OptimizeAutoreleaseRVCall(F, Inst, Class);
2528 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2529 if (IsAutorelease(Class) && Inst->use_empty()) {
2530 CallInst *Call = cast<CallInst>(Inst);
2531 const Value *Arg = Call->getArgOperand(0);
2532 Arg = FindSingleUseIdentifiedObject(Arg);
2537 // Create the declaration lazily.
2538 LLVMContext &C = Inst->getContext();
2540 CallInst::Create(getReleaseCallee(F.getParent()),
2541 Call->getArgOperand(0), "", Call);
2542 NewCall->setMetadata(ImpreciseReleaseMDKind,
2543 MDNode::get(C, ArrayRef<Value *>()));
2545 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
2546 "objc_autorelease(x) with objc_release(x) since x is "
2547 "otherwise unused.\n"
2548 " Old: " << *Call <<
2552 EraseInstruction(Call);
2558 // For functions which can never be passed stack arguments, add
2560 if (IsAlwaysTail(Class)) {
2562 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
2563 " to function since it can never be passed stack args: " << *Inst <<
2565 cast<CallInst>(Inst)->setTailCall();
2568 // Ensure that functions that can never have a "tail" keyword due to the
2569 // semantics of ARC truly do not do so.
2570 if (IsNeverTail(Class)) {
2572 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail "
2573 "keyword from function: " << *Inst <<
2575 cast<CallInst>(Inst)->setTailCall(false);
2578 // Set nounwind as needed.
2579 if (IsNoThrow(Class)) {
2581 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
2582 " class. Setting nounwind on: " << *Inst << "\n");
2583 cast<CallInst>(Inst)->setDoesNotThrow();
2586 if (!IsNoopOnNull(Class)) {
2587 UsedInThisFunction |= 1 << Class;
2591 const Value *Arg = GetObjCArg(Inst);
2593 // ARC calls with null are no-ops. Delete them.
2594 if (isNullOrUndef(Arg)) {
2597 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
2598 " null are no-ops. Erasing: " << *Inst << "\n");
2599 EraseInstruction(Inst);
2603 // Keep track of which of retain, release, autorelease, and retain_block
2604 // are actually present in this function.
2605 UsedInThisFunction |= 1 << Class;
2607 // If Arg is a PHI, and one or more incoming values to the
2608 // PHI are null, and the call is control-equivalent to the PHI, and there
2609 // are no relevant side effects between the PHI and the call, the call
2610 // could be pushed up to just those paths with non-null incoming values.
2611 // For now, don't bother splitting critical edges for this.
2612 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2613 Worklist.push_back(std::make_pair(Inst, Arg));
2615 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2619 const PHINode *PN = dyn_cast<PHINode>(Arg);
2622 // Determine if the PHI has any null operands, or any incoming
2624 bool HasNull = false;
2625 bool HasCriticalEdges = false;
2626 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2628 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2629 if (isNullOrUndef(Incoming))
2631 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2632 .getNumSuccessors() != 1) {
2633 HasCriticalEdges = true;
2637 // If we have null operands and no critical edges, optimize.
2638 if (!HasCriticalEdges && HasNull) {
2639 SmallPtrSet<Instruction *, 4> DependingInstructions;
2640 SmallPtrSet<const BasicBlock *, 4> Visited;
2642 // Check that there is nothing that cares about the reference
2643 // count between the call and the phi.
2646 case IC_RetainBlock:
2647 // These can always be moved up.
2650 // These can't be moved across things that care about the retain
2652 FindDependencies(NeedsPositiveRetainCount, Arg,
2653 Inst->getParent(), Inst,
2654 DependingInstructions, Visited, PA);
2656 case IC_Autorelease:
2657 // These can't be moved across autorelease pool scope boundaries.
2658 FindDependencies(AutoreleasePoolBoundary, Arg,
2659 Inst->getParent(), Inst,
2660 DependingInstructions, Visited, PA);
2663 case IC_AutoreleaseRV:
2664 // Don't move these; the RV optimization depends on the autoreleaseRV
2665 // being tail called, and the retainRV being immediately after a call
2666 // (which might still happen if we get lucky with codegen layout, but
2667 // it's not worth taking the chance).
2670 llvm_unreachable("Invalid dependence flavor");
2673 if (DependingInstructions.size() == 1 &&
2674 *DependingInstructions.begin() == PN) {
2677 // Clone the call into each predecessor that has a non-null value.
2678 CallInst *CInst = cast<CallInst>(Inst);
2679 Type *ParamTy = CInst->getArgOperand(0)->getType();
2680 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2682 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2683 if (!isNullOrUndef(Incoming)) {
2684 CallInst *Clone = cast<CallInst>(CInst->clone());
2685 Value *Op = PN->getIncomingValue(i);
2686 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2687 if (Op->getType() != ParamTy)
2688 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2689 Clone->setArgOperand(0, Op);
2690 Clone->insertBefore(InsertPos);
2692 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
2695 "clone at " << *InsertPos << "\n");
2696 Worklist.push_back(std::make_pair(Clone, Incoming));
2699 // Erase the original call.
2700 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
2701 EraseInstruction(CInst);
2705 } while (!Worklist.empty());
2707 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
2710 /// Check for critical edges, loop boundaries, irreducible control flow, or
2711 /// other CFG structures where moving code across the edge would result in it
2712 /// being executed more.
2714 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2715 DenseMap<const BasicBlock *, BBState> &BBStates,
2716 BBState &MyStates) const {
2717 // If any top-down local-use or possible-dec has a succ which is earlier in
2718 // the sequence, forget it.
2719 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
2720 E = MyStates.top_down_ptr_end(); I != E; ++I)
2721 switch (I->second.GetSeq()) {
2724 const Value *Arg = I->first;
2725 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2726 bool SomeSuccHasSame = false;
2727 bool AllSuccsHaveSame = true;
2728 PtrState &S = I->second;
2729 succ_const_iterator SI(TI), SE(TI, false);
2731 for (; SI != SE; ++SI) {
2732 Sequence SuccSSeq = S_None;
2733 bool SuccSRRIKnownSafe = false;
2734 // If VisitBottomUp has pointer information for this successor, take
2735 // what we know about it.
2736 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2738 assert(BBI != BBStates.end());
2739 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2740 SuccSSeq = SuccS.GetSeq();
2741 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2744 case S_CanRelease: {
2745 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2746 S.ClearSequenceProgress();
2752 SomeSuccHasSame = true;
2756 case S_MovableRelease:
2757 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2758 AllSuccsHaveSame = false;
2761 llvm_unreachable("bottom-up pointer in retain state!");
2764 // If the state at the other end of any of the successor edges
2765 // matches the current state, require all edges to match. This
2766 // guards against loops in the middle of a sequence.
2767 if (SomeSuccHasSame && !AllSuccsHaveSame)
2768 S.ClearSequenceProgress();
2771 case S_CanRelease: {
2772 const Value *Arg = I->first;
2773 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2774 bool SomeSuccHasSame = false;
2775 bool AllSuccsHaveSame = true;
2776 PtrState &S = I->second;
2777 succ_const_iterator SI(TI), SE(TI, false);
2779 for (; SI != SE; ++SI) {
2780 Sequence SuccSSeq = S_None;
2781 bool SuccSRRIKnownSafe = false;
2782 // If VisitBottomUp has pointer information for this successor, take
2783 // what we know about it.
2784 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2786 assert(BBI != BBStates.end());
2787 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2788 SuccSSeq = SuccS.GetSeq();
2789 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2792 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2793 S.ClearSequenceProgress();
2799 SomeSuccHasSame = true;
2803 case S_MovableRelease:
2805 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2806 AllSuccsHaveSame = false;
2809 llvm_unreachable("bottom-up pointer in retain state!");
2812 // If the state at the other end of any of the successor edges
2813 // matches the current state, require all edges to match. This
2814 // guards against loops in the middle of a sequence.
2815 if (SomeSuccHasSame && !AllSuccsHaveSame)
2816 S.ClearSequenceProgress();
2823 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
2825 MapVector<Value *, RRInfo> &Retains,
2826 BBState &MyStates) {
2827 bool NestingDetected = false;
2828 InstructionClass Class = GetInstructionClass(Inst);
2829 const Value *Arg = 0;
2833 Arg = GetObjCArg(Inst);
2835 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2837 // If we see two releases in a row on the same pointer. If so, make
2838 // a note, and we'll cicle back to revisit it after we've
2839 // hopefully eliminated the second release, which may allow us to
2840 // eliminate the first release too.
2841 // Theoretically we could implement removal of nested retain+release
2842 // pairs by making PtrState hold a stack of states, but this is
2843 // simple and avoids adding overhead for the non-nested case.
2844 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
2845 DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested "
2846 "releases (i.e. a release pair)\n");
2847 NestingDetected = true;
2850 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2851 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
2852 S.RRI.ReleaseMetadata = ReleaseMetadata;
2853 S.RRI.KnownSafe = S.IsKnownIncremented();
2854 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2855 S.RRI.Calls.insert(Inst);
2857 S.SetKnownPositiveRefCount();
2860 case IC_RetainBlock:
2861 // An objc_retainBlock call with just a use may need to be kept,
2862 // because it may be copying a block from the stack to the heap.
2863 if (!IsRetainBlockOptimizable(Inst))
2868 Arg = GetObjCArg(Inst);
2870 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2871 S.SetKnownPositiveRefCount();
2873 switch (S.GetSeq()) {
2876 case S_MovableRelease:
2878 S.RRI.ReverseInsertPts.clear();
2881 // Don't do retain+release tracking for IC_RetainRV, because it's
2882 // better to let it remain as the first instruction after a call.
2883 if (Class != IC_RetainRV) {
2884 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2885 Retains[Inst] = S.RRI;
2887 S.ClearSequenceProgress();
2892 llvm_unreachable("bottom-up pointer in retain state!");
2894 return NestingDetected;
2896 case IC_AutoreleasepoolPop:
2897 // Conservatively, clear MyStates for all known pointers.
2898 MyStates.clearBottomUpPointers();
2899 return NestingDetected;
2900 case IC_AutoreleasepoolPush:
2902 // These are irrelevant.
2903 return NestingDetected;
2908 // Consider any other possible effects of this instruction on each
2909 // pointer being tracked.
2910 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2911 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2912 const Value *Ptr = MI->first;
2914 continue; // Handled above.
2915 PtrState &S = MI->second;
2916 Sequence Seq = S.GetSeq();
2918 // Check for possible releases.
2919 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2923 S.SetSeq(S_CanRelease);
2927 case S_MovableRelease:
2932 llvm_unreachable("bottom-up pointer in retain state!");
2936 // Check for possible direct uses.
2939 case S_MovableRelease:
2940 if (CanUse(Inst, Ptr, PA, Class)) {
2941 assert(S.RRI.ReverseInsertPts.empty());
2942 // If this is an invoke instruction, we're scanning it as part of
2943 // one of its successor blocks, since we can't insert code after it
2944 // in its own block, and we don't want to split critical edges.
2945 if (isa<InvokeInst>(Inst))
2946 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2948 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2950 } else if (Seq == S_Release &&
2951 (Class == IC_User || Class == IC_CallOrUser)) {
2952 // Non-movable releases depend on any possible objc pointer use.
2954 assert(S.RRI.ReverseInsertPts.empty());
2955 // As above; handle invoke specially.
2956 if (isa<InvokeInst>(Inst))
2957 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2959 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2963 if (CanUse(Inst, Ptr, PA, Class))
2971 llvm_unreachable("bottom-up pointer in retain state!");
2975 return NestingDetected;
2979 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2980 DenseMap<const BasicBlock *, BBState> &BBStates,
2981 MapVector<Value *, RRInfo> &Retains) {
2982 bool NestingDetected = false;
2983 BBState &MyStates = BBStates[BB];
2985 // Merge the states from each successor to compute the initial state
2986 // for the current block.
2987 BBState::edge_iterator SI(MyStates.succ_begin()),
2988 SE(MyStates.succ_end());
2990 const BasicBlock *Succ = *SI;
2991 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2992 assert(I != BBStates.end());
2993 MyStates.InitFromSucc(I->second);
2995 for (; SI != SE; ++SI) {
2997 I = BBStates.find(Succ);
2998 assert(I != BBStates.end());
2999 MyStates.MergeSucc(I->second);
3003 // Visit all the instructions, bottom-up.
3004 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
3005 Instruction *Inst = llvm::prior(I);
3007 // Invoke instructions are visited as part of their successors (below).
3008 if (isa<InvokeInst>(Inst))
3011 DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n");
3013 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
3016 // If there's a predecessor with an invoke, visit the invoke as if it were
3017 // part of this block, since we can't insert code after an invoke in its own
3018 // block, and we don't want to split critical edges.
3019 for (BBState::edge_iterator PI(MyStates.pred_begin()),
3020 PE(MyStates.pred_end()); PI != PE; ++PI) {
3021 BasicBlock *Pred = *PI;
3022 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
3023 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
3026 return NestingDetected;
3030 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
3031 DenseMap<Value *, RRInfo> &Releases,
3032 BBState &MyStates) {
3033 bool NestingDetected = false;
3034 InstructionClass Class = GetInstructionClass(Inst);
3035 const Value *Arg = 0;
3038 case IC_RetainBlock:
3039 // An objc_retainBlock call with just a use may need to be kept,
3040 // because it may be copying a block from the stack to the heap.
3041 if (!IsRetainBlockOptimizable(Inst))
3046 Arg = GetObjCArg(Inst);
3048 PtrState &S = MyStates.getPtrTopDownState(Arg);
3050 // Don't do retain+release tracking for IC_RetainRV, because it's
3051 // better to let it remain as the first instruction after a call.
3052 if (Class != IC_RetainRV) {
3053 // If we see two retains in a row on the same pointer. If so, make
3054 // a note, and we'll cicle back to revisit it after we've
3055 // hopefully eliminated the second retain, which may allow us to
3056 // eliminate the first retain too.
3057 // Theoretically we could implement removal of nested retain+release
3058 // pairs by making PtrState hold a stack of states, but this is
3059 // simple and avoids adding overhead for the non-nested case.
3060 if (S.GetSeq() == S_Retain)
3061 NestingDetected = true;
3063 S.ResetSequenceProgress(S_Retain);
3064 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
3065 S.RRI.KnownSafe = S.IsKnownIncremented();
3066 S.RRI.Calls.insert(Inst);
3069 S.SetKnownPositiveRefCount();
3071 // A retain can be a potential use; procede to the generic checking
3076 Arg = GetObjCArg(Inst);
3078 PtrState &S = MyStates.getPtrTopDownState(Arg);
3081 switch (S.GetSeq()) {
3084 S.RRI.ReverseInsertPts.clear();
3087 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
3088 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
3089 Releases[Inst] = S.RRI;
3090 S.ClearSequenceProgress();
3096 case S_MovableRelease:
3097 llvm_unreachable("top-down pointer in release state!");
3101 case IC_AutoreleasepoolPop:
3102 // Conservatively, clear MyStates for all known pointers.
3103 MyStates.clearTopDownPointers();
3104 return NestingDetected;
3105 case IC_AutoreleasepoolPush:
3107 // These are irrelevant.
3108 return NestingDetected;
3113 // Consider any other possible effects of this instruction on each
3114 // pointer being tracked.
3115 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
3116 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
3117 const Value *Ptr = MI->first;
3119 continue; // Handled above.
3120 PtrState &S = MI->second;
3121 Sequence Seq = S.GetSeq();
3123 // Check for possible releases.
3124 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
3128 S.SetSeq(S_CanRelease);
3129 assert(S.RRI.ReverseInsertPts.empty());
3130 S.RRI.ReverseInsertPts.insert(Inst);
3132 // One call can't cause a transition from S_Retain to S_CanRelease
3133 // and S_CanRelease to S_Use. If we've made the first transition,
3142 case S_MovableRelease:
3143 llvm_unreachable("top-down pointer in release state!");
3147 // Check for possible direct uses.
3150 if (CanUse(Inst, Ptr, PA, Class))
3159 case S_MovableRelease:
3160 llvm_unreachable("top-down pointer in release state!");
3164 return NestingDetected;
3168 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
3169 DenseMap<const BasicBlock *, BBState> &BBStates,
3170 DenseMap<Value *, RRInfo> &Releases) {
3171 bool NestingDetected = false;
3172 BBState &MyStates = BBStates[BB];
3174 // Merge the states from each predecessor to compute the initial state
3175 // for the current block.
3176 BBState::edge_iterator PI(MyStates.pred_begin()),
3177 PE(MyStates.pred_end());
3179 const BasicBlock *Pred = *PI;
3180 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
3181 assert(I != BBStates.end());
3182 MyStates.InitFromPred(I->second);
3184 for (; PI != PE; ++PI) {
3186 I = BBStates.find(Pred);
3187 assert(I != BBStates.end());
3188 MyStates.MergePred(I->second);
3192 // Visit all the instructions, top-down.
3193 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3194 Instruction *Inst = I;
3196 DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n");
3198 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
3201 CheckForCFGHazards(BB, BBStates, MyStates);
3202 return NestingDetected;
3206 ComputePostOrders(Function &F,
3207 SmallVectorImpl<BasicBlock *> &PostOrder,
3208 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
3209 unsigned NoObjCARCExceptionsMDKind,
3210 DenseMap<const BasicBlock *, BBState> &BBStates) {
3211 /// The visited set, for doing DFS walks.
3212 SmallPtrSet<BasicBlock *, 16> Visited;
3214 // Do DFS, computing the PostOrder.
3215 SmallPtrSet<BasicBlock *, 16> OnStack;
3216 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
3218 // Functions always have exactly one entry block, and we don't have
3219 // any other block that we treat like an entry block.
3220 BasicBlock *EntryBB = &F.getEntryBlock();
3221 BBState &MyStates = BBStates[EntryBB];
3222 MyStates.SetAsEntry();
3223 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
3224 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
3225 Visited.insert(EntryBB);
3226 OnStack.insert(EntryBB);
3229 BasicBlock *CurrBB = SuccStack.back().first;
3230 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3231 succ_iterator SE(TI, false);
3233 while (SuccStack.back().second != SE) {
3234 BasicBlock *SuccBB = *SuccStack.back().second++;
3235 if (Visited.insert(SuccBB)) {
3236 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3237 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
3238 BBStates[CurrBB].addSucc(SuccBB);
3239 BBState &SuccStates = BBStates[SuccBB];
3240 SuccStates.addPred(CurrBB);
3241 OnStack.insert(SuccBB);
3245 if (!OnStack.count(SuccBB)) {
3246 BBStates[CurrBB].addSucc(SuccBB);
3247 BBStates[SuccBB].addPred(CurrBB);
3250 OnStack.erase(CurrBB);
3251 PostOrder.push_back(CurrBB);
3252 SuccStack.pop_back();
3253 } while (!SuccStack.empty());
3257 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
3258 // Functions may have many exits, and there also blocks which we treat
3259 // as exits due to ignored edges.
3260 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3261 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3262 BasicBlock *ExitBB = I;
3263 BBState &MyStates = BBStates[ExitBB];
3264 if (!MyStates.isExit())
3267 MyStates.SetAsExit();
3269 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
3270 Visited.insert(ExitBB);
3271 while (!PredStack.empty()) {
3272 reverse_dfs_next_succ:
3273 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3274 while (PredStack.back().second != PE) {
3275 BasicBlock *BB = *PredStack.back().second++;
3276 if (Visited.insert(BB)) {
3277 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
3278 goto reverse_dfs_next_succ;
3281 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3286 // Visit the function both top-down and bottom-up.
3288 ObjCARCOpt::Visit(Function &F,
3289 DenseMap<const BasicBlock *, BBState> &BBStates,
3290 MapVector<Value *, RRInfo> &Retains,
3291 DenseMap<Value *, RRInfo> &Releases) {
3293 // Use reverse-postorder traversals, because we magically know that loops
3294 // will be well behaved, i.e. they won't repeatedly call retain on a single
3295 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3296 // class here because we want the reverse-CFG postorder to consider each
3297 // function exit point, and we want to ignore selected cycle edges.
3298 SmallVector<BasicBlock *, 16> PostOrder;
3299 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
3300 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3301 NoObjCARCExceptionsMDKind,
3304 // Use reverse-postorder on the reverse CFG for bottom-up.
3305 bool BottomUpNestingDetected = false;
3306 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3307 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3309 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
3311 // Use reverse-postorder for top-down.
3312 bool TopDownNestingDetected = false;
3313 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3314 PostOrder.rbegin(), E = PostOrder.rend();
3316 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
3318 return TopDownNestingDetected && BottomUpNestingDetected;
3321 /// Move the calls in RetainsToMove and ReleasesToMove.
3322 void ObjCARCOpt::MoveCalls(Value *Arg,
3323 RRInfo &RetainsToMove,
3324 RRInfo &ReleasesToMove,
3325 MapVector<Value *, RRInfo> &Retains,
3326 DenseMap<Value *, RRInfo> &Releases,
3327 SmallVectorImpl<Instruction *> &DeadInsts,
3329 Type *ArgTy = Arg->getType();
3330 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
3332 // Insert the new retain and release calls.
3333 for (SmallPtrSet<Instruction *, 2>::const_iterator
3334 PI = ReleasesToMove.ReverseInsertPts.begin(),
3335 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3336 Instruction *InsertPt = *PI;
3337 Value *MyArg = ArgTy == ParamTy ? Arg :
3338 new BitCastInst(Arg, ParamTy, "", InsertPt);
3340 CallInst::Create(RetainsToMove.IsRetainBlock ?
3341 getRetainBlockCallee(M) : getRetainCallee(M),
3342 MyArg, "", InsertPt);
3343 Call->setDoesNotThrow();
3344 if (RetainsToMove.IsRetainBlock)
3345 Call->setMetadata(CopyOnEscapeMDKind,
3346 MDNode::get(M->getContext(), ArrayRef<Value *>()));
3348 Call->setTailCall();
3350 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
3352 " At insertion point: " << *InsertPt
3355 for (SmallPtrSet<Instruction *, 2>::const_iterator
3356 PI = RetainsToMove.ReverseInsertPts.begin(),
3357 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3358 Instruction *InsertPt = *PI;
3359 Value *MyArg = ArgTy == ParamTy ? Arg :
3360 new BitCastInst(Arg, ParamTy, "", InsertPt);
3361 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3363 // Attach a clang.imprecise_release metadata tag, if appropriate.
3364 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3365 Call->setMetadata(ImpreciseReleaseMDKind, M);
3366 Call->setDoesNotThrow();
3367 if (ReleasesToMove.IsTailCallRelease)
3368 Call->setTailCall();
3370 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
3372 " At insertion point: " << *InsertPt
3376 // Delete the original retain and release calls.
3377 for (SmallPtrSet<Instruction *, 2>::const_iterator
3378 AI = RetainsToMove.Calls.begin(),
3379 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3380 Instruction *OrigRetain = *AI;
3381 Retains.blot(OrigRetain);
3382 DeadInsts.push_back(OrigRetain);
3383 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
3386 for (SmallPtrSet<Instruction *, 2>::const_iterator
3387 AI = ReleasesToMove.Calls.begin(),
3388 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3389 Instruction *OrigRelease = *AI;
3390 Releases.erase(OrigRelease);
3391 DeadInsts.push_back(OrigRelease);
3392 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
3397 /// Identify pairings between the retains and releases, and delete and/or move
3400 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3402 MapVector<Value *, RRInfo> &Retains,
3403 DenseMap<Value *, RRInfo> &Releases,
3405 bool AnyPairsCompletelyEliminated = false;
3406 RRInfo RetainsToMove;
3407 RRInfo ReleasesToMove;
3408 SmallVector<Instruction *, 4> NewRetains;
3409 SmallVector<Instruction *, 4> NewReleases;
3410 SmallVector<Instruction *, 8> DeadInsts;
3412 // Visit each retain.
3413 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
3414 E = Retains.end(); I != E; ++I) {
3415 Value *V = I->first;
3416 if (!V) continue; // blotted
3418 Instruction *Retain = cast<Instruction>(V);
3420 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
3423 Value *Arg = GetObjCArg(Retain);
3425 // If the object being released is in static or stack storage, we know it's
3426 // not being managed by ObjC reference counting, so we can delete pairs
3427 // regardless of what possible decrements or uses lie between them.
3428 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
3430 // A constant pointer can't be pointing to an object on the heap. It may
3431 // be reference-counted, but it won't be deleted.
3432 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3433 if (const GlobalVariable *GV =
3434 dyn_cast<GlobalVariable>(
3435 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3436 if (GV->isConstant())
3439 // If a pair happens in a region where it is known that the reference count
3440 // is already incremented, we can similarly ignore possible decrements.
3441 bool KnownSafeTD = true, KnownSafeBU = true;
3443 // Connect the dots between the top-down-collected RetainsToMove and
3444 // bottom-up-collected ReleasesToMove to form sets of related calls.
3445 // This is an iterative process so that we connect multiple releases
3446 // to multiple retains if needed.
3447 unsigned OldDelta = 0;
3448 unsigned NewDelta = 0;
3449 unsigned OldCount = 0;
3450 unsigned NewCount = 0;
3451 bool FirstRelease = true;
3452 bool FirstRetain = true;
3453 NewRetains.push_back(Retain);
3455 for (SmallVectorImpl<Instruction *>::const_iterator
3456 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3457 Instruction *NewRetain = *NI;
3458 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3459 assert(It != Retains.end());
3460 const RRInfo &NewRetainRRI = It->second;
3461 KnownSafeTD &= NewRetainRRI.KnownSafe;
3462 for (SmallPtrSet<Instruction *, 2>::const_iterator
3463 LI = NewRetainRRI.Calls.begin(),
3464 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3465 Instruction *NewRetainRelease = *LI;
3466 DenseMap<Value *, RRInfo>::const_iterator Jt =
3467 Releases.find(NewRetainRelease);
3468 if (Jt == Releases.end())
3470 const RRInfo &NewRetainReleaseRRI = Jt->second;
3471 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3472 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3474 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3476 // Merge the ReleaseMetadata and IsTailCallRelease values.
3478 ReleasesToMove.ReleaseMetadata =
3479 NewRetainReleaseRRI.ReleaseMetadata;
3480 ReleasesToMove.IsTailCallRelease =
3481 NewRetainReleaseRRI.IsTailCallRelease;
3482 FirstRelease = false;
3484 if (ReleasesToMove.ReleaseMetadata !=
3485 NewRetainReleaseRRI.ReleaseMetadata)
3486 ReleasesToMove.ReleaseMetadata = 0;
3487 if (ReleasesToMove.IsTailCallRelease !=
3488 NewRetainReleaseRRI.IsTailCallRelease)
3489 ReleasesToMove.IsTailCallRelease = false;
3492 // Collect the optimal insertion points.
3494 for (SmallPtrSet<Instruction *, 2>::const_iterator
3495 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3496 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3498 Instruction *RIP = *RI;
3499 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3500 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3502 NewReleases.push_back(NewRetainRelease);
3507 if (NewReleases.empty()) break;
3509 // Back the other way.
3510 for (SmallVectorImpl<Instruction *>::const_iterator
3511 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3512 Instruction *NewRelease = *NI;
3513 DenseMap<Value *, RRInfo>::const_iterator It =
3514 Releases.find(NewRelease);
3515 assert(It != Releases.end());
3516 const RRInfo &NewReleaseRRI = It->second;
3517 KnownSafeBU &= NewReleaseRRI.KnownSafe;
3518 for (SmallPtrSet<Instruction *, 2>::const_iterator
3519 LI = NewReleaseRRI.Calls.begin(),
3520 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3521 Instruction *NewReleaseRetain = *LI;
3522 MapVector<Value *, RRInfo>::const_iterator Jt =
3523 Retains.find(NewReleaseRetain);
3524 if (Jt == Retains.end())
3526 const RRInfo &NewReleaseRetainRRI = Jt->second;
3527 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3528 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3529 unsigned PathCount =
3530 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3531 OldDelta += PathCount;
3532 OldCount += PathCount;
3534 // Merge the IsRetainBlock values.
3536 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3537 FirstRetain = false;
3538 } else if (ReleasesToMove.IsRetainBlock !=
3539 NewReleaseRetainRRI.IsRetainBlock)
3540 // It's not possible to merge the sequences if one uses
3541 // objc_retain and the other uses objc_retainBlock.
3544 // Collect the optimal insertion points.
3546 for (SmallPtrSet<Instruction *, 2>::const_iterator
3547 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3548 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3550 Instruction *RIP = *RI;
3551 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3552 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3553 NewDelta += PathCount;
3554 NewCount += PathCount;
3557 NewRetains.push_back(NewReleaseRetain);
3561 NewReleases.clear();
3562 if (NewRetains.empty()) break;
3565 // If the pointer is known incremented or nested, we can safely delete the
3566 // pair regardless of what's between them.
3567 if (KnownSafeTD || KnownSafeBU) {
3568 RetainsToMove.ReverseInsertPts.clear();
3569 ReleasesToMove.ReverseInsertPts.clear();
3572 // Determine whether the new insertion points we computed preserve the
3573 // balance of retain and release calls through the program.
3574 // TODO: If the fully aggressive solution isn't valid, try to find a
3575 // less aggressive solution which is.
3580 // Determine whether the original call points are balanced in the retain and
3581 // release calls through the program. If not, conservatively don't touch
3583 // TODO: It's theoretically possible to do code motion in this case, as
3584 // long as the existing imbalances are maintained.
3588 // Ok, everything checks out and we're all set. Let's move some code!
3590 assert(OldCount != 0 && "Unreachable code?");
3591 AnyPairsCompletelyEliminated = NewCount == 0;
3592 NumRRs += OldCount - NewCount;
3593 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3594 Retains, Releases, DeadInsts, M);
3597 NewReleases.clear();
3599 RetainsToMove.clear();
3600 ReleasesToMove.clear();
3603 // Now that we're done moving everything, we can delete the newly dead
3604 // instructions, as we no longer need them as insert points.
3605 while (!DeadInsts.empty())
3606 EraseInstruction(DeadInsts.pop_back_val());
3608 return AnyPairsCompletelyEliminated;
3611 /// Weak pointer optimizations.
3612 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3613 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3614 // itself because it uses AliasAnalysis and we need to do provenance
3616 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3617 Instruction *Inst = &*I++;
3619 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
3622 InstructionClass Class = GetBasicInstructionClass(Inst);
3623 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3626 // Delete objc_loadWeak calls with no users.
3627 if (Class == IC_LoadWeak && Inst->use_empty()) {
3628 Inst->eraseFromParent();
3632 // TODO: For now, just look for an earlier available version of this value
3633 // within the same block. Theoretically, we could do memdep-style non-local
3634 // analysis too, but that would want caching. A better approach would be to
3635 // use the technique that EarlyCSE uses.
3636 inst_iterator Current = llvm::prior(I);
3637 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3638 for (BasicBlock::iterator B = CurrentBB->begin(),
3639 J = Current.getInstructionIterator();
3641 Instruction *EarlierInst = &*llvm::prior(J);
3642 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3643 switch (EarlierClass) {
3645 case IC_LoadWeakRetained: {
3646 // If this is loading from the same pointer, replace this load's value
3648 CallInst *Call = cast<CallInst>(Inst);
3649 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3650 Value *Arg = Call->getArgOperand(0);
3651 Value *EarlierArg = EarlierCall->getArgOperand(0);
3652 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3653 case AliasAnalysis::MustAlias:
3655 // If the load has a builtin retain, insert a plain retain for it.
3656 if (Class == IC_LoadWeakRetained) {
3658 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3662 // Zap the fully redundant load.
3663 Call->replaceAllUsesWith(EarlierCall);
3664 Call->eraseFromParent();
3666 case AliasAnalysis::MayAlias:
3667 case AliasAnalysis::PartialAlias:
3669 case AliasAnalysis::NoAlias:
3676 // If this is storing to the same pointer and has the same size etc.
3677 // replace this load's value with the stored value.
3678 CallInst *Call = cast<CallInst>(Inst);
3679 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3680 Value *Arg = Call->getArgOperand(0);
3681 Value *EarlierArg = EarlierCall->getArgOperand(0);
3682 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3683 case AliasAnalysis::MustAlias:
3685 // If the load has a builtin retain, insert a plain retain for it.
3686 if (Class == IC_LoadWeakRetained) {
3688 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3692 // Zap the fully redundant load.
3693 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3694 Call->eraseFromParent();
3696 case AliasAnalysis::MayAlias:
3697 case AliasAnalysis::PartialAlias:
3699 case AliasAnalysis::NoAlias:
3706 // TOOD: Grab the copied value.
3708 case IC_AutoreleasepoolPush:
3711 // Weak pointers are only modified through the weak entry points
3712 // (and arbitrary calls, which could call the weak entry points).
3715 // Anything else could modify the weak pointer.
3722 // Then, for each destroyWeak with an alloca operand, check to see if
3723 // the alloca and all its users can be zapped.
3724 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3725 Instruction *Inst = &*I++;
3726 InstructionClass Class = GetBasicInstructionClass(Inst);
3727 if (Class != IC_DestroyWeak)
3730 CallInst *Call = cast<CallInst>(Inst);
3731 Value *Arg = Call->getArgOperand(0);
3732 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3733 for (Value::use_iterator UI = Alloca->use_begin(),
3734 UE = Alloca->use_end(); UI != UE; ++UI) {
3735 const Instruction *UserInst = cast<Instruction>(*UI);
3736 switch (GetBasicInstructionClass(UserInst)) {
3739 case IC_DestroyWeak:
3746 for (Value::use_iterator UI = Alloca->use_begin(),
3747 UE = Alloca->use_end(); UI != UE; ) {
3748 CallInst *UserInst = cast<CallInst>(*UI++);
3749 switch (GetBasicInstructionClass(UserInst)) {
3752 // These functions return their second argument.
3753 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3755 case IC_DestroyWeak:
3759 llvm_unreachable("alloca really is used!");
3761 UserInst->eraseFromParent();
3763 Alloca->eraseFromParent();
3768 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
3772 /// Identify program paths which execute sequences of retains and releases which
3773 /// can be eliminated.
3774 bool ObjCARCOpt::OptimizeSequences(Function &F) {
3775 /// Releases, Retains - These are used to store the results of the main flow
3776 /// analysis. These use Value* as the key instead of Instruction* so that the
3777 /// map stays valid when we get around to rewriting code and calls get
3778 /// replaced by arguments.
3779 DenseMap<Value *, RRInfo> Releases;
3780 MapVector<Value *, RRInfo> Retains;
3782 /// This is used during the traversal of the function to track the
3783 /// states for each identified object at each block.
3784 DenseMap<const BasicBlock *, BBState> BBStates;
3786 // Analyze the CFG of the function, and all instructions.
3787 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3790 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3794 /// Look for this pattern:
3796 /// %call = call i8* @something(...)
3797 /// %2 = call i8* @objc_retain(i8* %call)
3798 /// %3 = call i8* @objc_autorelease(i8* %2)
3801 /// And delete the retain and autorelease.
3803 /// Otherwise if it's just this:
3805 /// %3 = call i8* @objc_autorelease(i8* %2)
3808 /// convert the autorelease to autoreleaseRV.
3809 void ObjCARCOpt::OptimizeReturns(Function &F) {
3810 if (!F.getReturnType()->isPointerTy())
3813 SmallPtrSet<Instruction *, 4> DependingInstructions;
3814 SmallPtrSet<const BasicBlock *, 4> Visited;
3815 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3816 BasicBlock *BB = FI;
3817 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3819 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
3823 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3824 FindDependencies(NeedsPositiveRetainCount, Arg,
3825 BB, Ret, DependingInstructions, Visited, PA);
3826 if (DependingInstructions.size() != 1)
3830 CallInst *Autorelease =
3831 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3834 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3835 if (!IsAutorelease(AutoreleaseClass))
3837 if (GetObjCArg(Autorelease) != Arg)
3840 DependingInstructions.clear();
3843 // Check that there is nothing that can affect the reference
3844 // count between the autorelease and the retain.
3845 FindDependencies(CanChangeRetainCount, Arg,
3846 BB, Autorelease, DependingInstructions, Visited, PA);
3847 if (DependingInstructions.size() != 1)
3852 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3854 // Check that we found a retain with the same argument.
3856 !IsRetain(GetBasicInstructionClass(Retain)) ||
3857 GetObjCArg(Retain) != Arg)
3860 DependingInstructions.clear();
3863 // Convert the autorelease to an autoreleaseRV, since it's
3864 // returning the value.
3865 if (AutoreleaseClass == IC_Autorelease) {
3866 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
3867 "=> autoreleaseRV since it's returning a value.\n"
3868 " In: " << *Autorelease
3870 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3871 DEBUG(dbgs() << " Out: " << *Autorelease
3873 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
3874 AutoreleaseClass = IC_AutoreleaseRV;
3877 // Check that there is nothing that can affect the reference
3878 // count between the retain and the call.
3879 // Note that Retain need not be in BB.
3880 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3881 DependingInstructions, Visited, PA);
3882 if (DependingInstructions.size() != 1)
3887 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3889 // Check that the pointer is the return value of the call.
3890 if (!Call || Arg != Call)
3893 // Check that the call is a regular call.
3894 InstructionClass Class = GetBasicInstructionClass(Call);
3895 if (Class != IC_CallOrUser && Class != IC_Call)
3898 // If so, we can zap the retain and autorelease.
3901 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
3903 << *Autorelease << "\n");
3904 EraseInstruction(Retain);
3905 EraseInstruction(Autorelease);
3911 DependingInstructions.clear();
3915 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
3919 bool ObjCARCOpt::doInitialization(Module &M) {
3923 // If nothing in the Module uses ARC, don't do anything.
3924 Run = ModuleHasARC(M);
3928 // Identify the imprecise release metadata kind.
3929 ImpreciseReleaseMDKind =
3930 M.getContext().getMDKindID("clang.imprecise_release");
3931 CopyOnEscapeMDKind =
3932 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3933 NoObjCARCExceptionsMDKind =
3934 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3936 // Intuitively, objc_retain and others are nocapture, however in practice
3937 // they are not, because they return their argument value. And objc_release
3938 // calls finalizers which can have arbitrary side effects.
3940 // These are initialized lazily.
3942 AutoreleaseRVCallee = 0;
3945 RetainBlockCallee = 0;
3946 AutoreleaseCallee = 0;
3951 bool ObjCARCOpt::runOnFunction(Function &F) {
3955 // If nothing in the Module uses ARC, don't do anything.
3961 DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
3963 PA.setAA(&getAnalysis<AliasAnalysis>());
3965 // This pass performs several distinct transformations. As a compile-time aid
3966 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3967 // library functions aren't declared.
3969 // Preliminary optimizations. This also computs UsedInThisFunction.
3970 OptimizeIndividualCalls(F);
3972 // Optimizations for weak pointers.
3973 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3974 (1 << IC_LoadWeakRetained) |
3975 (1 << IC_StoreWeak) |
3976 (1 << IC_InitWeak) |
3977 (1 << IC_CopyWeak) |
3978 (1 << IC_MoveWeak) |
3979 (1 << IC_DestroyWeak)))
3980 OptimizeWeakCalls(F);
3982 // Optimizations for retain+release pairs.
3983 if (UsedInThisFunction & ((1 << IC_Retain) |
3984 (1 << IC_RetainRV) |
3985 (1 << IC_RetainBlock)))
3986 if (UsedInThisFunction & (1 << IC_Release))
3987 // Run OptimizeSequences until it either stops making changes or
3988 // no retain+release pair nesting is detected.
3989 while (OptimizeSequences(F)) {}
3991 // Optimizations if objc_autorelease is used.
3992 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3993 (1 << IC_AutoreleaseRV)))
3996 DEBUG(dbgs() << "\n");
4001 void ObjCARCOpt::releaseMemory() {
4007 /// \defgroup ARCContract ARC Contraction.
4010 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
4011 // dominated by single calls.
4013 #include "llvm/Analysis/Dominators.h"
4014 #include "llvm/IR/InlineAsm.h"
4015 #include "llvm/IR/Operator.h"
4017 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
4020 /// \brief Late ARC optimizations
4022 /// These change the IR in a way that makes it difficult to be analyzed by
4023 /// ObjCARCOpt, so it's run late.
4024 class ObjCARCContract : public FunctionPass {
4028 ProvenanceAnalysis PA;
4030 /// A flag indicating whether this optimization pass should run.
4033 /// Declarations for ObjC runtime functions, for use in creating calls to
4034 /// them. These are initialized lazily to avoid cluttering up the Module
4035 /// with unused declarations.
4037 /// Declaration for objc_storeStrong().
4038 Constant *StoreStrongCallee;
4039 /// Declaration for objc_retainAutorelease().
4040 Constant *RetainAutoreleaseCallee;
4041 /// Declaration for objc_retainAutoreleaseReturnValue().
4042 Constant *RetainAutoreleaseRVCallee;
4044 /// The inline asm string to insert between calls and RetainRV calls to make
4045 /// the optimization work on targets which need it.
4046 const MDString *RetainRVMarker;
4048 /// The set of inserted objc_storeStrong calls. If at the end of walking the
4049 /// function we have found no alloca instructions, these calls can be marked
4051 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
4053 Constant *getStoreStrongCallee(Module *M);
4054 Constant *getRetainAutoreleaseCallee(Module *M);
4055 Constant *getRetainAutoreleaseRVCallee(Module *M);
4057 bool ContractAutorelease(Function &F, Instruction *Autorelease,
4058 InstructionClass Class,
4059 SmallPtrSet<Instruction *, 4>
4060 &DependingInstructions,
4061 SmallPtrSet<const BasicBlock *, 4>
4064 void ContractRelease(Instruction *Release,
4065 inst_iterator &Iter);
4067 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
4068 virtual bool doInitialization(Module &M);
4069 virtual bool runOnFunction(Function &F);
4073 ObjCARCContract() : FunctionPass(ID) {
4074 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
4079 char ObjCARCContract::ID = 0;
4080 INITIALIZE_PASS_BEGIN(ObjCARCContract,
4081 "objc-arc-contract", "ObjC ARC contraction", false, false)
4082 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
4083 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
4084 INITIALIZE_PASS_END(ObjCARCContract,
4085 "objc-arc-contract", "ObjC ARC contraction", false, false)
4087 Pass *llvm::createObjCARCContractPass() {
4088 return new ObjCARCContract();
4091 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
4092 AU.addRequired<AliasAnalysis>();
4093 AU.addRequired<DominatorTree>();
4094 AU.setPreservesCFG();
4097 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
4098 if (!StoreStrongCallee) {
4099 LLVMContext &C = M->getContext();
4100 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4101 Type *I8XX = PointerType::getUnqual(I8X);
4102 Type *Params[] = { I8XX, I8X };
4104 AttributeSet Attribute = AttributeSet()
4105 .addAttr(M->getContext(), AttributeSet::FunctionIndex,
4106 Attribute::get(C, Attribute::NoUnwind))
4107 .addAttr(M->getContext(), 1, Attribute::get(C, Attribute::NoCapture));
4110 M->getOrInsertFunction(
4112 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
4115 return StoreStrongCallee;
4118 Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
4119 if (!RetainAutoreleaseCallee) {
4120 LLVMContext &C = M->getContext();
4121 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4122 Type *Params[] = { I8X };
4123 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
4124 AttributeSet Attribute =
4125 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
4126 Attribute::get(C, Attribute::NoUnwind));
4127 RetainAutoreleaseCallee =
4128 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
4130 return RetainAutoreleaseCallee;
4133 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
4134 if (!RetainAutoreleaseRVCallee) {
4135 LLVMContext &C = M->getContext();
4136 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4137 Type *Params[] = { I8X };
4138 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
4139 AttributeSet Attribute =
4140 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
4141 Attribute::get(C, Attribute::NoUnwind));
4142 RetainAutoreleaseRVCallee =
4143 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
4146 return RetainAutoreleaseRVCallee;
4149 /// Merge an autorelease with a retain into a fused call.
4151 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
4152 InstructionClass Class,
4153 SmallPtrSet<Instruction *, 4>
4154 &DependingInstructions,
4155 SmallPtrSet<const BasicBlock *, 4>
4157 const Value *Arg = GetObjCArg(Autorelease);
4159 // Check that there are no instructions between the retain and the autorelease
4160 // (such as an autorelease_pop) which may change the count.
4161 CallInst *Retain = 0;
4162 if (Class == IC_AutoreleaseRV)
4163 FindDependencies(RetainAutoreleaseRVDep, Arg,
4164 Autorelease->getParent(), Autorelease,
4165 DependingInstructions, Visited, PA);
4167 FindDependencies(RetainAutoreleaseDep, Arg,
4168 Autorelease->getParent(), Autorelease,
4169 DependingInstructions, Visited, PA);
4172 if (DependingInstructions.size() != 1) {
4173 DependingInstructions.clear();
4177 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
4178 DependingInstructions.clear();
4181 GetBasicInstructionClass(Retain) != IC_Retain ||
4182 GetObjCArg(Retain) != Arg)
4188 DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing "
4189 "retain/autorelease. Erasing: " << *Autorelease << "\n"
4191 << *Retain << "\n");
4193 if (Class == IC_AutoreleaseRV)
4194 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
4196 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
4198 DEBUG(dbgs() << " New Retain: "
4199 << *Retain << "\n");
4201 EraseInstruction(Autorelease);
4205 /// Attempt to merge an objc_release with a store, load, and objc_retain to form
4206 /// an objc_storeStrong. This can be a little tricky because the instructions
4207 /// don't always appear in order, and there may be unrelated intervening
4209 void ObjCARCContract::ContractRelease(Instruction *Release,
4210 inst_iterator &Iter) {
4211 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
4212 if (!Load || !Load->isSimple()) return;
4214 // For now, require everything to be in one basic block.
4215 BasicBlock *BB = Release->getParent();
4216 if (Load->getParent() != BB) return;
4218 // Walk down to find the store and the release, which may be in either order.
4219 BasicBlock::iterator I = Load, End = BB->end();
4221 AliasAnalysis::Location Loc = AA->getLocation(Load);
4222 StoreInst *Store = 0;
4223 bool SawRelease = false;
4224 for (; !Store || !SawRelease; ++I) {
4228 Instruction *Inst = I;
4229 if (Inst == Release) {
4234 InstructionClass Class = GetBasicInstructionClass(Inst);
4236 // Unrelated retains are harmless.
4237 if (IsRetain(Class))
4241 // The store is the point where we're going to put the objc_storeStrong,
4242 // so make sure there are no uses after it.
4243 if (CanUse(Inst, Load, PA, Class))
4245 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
4246 // We are moving the load down to the store, so check for anything
4247 // else which writes to the memory between the load and the store.
4248 Store = dyn_cast<StoreInst>(Inst);
4249 if (!Store || !Store->isSimple()) return;
4250 if (Store->getPointerOperand() != Loc.Ptr) return;
4254 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
4256 // Walk up to find the retain.
4258 BasicBlock::iterator Begin = BB->begin();
4259 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
4261 Instruction *Retain = I;
4262 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
4263 if (GetObjCArg(Retain) != New) return;
4268 LLVMContext &C = Release->getContext();
4269 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4270 Type *I8XX = PointerType::getUnqual(I8X);
4272 Value *Args[] = { Load->getPointerOperand(), New };
4273 if (Args[0]->getType() != I8XX)
4274 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
4275 if (Args[1]->getType() != I8X)
4276 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
4277 CallInst *StoreStrong =
4278 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
4280 StoreStrong->setDoesNotThrow();
4281 StoreStrong->setDebugLoc(Store->getDebugLoc());
4283 // We can't set the tail flag yet, because we haven't yet determined
4284 // whether there are any escaping allocas. Remember this call, so that
4285 // we can set the tail flag once we know it's safe.
4286 StoreStrongCalls.insert(StoreStrong);
4288 if (&*Iter == Store) ++Iter;
4289 Store->eraseFromParent();
4290 Release->eraseFromParent();
4291 EraseInstruction(Retain);
4292 if (Load->use_empty())
4293 Load->eraseFromParent();
4296 bool ObjCARCContract::doInitialization(Module &M) {
4297 // If nothing in the Module uses ARC, don't do anything.
4298 Run = ModuleHasARC(M);
4302 // These are initialized lazily.
4303 StoreStrongCallee = 0;
4304 RetainAutoreleaseCallee = 0;
4305 RetainAutoreleaseRVCallee = 0;
4307 // Initialize RetainRVMarker.
4309 if (NamedMDNode *NMD =
4310 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4311 if (NMD->getNumOperands() == 1) {
4312 const MDNode *N = NMD->getOperand(0);
4313 if (N->getNumOperands() == 1)
4314 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4321 bool ObjCARCContract::runOnFunction(Function &F) {
4325 // If nothing in the Module uses ARC, don't do anything.
4330 AA = &getAnalysis<AliasAnalysis>();
4331 DT = &getAnalysis<DominatorTree>();
4333 PA.setAA(&getAnalysis<AliasAnalysis>());
4335 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4336 // keyword. Be conservative if the function has variadic arguments.
4337 // It seems that functions which "return twice" are also unsafe for the
4338 // "tail" argument, because they are setjmp, which could need to
4339 // return to an earlier stack state.
4340 bool TailOkForStoreStrongs = !F.isVarArg() &&
4341 !F.callsFunctionThatReturnsTwice();
4343 // For ObjC library calls which return their argument, replace uses of the
4344 // argument with uses of the call return value, if it dominates the use. This
4345 // reduces register pressure.
4346 SmallPtrSet<Instruction *, 4> DependingInstructions;
4347 SmallPtrSet<const BasicBlock *, 4> Visited;
4348 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4349 Instruction *Inst = &*I++;
4351 DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
4353 // Only these library routines return their argument. In particular,
4354 // objc_retainBlock does not necessarily return its argument.
4355 InstructionClass Class = GetBasicInstructionClass(Inst);
4358 case IC_FusedRetainAutorelease:
4359 case IC_FusedRetainAutoreleaseRV:
4361 case IC_Autorelease:
4362 case IC_AutoreleaseRV:
4363 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4367 // If we're compiling for a target which needs a special inline-asm
4368 // marker to do the retainAutoreleasedReturnValue optimization,
4370 if (!RetainRVMarker)
4372 BasicBlock::iterator BBI = Inst;
4373 BasicBlock *InstParent = Inst->getParent();
4375 // Step up to see if the call immediately precedes the RetainRV call.
4376 // If it's an invoke, we have to cross a block boundary. And we have
4377 // to carefully dodge no-op instructions.
4379 if (&*BBI == InstParent->begin()) {
4380 BasicBlock *Pred = InstParent->getSinglePredecessor();
4382 goto decline_rv_optimization;
4383 BBI = Pred->getTerminator();
4387 } while (isNoopInstruction(BBI));
4389 if (&*BBI == GetObjCArg(Inst)) {
4390 DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
4391 "retainAutoreleasedReturnValue optimization.\n");
4394 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4395 /*isVarArg=*/false),
4396 RetainRVMarker->getString(),
4397 /*Constraints=*/"", /*hasSideEffects=*/true);
4398 CallInst::Create(IA, "", Inst);
4400 decline_rv_optimization:
4404 // objc_initWeak(p, null) => *p = null
4405 CallInst *CI = cast<CallInst>(Inst);
4406 if (isNullOrUndef(CI->getArgOperand(1))) {
4408 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4410 new StoreInst(Null, CI->getArgOperand(0), CI);
4412 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
4413 << " New = " << *Null << "\n");
4415 CI->replaceAllUsesWith(Null);
4416 CI->eraseFromParent();
4421 ContractRelease(Inst, I);
4424 // Be conservative if the function has any alloca instructions.
4425 // Technically we only care about escaping alloca instructions,
4426 // but this is sufficient to handle some interesting cases.
4427 if (isa<AllocaInst>(Inst))
4428 TailOkForStoreStrongs = false;
4434 DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n");
4436 // Don't use GetObjCArg because we don't want to look through bitcasts
4437 // and such; to do the replacement, the argument must have type i8*.
4438 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4440 // If we're compiling bugpointed code, don't get in trouble.
4441 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4443 // Look through the uses of the pointer.
4444 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4446 Use &U = UI.getUse();
4447 unsigned OperandNo = UI.getOperandNo();
4448 ++UI; // Increment UI now, because we may unlink its element.
4450 // If the call's return value dominates a use of the call's argument
4451 // value, rewrite the use to use the return value. We check for
4452 // reachability here because an unreachable call is considered to
4453 // trivially dominate itself, which would lead us to rewriting its
4454 // argument in terms of its return value, which would lead to
4455 // infinite loops in GetObjCArg.
4456 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
4458 Instruction *Replacement = Inst;
4459 Type *UseTy = U.get()->getType();
4460 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
4461 // For PHI nodes, insert the bitcast in the predecessor block.
4462 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4463 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
4464 if (Replacement->getType() != UseTy)
4465 Replacement = new BitCastInst(Replacement, UseTy, "",
4467 // While we're here, rewrite all edges for this PHI, rather
4468 // than just one use at a time, to minimize the number of
4469 // bitcasts we emit.
4470 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4471 if (PHI->getIncomingBlock(i) == BB) {
4472 // Keep the UI iterator valid.
4473 if (&PHI->getOperandUse(
4474 PHINode::getOperandNumForIncomingValue(i)) ==
4477 PHI->setIncomingValue(i, Replacement);
4480 if (Replacement->getType() != UseTy)
4481 Replacement = new BitCastInst(Replacement, UseTy, "",
4482 cast<Instruction>(U.getUser()));
4488 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
4489 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4490 Arg = BI->getOperand(0);
4491 else if (isa<GEPOperator>(Arg) &&
4492 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4493 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4494 else if (isa<GlobalAlias>(Arg) &&
4495 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4496 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4502 // If this function has no escaping allocas or suspicious vararg usage,
4503 // objc_storeStrong calls can be marked with the "tail" keyword.
4504 if (TailOkForStoreStrongs)
4505 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
4506 E = StoreStrongCalls.end(); I != E; ++I)
4507 (*I)->setTailCall();
4508 StoreStrongCalls.clear();