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
172 /// \brief Test whether the given value is possible a reference-counted pointer.
173 static bool IsPotentialUse(const Value *Op) {
174 // Pointers to static or stack storage are not reference-counted pointers.
175 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
177 // Special arguments are not reference-counted.
178 if (const Argument *Arg = dyn_cast<Argument>(Op))
179 if (Arg->hasByValAttr() ||
180 Arg->hasNestAttr() ||
181 Arg->hasStructRetAttr())
183 // Only consider values with pointer types.
184 // It seemes intuitive to exclude function pointer types as well, since
185 // functions are never reference-counted, however clang occasionally
186 // bitcasts reference-counted pointers to function-pointer type
188 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
191 // Conservatively assume anything else is a potential use.
195 /// \brief Helper for GetInstructionClass. Determines what kind of construct CS
197 static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
198 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
200 if (IsPotentialUse(*I))
201 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
203 return CS.onlyReadsMemory() ? IC_None : IC_Call;
206 /// \brief Determine if F is one of the special known Functions. If it isn't,
207 /// return IC_CallOrUser.
208 static InstructionClass GetFunctionClass(const Function *F) {
209 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
213 return StringSwitch<InstructionClass>(F->getName())
214 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
215 .Default(IC_CallOrUser);
218 const Argument *A0 = AI++;
220 // Argument is a pointer.
221 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
222 Type *ETy = PTy->getElementType();
224 if (ETy->isIntegerTy(8))
225 return StringSwitch<InstructionClass>(F->getName())
226 .Case("objc_retain", IC_Retain)
227 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
228 .Case("objc_retainBlock", IC_RetainBlock)
229 .Case("objc_release", IC_Release)
230 .Case("objc_autorelease", IC_Autorelease)
231 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
232 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
233 .Case("objc_retainedObject", IC_NoopCast)
234 .Case("objc_unretainedObject", IC_NoopCast)
235 .Case("objc_unretainedPointer", IC_NoopCast)
236 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
237 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
238 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
239 .Default(IC_CallOrUser);
242 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
243 if (Pte->getElementType()->isIntegerTy(8))
244 return StringSwitch<InstructionClass>(F->getName())
245 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
246 .Case("objc_loadWeak", IC_LoadWeak)
247 .Case("objc_destroyWeak", IC_DestroyWeak)
248 .Default(IC_CallOrUser);
251 // Two arguments, first is i8**.
252 const Argument *A1 = AI++;
254 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
255 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
256 if (Pte->getElementType()->isIntegerTy(8))
257 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
258 Type *ETy1 = PTy1->getElementType();
259 // Second argument is i8*
260 if (ETy1->isIntegerTy(8))
261 return StringSwitch<InstructionClass>(F->getName())
262 .Case("objc_storeWeak", IC_StoreWeak)
263 .Case("objc_initWeak", IC_InitWeak)
264 .Case("objc_storeStrong", IC_StoreStrong)
265 .Default(IC_CallOrUser);
266 // Second argument is i8**.
267 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
268 if (Pte1->getElementType()->isIntegerTy(8))
269 return StringSwitch<InstructionClass>(F->getName())
270 .Case("objc_moveWeak", IC_MoveWeak)
271 .Case("objc_copyWeak", IC_CopyWeak)
272 .Default(IC_CallOrUser);
276 return IC_CallOrUser;
279 /// \brief Determine what kind of construct V is.
280 static InstructionClass GetInstructionClass(const Value *V) {
281 if (const Instruction *I = dyn_cast<Instruction>(V)) {
282 // Any instruction other than bitcast and gep with a pointer operand have a
283 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
284 // to a subsequent use, rather than using it themselves, in this sense.
285 // As a short cut, several other opcodes are known to have no pointer
286 // operands of interest. And ret is never followed by a release, so it's
287 // not interesting to examine.
288 switch (I->getOpcode()) {
289 case Instruction::Call: {
290 const CallInst *CI = cast<CallInst>(I);
291 // Check for calls to special functions.
292 if (const Function *F = CI->getCalledFunction()) {
293 InstructionClass Class = GetFunctionClass(F);
294 if (Class != IC_CallOrUser)
297 // None of the intrinsic functions do objc_release. For intrinsics, the
298 // only question is whether or not they may be users.
299 switch (F->getIntrinsicID()) {
300 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
301 case Intrinsic::stacksave: case Intrinsic::stackrestore:
302 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
303 case Intrinsic::objectsize: case Intrinsic::prefetch:
304 case Intrinsic::stackprotector:
305 case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
306 case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
307 case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
308 case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
309 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
310 case Intrinsic::invariant_start: case Intrinsic::invariant_end:
311 // Don't let dbg info affect our results.
312 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
313 // Short cut: Some intrinsics obviously don't use ObjC pointers.
319 return GetCallSiteClass(CI);
321 case Instruction::Invoke:
322 return GetCallSiteClass(cast<InvokeInst>(I));
323 case Instruction::BitCast:
324 case Instruction::GetElementPtr:
325 case Instruction::Select: case Instruction::PHI:
326 case Instruction::Ret: case Instruction::Br:
327 case Instruction::Switch: case Instruction::IndirectBr:
328 case Instruction::Alloca: case Instruction::VAArg:
329 case Instruction::Add: case Instruction::FAdd:
330 case Instruction::Sub: case Instruction::FSub:
331 case Instruction::Mul: case Instruction::FMul:
332 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
333 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
334 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
335 case Instruction::And: case Instruction::Or: case Instruction::Xor:
336 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
337 case Instruction::IntToPtr: case Instruction::FCmp:
338 case Instruction::FPTrunc: case Instruction::FPExt:
339 case Instruction::FPToUI: case Instruction::FPToSI:
340 case Instruction::UIToFP: case Instruction::SIToFP:
341 case Instruction::InsertElement: case Instruction::ExtractElement:
342 case Instruction::ShuffleVector:
343 case Instruction::ExtractValue:
345 case Instruction::ICmp:
346 // Comparing a pointer with null, or any other constant, isn't an
347 // interesting use, because we don't care what the pointer points to, or
348 // about the values of any other dynamic reference-counted pointers.
349 if (IsPotentialUse(I->getOperand(1)))
353 // For anything else, check all the operands.
354 // Note that this includes both operands of a Store: while the first
355 // operand isn't actually being dereferenced, it is being stored to
356 // memory where we can no longer track who might read it and dereference
357 // it, so we have to consider it potentially used.
358 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
360 if (IsPotentialUse(*OI))
365 // Otherwise, it's totally inert for ARC purposes.
369 /// \brief Determine which objc runtime call instruction class V belongs to.
371 /// This is similar to GetInstructionClass except that it only detects objc
372 /// runtime calls. This allows it to be faster.
374 static InstructionClass GetBasicInstructionClass(const Value *V) {
375 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
376 if (const Function *F = CI->getCalledFunction())
377 return GetFunctionClass(F);
378 // Otherwise, be conservative.
379 return IC_CallOrUser;
382 // Otherwise, be conservative.
383 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
386 /// \brief Test if the given class is objc_retain or equivalent.
387 static bool IsRetain(InstructionClass Class) {
388 return Class == IC_Retain ||
389 Class == IC_RetainRV;
392 /// \brief Test if the given class is objc_autorelease or equivalent.
393 static bool IsAutorelease(InstructionClass Class) {
394 return Class == IC_Autorelease ||
395 Class == IC_AutoreleaseRV;
398 /// \brief Test if the given class represents instructions which return their
399 /// argument verbatim.
400 static bool IsForwarding(InstructionClass Class) {
401 // objc_retainBlock technically doesn't always return its argument
402 // verbatim, but it doesn't matter for our purposes here.
403 return Class == IC_Retain ||
404 Class == IC_RetainRV ||
405 Class == IC_Autorelease ||
406 Class == IC_AutoreleaseRV ||
407 Class == IC_RetainBlock ||
408 Class == IC_NoopCast;
411 /// \brief Test if the given class represents instructions which do nothing if
412 /// passed a null pointer.
413 static bool IsNoopOnNull(InstructionClass Class) {
414 return Class == IC_Retain ||
415 Class == IC_RetainRV ||
416 Class == IC_Release ||
417 Class == IC_Autorelease ||
418 Class == IC_AutoreleaseRV ||
419 Class == IC_RetainBlock;
422 /// \brief Test if the given class represents instructions which are always safe
423 /// to mark with the "tail" keyword.
424 static bool IsAlwaysTail(InstructionClass Class) {
425 // IC_RetainBlock may be given a stack argument.
426 return Class == IC_Retain ||
427 Class == IC_RetainRV ||
428 Class == IC_AutoreleaseRV;
431 /// \brief Test if the given class represents instructions which are never safe
432 /// to mark with the "tail" keyword.
433 static bool IsNeverTail(InstructionClass Class) {
434 /// It is never safe to tail call objc_autorelease since by tail calling
435 /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
436 /// fast autoreleasing causing our object to be potentially reclaimed from the
437 /// autorelease pool which violates the semantics of __autoreleasing types in
439 return Class == IC_Autorelease;
442 /// \brief Test if the given class represents instructions which are always safe
443 /// to mark with the nounwind attribute.
444 static bool IsNoThrow(InstructionClass Class) {
445 // objc_retainBlock is not nounwind because it calls user copy constructors
446 // which could theoretically throw.
447 return Class == IC_Retain ||
448 Class == IC_RetainRV ||
449 Class == IC_Release ||
450 Class == IC_Autorelease ||
451 Class == IC_AutoreleaseRV ||
452 Class == IC_AutoreleasepoolPush ||
453 Class == IC_AutoreleasepoolPop;
456 /// \brief Erase the given instruction.
458 /// Many ObjC calls return their argument verbatim,
459 /// so if it's such a call and the return value has users, replace them with the
462 static void EraseInstruction(Instruction *CI) {
463 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
465 bool Unused = CI->use_empty();
468 // Replace the return value with the argument.
469 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
470 "Can't delete non-forwarding instruction with users!");
471 CI->replaceAllUsesWith(OldArg);
474 CI->eraseFromParent();
477 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
480 /// \brief This is a wrapper around getUnderlyingObject which also knows how to
481 /// look through objc_retain and objc_autorelease calls, which we know to return
482 /// their argument verbatim.
483 static const Value *GetUnderlyingObjCPtr(const Value *V) {
485 V = GetUnderlyingObject(V);
486 if (!IsForwarding(GetBasicInstructionClass(V)))
488 V = cast<CallInst>(V)->getArgOperand(0);
494 /// \brief This is a wrapper around Value::stripPointerCasts which also knows
495 /// how to look through objc_retain and objc_autorelease calls, which we know to
496 /// return their argument verbatim.
497 static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
499 V = V->stripPointerCasts();
500 if (!IsForwarding(GetBasicInstructionClass(V)))
502 V = cast<CallInst>(V)->getArgOperand(0);
507 /// \brief This is a wrapper around Value::stripPointerCasts which also knows
508 /// how to look through objc_retain and objc_autorelease calls, which we know to
509 /// return their argument verbatim.
510 static Value *StripPointerCastsAndObjCCalls(Value *V) {
512 V = V->stripPointerCasts();
513 if (!IsForwarding(GetBasicInstructionClass(V)))
515 V = cast<CallInst>(V)->getArgOperand(0);
520 /// \brief Assuming the given instruction is one of the special calls such as
521 /// objc_retain or objc_release, return the argument value, stripped of no-op
522 /// casts and forwarding calls.
523 static Value *GetObjCArg(Value *Inst) {
524 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
527 /// \brief This is similar to AliasAnalysis's isObjCIdentifiedObject, except
528 /// that it uses special knowledge of ObjC conventions.
529 static bool IsObjCIdentifiedObject(const Value *V) {
530 // Assume that call results and arguments have their own "provenance".
531 // Constants (including GlobalVariables) and Allocas are never
532 // reference-counted.
533 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
534 isa<Argument>(V) || isa<Constant>(V) ||
538 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
539 const Value *Pointer =
540 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
541 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
542 // A constant pointer can't be pointing to an object on the heap. It may
543 // be reference-counted, but it won't be deleted.
544 if (GV->isConstant())
546 StringRef Name = GV->getName();
547 // These special variables are known to hold values which are not
548 // reference-counted pointers.
549 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
550 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
551 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
552 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
553 Name.startswith("\01l_objc_msgSend_fixup_"))
561 /// \brief This is similar to StripPointerCastsAndObjCCalls but it stops as soon
562 /// as it finds a value with multiple uses.
563 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
564 if (Arg->hasOneUse()) {
565 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
566 return FindSingleUseIdentifiedObject(BC->getOperand(0));
567 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
568 if (GEP->hasAllZeroIndices())
569 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
570 if (IsForwarding(GetBasicInstructionClass(Arg)))
571 return FindSingleUseIdentifiedObject(
572 cast<CallInst>(Arg)->getArgOperand(0));
573 if (!IsObjCIdentifiedObject(Arg))
578 // If we found an identifiable object but it has multiple uses, but they are
579 // trivial uses, we can still consider this to be a single-use value.
580 if (IsObjCIdentifiedObject(Arg)) {
581 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
584 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
594 /// \brief Test if the given module looks interesting to run ARC optimization
596 static bool ModuleHasARC(const Module &M) {
598 M.getNamedValue("objc_retain") ||
599 M.getNamedValue("objc_release") ||
600 M.getNamedValue("objc_autorelease") ||
601 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
602 M.getNamedValue("objc_retainBlock") ||
603 M.getNamedValue("objc_autoreleaseReturnValue") ||
604 M.getNamedValue("objc_autoreleasePoolPush") ||
605 M.getNamedValue("objc_loadWeakRetained") ||
606 M.getNamedValue("objc_loadWeak") ||
607 M.getNamedValue("objc_destroyWeak") ||
608 M.getNamedValue("objc_storeWeak") ||
609 M.getNamedValue("objc_initWeak") ||
610 M.getNamedValue("objc_moveWeak") ||
611 M.getNamedValue("objc_copyWeak") ||
612 M.getNamedValue("objc_retainedObject") ||
613 M.getNamedValue("objc_unretainedObject") ||
614 M.getNamedValue("objc_unretainedPointer");
617 /// \brief Test whether the given pointer, which is an Objective C block
618 /// pointer, does not "escape".
620 /// This differs from regular escape analysis in that a use as an
621 /// argument to a call is not considered an escape.
623 static bool DoesObjCBlockEscape(const Value *BlockPtr) {
625 DEBUG(dbgs() << "DoesObjCBlockEscape: Target: " << *BlockPtr << "\n");
627 // Walk the def-use chains.
628 SmallVector<const Value *, 4> Worklist;
629 Worklist.push_back(BlockPtr);
631 // Ensure we do not visit any value twice.
632 SmallPtrSet<const Value *, 4> VisitedSet;
635 const Value *V = Worklist.pop_back_val();
637 DEBUG(dbgs() << "DoesObjCBlockEscape: Visiting: " << *V << "\n");
639 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
641 const User *UUser = *UI;
643 DEBUG(dbgs() << "DoesObjCBlockEscape: User: " << *UUser << "\n");
645 // Special - Use by a call (callee or argument) is not considered
647 switch (GetBasicInstructionClass(UUser)) {
652 case IC_AutoreleaseRV: {
653 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies pointer arguments. "
655 // These special functions make copies of their pointer arguments.
660 // Use by an instruction which copies the value is an escape if the
661 // result is an escape.
662 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
663 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
665 if (!VisitedSet.insert(UUser)) {
666 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies value. Escapes "
667 "if result escapes. Adding to list.\n");
668 Worklist.push_back(UUser);
670 DEBUG(dbgs() << "DoesObjCBlockEscape: Already visited node.\n");
674 // Use by a load is not an escape.
675 if (isa<LoadInst>(UUser))
677 // Use by a store is not an escape if the use is the address.
678 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
679 if (V != SI->getValueOperand())
683 // Regular calls and other stuff are not considered escapes.
686 // Otherwise, conservatively assume an escape.
687 DEBUG(dbgs() << "DoesObjCBlockEscape: Assuming block escapes.\n");
690 } while (!Worklist.empty());
693 DEBUG(dbgs() << "DoesObjCBlockEscape: Block does not escape.\n");
699 /// \defgroup ARCAA Extends alias analysis using ObjC specific knowledge.
702 #include "llvm/Analysis/AliasAnalysis.h"
703 #include "llvm/Analysis/Passes.h"
704 #include "llvm/Pass.h"
707 /// \brief This is a simple alias analysis implementation that uses knowledge
708 /// of ARC constructs to answer queries.
710 /// TODO: This class could be generalized to know about other ObjC-specific
711 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
712 /// even though their offsets are dynamic.
713 class ObjCARCAliasAnalysis : public ImmutablePass,
714 public AliasAnalysis {
716 static char ID; // Class identification, replacement for typeinfo
717 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
718 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
722 virtual void initializePass() {
723 InitializeAliasAnalysis(this);
726 /// This method is used when a pass implements an analysis interface through
727 /// multiple inheritance. If needed, it should override this to adjust the
728 /// this pointer as needed for the specified pass info.
729 virtual void *getAdjustedAnalysisPointer(const void *PI) {
730 if (PI == &AliasAnalysis::ID)
731 return static_cast<AliasAnalysis *>(this);
735 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
736 virtual AliasResult alias(const Location &LocA, const Location &LocB);
737 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
738 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
739 virtual ModRefBehavior getModRefBehavior(const Function *F);
740 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
741 const Location &Loc);
742 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
743 ImmutableCallSite CS2);
745 } // End of anonymous namespace
747 // Register this pass...
748 char ObjCARCAliasAnalysis::ID = 0;
749 INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
750 "ObjC-ARC-Based Alias Analysis", false, true, false)
752 ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
753 return new ObjCARCAliasAnalysis();
757 ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
758 AU.setPreservesAll();
759 AliasAnalysis::getAnalysisUsage(AU);
762 AliasAnalysis::AliasResult
763 ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
765 return AliasAnalysis::alias(LocA, LocB);
767 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
768 // precise alias query.
769 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
770 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
772 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
773 Location(SB, LocB.Size, LocB.TBAATag));
774 if (Result != MayAlias)
777 // If that failed, climb to the underlying object, including climbing through
778 // ObjC-specific no-ops, and try making an imprecise alias query.
779 const Value *UA = GetUnderlyingObjCPtr(SA);
780 const Value *UB = GetUnderlyingObjCPtr(SB);
781 if (UA != SA || UB != SB) {
782 Result = AliasAnalysis::alias(Location(UA), Location(UB));
783 // We can't use MustAlias or PartialAlias results here because
784 // GetUnderlyingObjCPtr may return an offsetted pointer value.
785 if (Result == NoAlias)
789 // If that failed, fail. We don't need to chain here, since that's covered
790 // by the earlier precise query.
795 ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
798 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
800 // First, strip off no-ops, including ObjC-specific no-ops, and try making
801 // a precise alias query.
802 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
803 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
807 // If that failed, climb to the underlying object, including climbing through
808 // ObjC-specific no-ops, and try making an imprecise alias query.
809 const Value *U = GetUnderlyingObjCPtr(S);
811 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
813 // If that failed, fail. We don't need to chain here, since that's covered
814 // by the earlier precise query.
818 AliasAnalysis::ModRefBehavior
819 ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
820 // We have nothing to do. Just chain to the next AliasAnalysis.
821 return AliasAnalysis::getModRefBehavior(CS);
824 AliasAnalysis::ModRefBehavior
825 ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
827 return AliasAnalysis::getModRefBehavior(F);
829 switch (GetFunctionClass(F)) {
831 return DoesNotAccessMemory;
836 return AliasAnalysis::getModRefBehavior(F);
839 AliasAnalysis::ModRefResult
840 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
842 return AliasAnalysis::getModRefInfo(CS, Loc);
844 switch (GetBasicInstructionClass(CS.getInstruction())) {
848 case IC_AutoreleaseRV:
850 case IC_AutoreleasepoolPush:
851 case IC_FusedRetainAutorelease:
852 case IC_FusedRetainAutoreleaseRV:
853 // These functions don't access any memory visible to the compiler.
854 // Note that this doesn't include objc_retainBlock, because it updates
855 // pointers when it copies block data.
861 return AliasAnalysis::getModRefInfo(CS, Loc);
864 AliasAnalysis::ModRefResult
865 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
866 ImmutableCallSite CS2) {
867 // TODO: Theoretically we could check for dependencies between objc_* calls
868 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
869 return AliasAnalysis::getModRefInfo(CS1, CS2);
874 /// \defgroup ARCExpansion Early ARC Optimizations.
877 #include "llvm/Support/InstIterator.h"
878 #include "llvm/Transforms/Scalar.h"
881 /// \brief Early ARC transformations.
882 class ObjCARCExpand : public FunctionPass {
883 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
884 virtual bool doInitialization(Module &M);
885 virtual bool runOnFunction(Function &F);
887 /// A flag indicating whether this optimization pass should run.
892 ObjCARCExpand() : FunctionPass(ID) {
893 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
898 char ObjCARCExpand::ID = 0;
899 INITIALIZE_PASS(ObjCARCExpand,
900 "objc-arc-expand", "ObjC ARC expansion", false, false)
902 Pass *llvm::createObjCARCExpandPass() {
903 return new ObjCARCExpand();
906 void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
907 AU.setPreservesCFG();
910 bool ObjCARCExpand::doInitialization(Module &M) {
911 Run = ModuleHasARC(M);
915 bool ObjCARCExpand::runOnFunction(Function &F) {
919 // If nothing in the Module uses ARC, don't do anything.
923 bool Changed = false;
925 DEBUG(dbgs() << "ObjCARCExpand: Visiting Function: " << F.getName() << "\n");
927 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
928 Instruction *Inst = &*I;
930 DEBUG(dbgs() << "ObjCARCExpand: Visiting: " << *Inst << "\n");
932 switch (GetBasicInstructionClass(Inst)) {
936 case IC_AutoreleaseRV:
937 case IC_FusedRetainAutorelease:
938 case IC_FusedRetainAutoreleaseRV: {
939 // These calls return their argument verbatim, as a low-level
940 // optimization. However, this makes high-level optimizations
941 // harder. Undo any uses of this optimization that the front-end
942 // emitted here. We'll redo them in the contract pass.
944 Value *Value = cast<CallInst>(Inst)->getArgOperand(0);
945 DEBUG(dbgs() << "ObjCARCExpand: Old = " << *Inst << "\n"
946 " New = " << *Value << "\n");
947 Inst->replaceAllUsesWith(Value);
955 DEBUG(dbgs() << "ObjCARCExpand: Finished List.\n\n");
962 /// \defgroup ARCAPElim ARC Autorelease Pool Elimination.
965 #include "llvm/ADT/STLExtras.h"
966 #include "llvm/IR/Constants.h"
969 /// \brief Autorelease pool elimination.
970 class ObjCARCAPElim : public ModulePass {
971 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
972 virtual bool runOnModule(Module &M);
974 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
975 static bool OptimizeBB(BasicBlock *BB);
979 ObjCARCAPElim() : ModulePass(ID) {
980 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
985 char ObjCARCAPElim::ID = 0;
986 INITIALIZE_PASS(ObjCARCAPElim,
988 "ObjC ARC autorelease pool elimination",
991 Pass *llvm::createObjCARCAPElimPass() {
992 return new ObjCARCAPElim();
995 void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
996 AU.setPreservesCFG();
999 /// Interprocedurally determine if calls made by the given call site can
1000 /// possibly produce autoreleases.
1001 bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
1002 if (const Function *Callee = CS.getCalledFunction()) {
1003 if (Callee->isDeclaration() || Callee->mayBeOverridden())
1005 for (Function::const_iterator I = Callee->begin(), E = Callee->end();
1007 const BasicBlock *BB = I;
1008 for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
1010 if (ImmutableCallSite JCS = ImmutableCallSite(J))
1011 // This recursion depth limit is arbitrary. It's just great
1012 // enough to cover known interesting testcases.
1014 !JCS.onlyReadsMemory() &&
1015 MayAutorelease(JCS, Depth + 1))
1024 bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
1025 bool Changed = false;
1027 Instruction *Push = 0;
1028 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1029 Instruction *Inst = I++;
1030 switch (GetBasicInstructionClass(Inst)) {
1031 case IC_AutoreleasepoolPush:
1034 case IC_AutoreleasepoolPop:
1035 // If this pop matches a push and nothing in between can autorelease,
1037 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
1039 DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop "
1040 "autorelease pair:\n"
1041 " Pop: " << *Inst << "\n"
1042 << " Push: " << *Push << "\n");
1043 Inst->eraseFromParent();
1044 Push->eraseFromParent();
1049 if (MayAutorelease(ImmutableCallSite(Inst)))
1060 bool ObjCARCAPElim::runOnModule(Module &M) {
1064 // If nothing in the Module uses ARC, don't do anything.
1065 if (!ModuleHasARC(M))
1068 // Find the llvm.global_ctors variable, as the first step in
1069 // identifying the global constructors. In theory, unnecessary autorelease
1070 // pools could occur anywhere, but in practice it's pretty rare. Global
1071 // ctors are a place where autorelease pools get inserted automatically,
1072 // so it's pretty common for them to be unnecessary, and it's pretty
1073 // profitable to eliminate them.
1074 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1078 assert(GV->hasDefinitiveInitializer() &&
1079 "llvm.global_ctors is uncooperative!");
1081 bool Changed = false;
1083 // Dig the constructor functions out of GV's initializer.
1084 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1085 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1088 // llvm.global_ctors is an array of pairs where the second members
1089 // are constructor functions.
1090 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1091 // If the user used a constructor function with the wrong signature and
1092 // it got bitcasted or whatever, look the other way.
1095 // Only look at function definitions.
1096 if (F->isDeclaration())
1098 // Only look at functions with one basic block.
1099 if (llvm::next(F->begin()) != F->end())
1101 // Ok, a single-block constructor function definition. Try to optimize it.
1102 Changed |= OptimizeBB(F->begin());
1110 /// \defgroup ARCOpt ARC Optimization.
1113 // TODO: On code like this:
1116 // stuff_that_cannot_release()
1117 // objc_autorelease(%x)
1118 // stuff_that_cannot_release()
1120 // stuff_that_cannot_release()
1121 // objc_autorelease(%x)
1123 // The second retain and autorelease can be deleted.
1125 // TODO: It should be possible to delete
1126 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
1127 // pairs if nothing is actually autoreleased between them. Also, autorelease
1128 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1129 // after inlining) can be turned into plain release calls.
1131 // TODO: Critical-edge splitting. If the optimial insertion point is
1132 // a critical edge, the current algorithm has to fail, because it doesn't
1133 // know how to split edges. It should be possible to make the optimizer
1134 // think in terms of edges, rather than blocks, and then split critical
1137 // TODO: OptimizeSequences could generalized to be Interprocedural.
1139 // TODO: Recognize that a bunch of other objc runtime calls have
1140 // non-escaping arguments and non-releasing arguments, and may be
1141 // non-autoreleasing.
1143 // TODO: Sink autorelease calls as far as possible. Unfortunately we
1144 // usually can't sink them past other calls, which would be the main
1145 // case where it would be useful.
1147 // TODO: The pointer returned from objc_loadWeakRetained is retained.
1149 // TODO: Delete release+retain pairs (rare).
1151 #include "llvm/ADT/SmallPtrSet.h"
1152 #include "llvm/ADT/Statistic.h"
1153 #include "llvm/IR/LLVMContext.h"
1154 #include "llvm/Support/CFG.h"
1156 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1157 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1158 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1159 STATISTIC(NumRets, "Number of return value forwarding "
1160 "retain+autoreleaes eliminated");
1161 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1162 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1165 /// \brief This is similar to BasicAliasAnalysis, and it uses many of the same
1166 /// techniques, except it uses special ObjC-specific reasoning about pointer
1168 class ProvenanceAnalysis {
1171 typedef std::pair<const Value *, const Value *> ValuePairTy;
1172 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1173 CachedResultsTy CachedResults;
1175 bool relatedCheck(const Value *A, const Value *B);
1176 bool relatedSelect(const SelectInst *A, const Value *B);
1177 bool relatedPHI(const PHINode *A, const Value *B);
1179 void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1180 ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1183 ProvenanceAnalysis() {}
1185 void setAA(AliasAnalysis *aa) { AA = aa; }
1187 AliasAnalysis *getAA() const { return AA; }
1189 bool related(const Value *A, const Value *B);
1192 CachedResults.clear();
1197 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1198 // If the values are Selects with the same condition, we can do a more precise
1199 // check: just check for relations between the values on corresponding arms.
1200 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
1201 if (A->getCondition() == SB->getCondition())
1202 return related(A->getTrueValue(), SB->getTrueValue()) ||
1203 related(A->getFalseValue(), SB->getFalseValue());
1205 // Check both arms of the Select node individually.
1206 return related(A->getTrueValue(), B) ||
1207 related(A->getFalseValue(), B);
1210 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1211 // If the values are PHIs in the same block, we can do a more precise as well
1212 // as efficient check: just check for relations between the values on
1213 // corresponding edges.
1214 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1215 if (PNB->getParent() == A->getParent()) {
1216 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1217 if (related(A->getIncomingValue(i),
1218 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1223 // Check each unique source of the PHI node against B.
1224 SmallPtrSet<const Value *, 4> UniqueSrc;
1225 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1226 const Value *PV1 = A->getIncomingValue(i);
1227 if (UniqueSrc.insert(PV1) && related(PV1, B))
1231 // All of the arms checked out.
1235 /// Test if the value of P, or any value covered by its provenance, is ever
1236 /// stored within the function (not counting callees).
1237 static bool isStoredObjCPointer(const Value *P) {
1238 SmallPtrSet<const Value *, 8> Visited;
1239 SmallVector<const Value *, 8> Worklist;
1240 Worklist.push_back(P);
1243 P = Worklist.pop_back_val();
1244 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1246 const User *Ur = *UI;
1247 if (isa<StoreInst>(Ur)) {
1248 if (UI.getOperandNo() == 0)
1249 // The pointer is stored.
1251 // The pointed is stored through.
1254 if (isa<CallInst>(Ur))
1255 // The pointer is passed as an argument, ignore this.
1257 if (isa<PtrToIntInst>(P))
1258 // Assume the worst.
1260 if (Visited.insert(Ur))
1261 Worklist.push_back(Ur);
1263 } while (!Worklist.empty());
1265 // Everything checked out.
1269 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1270 // Skip past provenance pass-throughs.
1271 A = GetUnderlyingObjCPtr(A);
1272 B = GetUnderlyingObjCPtr(B);
1278 // Ask regular AliasAnalysis, for a first approximation.
1279 switch (AA->alias(A, B)) {
1280 case AliasAnalysis::NoAlias:
1282 case AliasAnalysis::MustAlias:
1283 case AliasAnalysis::PartialAlias:
1285 case AliasAnalysis::MayAlias:
1289 bool AIsIdentified = IsObjCIdentifiedObject(A);
1290 bool BIsIdentified = IsObjCIdentifiedObject(B);
1292 // An ObjC-Identified object can't alias a load if it is never locally stored.
1293 if (AIsIdentified) {
1294 // Check for an obvious escape.
1295 if (isa<LoadInst>(B))
1296 return isStoredObjCPointer(A);
1297 if (BIsIdentified) {
1298 // Check for an obvious escape.
1299 if (isa<LoadInst>(A))
1300 return isStoredObjCPointer(B);
1301 // Both pointers are identified and escapes aren't an evident problem.
1304 } else if (BIsIdentified) {
1305 // Check for an obvious escape.
1306 if (isa<LoadInst>(A))
1307 return isStoredObjCPointer(B);
1310 // Special handling for PHI and Select.
1311 if (const PHINode *PN = dyn_cast<PHINode>(A))
1312 return relatedPHI(PN, B);
1313 if (const PHINode *PN = dyn_cast<PHINode>(B))
1314 return relatedPHI(PN, A);
1315 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1316 return relatedSelect(S, B);
1317 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1318 return relatedSelect(S, A);
1324 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1325 // Begin by inserting a conservative value into the map. If the insertion
1326 // fails, we have the answer already. If it succeeds, leave it there until we
1327 // compute the real answer to guard against recursive queries.
1328 if (A > B) std::swap(A, B);
1329 std::pair<CachedResultsTy::iterator, bool> Pair =
1330 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1332 return Pair.first->second;
1334 bool Result = relatedCheck(A, B);
1335 CachedResults[ValuePairTy(A, B)] = Result;
1342 /// \brief A sequence of states that a pointer may go through in which an
1343 /// objc_retain and objc_release are actually needed.
1346 S_Retain, ///< objc_retain(x)
1347 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1348 S_Use, ///< any use of x
1349 S_Stop, ///< like S_Release, but code motion is stopped
1350 S_Release, ///< objc_release(x)
1351 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1355 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1359 if (A == S_None || B == S_None)
1362 if (A > B) std::swap(A, B);
1364 // Choose the side which is further along in the sequence.
1365 if ((A == S_Retain || A == S_CanRelease) &&
1366 (B == S_CanRelease || B == S_Use))
1369 // Choose the side which is further along in the sequence.
1370 if ((A == S_Use || A == S_CanRelease) &&
1371 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
1373 // If both sides are releases, choose the more conservative one.
1374 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1376 if (A == S_Release && B == S_MovableRelease)
1384 /// \brief Unidirectional information about either a
1385 /// retain-decrement-use-release sequence or release-use-decrement-retain
1386 /// reverese sequence.
1388 /// After an objc_retain, the reference count of the referenced
1389 /// object is known to be positive. Similarly, before an objc_release, the
1390 /// reference count of the referenced object is known to be positive. If
1391 /// there are retain-release pairs in code regions where the retain count
1392 /// is known to be positive, they can be eliminated, regardless of any side
1393 /// effects between them.
1395 /// Also, a retain+release pair nested within another retain+release
1396 /// pair all on the known same pointer value can be eliminated, regardless
1397 /// of any intervening side effects.
1399 /// KnownSafe is true when either of these conditions is satisfied.
1402 /// True if the Calls are objc_retainBlock calls (as opposed to objc_retain
1406 /// True of the objc_release calls are all marked with the "tail" keyword.
1407 bool IsTailCallRelease;
1409 /// If the Calls are objc_release calls and they all have a
1410 /// clang.imprecise_release tag, this is the metadata tag.
1411 MDNode *ReleaseMetadata;
1413 /// For a top-down sequence, the set of objc_retains or
1414 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1415 SmallPtrSet<Instruction *, 2> Calls;
1417 /// The set of optimal insert positions for moving calls in the opposite
1419 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1422 KnownSafe(false), IsRetainBlock(false),
1423 IsTailCallRelease(false),
1424 ReleaseMetadata(0) {}
1430 void RRInfo::clear() {
1432 IsRetainBlock = false;
1433 IsTailCallRelease = false;
1434 ReleaseMetadata = 0;
1436 ReverseInsertPts.clear();
1440 /// \brief This class summarizes several per-pointer runtime properties which
1441 /// are propogated through the flow graph.
1443 /// True if the reference count is known to be incremented.
1444 bool KnownPositiveRefCount;
1446 /// True of we've seen an opportunity for partial RR elimination, such as
1447 /// pushing calls into a CFG triangle or into one side of a CFG diamond.
1450 /// The current position in the sequence.
1454 /// Unidirectional information about the current sequence.
1456 /// TODO: Encapsulate this better.
1459 PtrState() : KnownPositiveRefCount(false), Partial(false),
1462 void SetKnownPositiveRefCount() {
1463 KnownPositiveRefCount = true;
1466 void ClearRefCount() {
1467 KnownPositiveRefCount = false;
1470 bool IsKnownIncremented() const {
1471 return KnownPositiveRefCount;
1474 void SetSeq(Sequence NewSeq) {
1478 Sequence GetSeq() const {
1482 void ClearSequenceProgress() {
1483 ResetSequenceProgress(S_None);
1486 void ResetSequenceProgress(Sequence NewSeq) {
1492 void Merge(const PtrState &Other, bool TopDown);
1497 PtrState::Merge(const PtrState &Other, bool TopDown) {
1498 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1499 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
1501 // We can't merge a plain objc_retain with an objc_retainBlock.
1502 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1505 // If we're not in a sequence (anymore), drop all associated state.
1506 if (Seq == S_None) {
1509 } else if (Partial || Other.Partial) {
1510 // If we're doing a merge on a path that's previously seen a partial
1511 // merge, conservatively drop the sequence, to avoid doing partial
1512 // RR elimination. If the branch predicates for the two merge differ,
1513 // mixing them is unsafe.
1514 ClearSequenceProgress();
1516 // Conservatively merge the ReleaseMetadata information.
1517 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1518 RRI.ReleaseMetadata = 0;
1520 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
1521 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1522 Other.RRI.IsTailCallRelease;
1523 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1525 // Merge the insert point sets. If there are any differences,
1526 // that makes this a partial merge.
1527 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
1528 for (SmallPtrSet<Instruction *, 2>::const_iterator
1529 I = Other.RRI.ReverseInsertPts.begin(),
1530 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1531 Partial |= RRI.ReverseInsertPts.insert(*I);
1536 /// \brief Per-BasicBlock state.
1538 /// The number of unique control paths from the entry which can reach this
1540 unsigned TopDownPathCount;
1542 /// The number of unique control paths to exits from this block.
1543 unsigned BottomUpPathCount;
1545 /// A type for PerPtrTopDown and PerPtrBottomUp.
1546 typedef MapVector<const Value *, PtrState> MapTy;
1548 /// The top-down traversal uses this to record information known about a
1549 /// pointer at the bottom of each block.
1550 MapTy PerPtrTopDown;
1552 /// The bottom-up traversal uses this to record information known about a
1553 /// pointer at the top of each block.
1554 MapTy PerPtrBottomUp;
1556 /// Effective predecessors of the current block ignoring ignorable edges and
1557 /// ignored backedges.
1558 SmallVector<BasicBlock *, 2> Preds;
1559 /// Effective successors of the current block ignoring ignorable edges and
1560 /// ignored backedges.
1561 SmallVector<BasicBlock *, 2> Succs;
1564 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1566 typedef MapTy::iterator ptr_iterator;
1567 typedef MapTy::const_iterator ptr_const_iterator;
1569 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1570 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1571 ptr_const_iterator top_down_ptr_begin() const {
1572 return PerPtrTopDown.begin();
1574 ptr_const_iterator top_down_ptr_end() const {
1575 return PerPtrTopDown.end();
1578 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1579 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1580 ptr_const_iterator bottom_up_ptr_begin() const {
1581 return PerPtrBottomUp.begin();
1583 ptr_const_iterator bottom_up_ptr_end() const {
1584 return PerPtrBottomUp.end();
1587 /// Mark this block as being an entry block, which has one path from the
1588 /// entry by definition.
1589 void SetAsEntry() { TopDownPathCount = 1; }
1591 /// Mark this block as being an exit block, which has one path to an exit by
1593 void SetAsExit() { BottomUpPathCount = 1; }
1595 PtrState &getPtrTopDownState(const Value *Arg) {
1596 return PerPtrTopDown[Arg];
1599 PtrState &getPtrBottomUpState(const Value *Arg) {
1600 return PerPtrBottomUp[Arg];
1603 void clearBottomUpPointers() {
1604 PerPtrBottomUp.clear();
1607 void clearTopDownPointers() {
1608 PerPtrTopDown.clear();
1611 void InitFromPred(const BBState &Other);
1612 void InitFromSucc(const BBState &Other);
1613 void MergePred(const BBState &Other);
1614 void MergeSucc(const BBState &Other);
1616 /// Return the number of possible unique paths from an entry to an exit
1617 /// which pass through this block. This is only valid after both the
1618 /// top-down and bottom-up traversals are complete.
1619 unsigned GetAllPathCount() const {
1620 assert(TopDownPathCount != 0);
1621 assert(BottomUpPathCount != 0);
1622 return TopDownPathCount * BottomUpPathCount;
1625 // Specialized CFG utilities.
1626 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
1627 edge_iterator pred_begin() { return Preds.begin(); }
1628 edge_iterator pred_end() { return Preds.end(); }
1629 edge_iterator succ_begin() { return Succs.begin(); }
1630 edge_iterator succ_end() { return Succs.end(); }
1632 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1633 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1635 bool isExit() const { return Succs.empty(); }
1639 void BBState::InitFromPred(const BBState &Other) {
1640 PerPtrTopDown = Other.PerPtrTopDown;
1641 TopDownPathCount = Other.TopDownPathCount;
1644 void BBState::InitFromSucc(const BBState &Other) {
1645 PerPtrBottomUp = Other.PerPtrBottomUp;
1646 BottomUpPathCount = Other.BottomUpPathCount;
1649 /// The top-down traversal uses this to merge information about predecessors to
1650 /// form the initial state for a new block.
1651 void BBState::MergePred(const BBState &Other) {
1652 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1653 // loop backedge. Loop backedges are special.
1654 TopDownPathCount += Other.TopDownPathCount;
1656 // Check for overflow. If we have overflow, fall back to conservative
1658 if (TopDownPathCount < Other.TopDownPathCount) {
1659 clearTopDownPointers();
1663 // For each entry in the other set, if our set has an entry with the same key,
1664 // merge the entries. Otherwise, copy the entry and merge it with an empty
1666 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1667 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1668 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1669 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1673 // For each entry in our set, if the other set doesn't have an entry with the
1674 // same key, force it to merge with an empty entry.
1675 for (ptr_iterator MI = top_down_ptr_begin(),
1676 ME = top_down_ptr_end(); MI != ME; ++MI)
1677 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1678 MI->second.Merge(PtrState(), /*TopDown=*/true);
1681 /// The bottom-up traversal uses this to merge information about successors to
1682 /// form the initial state for a new block.
1683 void BBState::MergeSucc(const BBState &Other) {
1684 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1685 // loop backedge. Loop backedges are special.
1686 BottomUpPathCount += Other.BottomUpPathCount;
1688 // Check for overflow. If we have overflow, fall back to conservative
1690 if (BottomUpPathCount < Other.BottomUpPathCount) {
1691 clearBottomUpPointers();
1695 // For each entry in the other set, if our set has an entry with the
1696 // same key, merge the entries. Otherwise, copy the entry and merge
1697 // it with an empty entry.
1698 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1699 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1700 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1701 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1705 // For each entry in our set, if the other set doesn't have an entry
1706 // with the same key, force it to merge with an empty entry.
1707 for (ptr_iterator MI = bottom_up_ptr_begin(),
1708 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1709 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1710 MI->second.Merge(PtrState(), /*TopDown=*/false);
1714 /// \brief The main ARC optimization pass.
1715 class ObjCARCOpt : public FunctionPass {
1717 ProvenanceAnalysis PA;
1719 /// A flag indicating whether this optimization pass should run.
1722 /// Declarations for ObjC runtime functions, for use in creating calls to
1723 /// them. These are initialized lazily to avoid cluttering up the Module
1724 /// with unused declarations.
1726 /// Declaration for ObjC runtime function
1727 /// objc_retainAutoreleasedReturnValue.
1728 Constant *RetainRVCallee;
1729 /// Declaration for ObjC runtime function objc_autoreleaseReturnValue.
1730 Constant *AutoreleaseRVCallee;
1731 /// Declaration for ObjC runtime function objc_release.
1732 Constant *ReleaseCallee;
1733 /// Declaration for ObjC runtime function objc_retain.
1734 Constant *RetainCallee;
1735 /// Declaration for ObjC runtime function objc_retainBlock.
1736 Constant *RetainBlockCallee;
1737 /// Declaration for ObjC runtime function objc_autorelease.
1738 Constant *AutoreleaseCallee;
1740 /// Flags which determine whether each of the interesting runtine functions
1741 /// is in fact used in the current function.
1742 unsigned UsedInThisFunction;
1744 /// The Metadata Kind for clang.imprecise_release metadata.
1745 unsigned ImpreciseReleaseMDKind;
1747 /// The Metadata Kind for clang.arc.copy_on_escape metadata.
1748 unsigned CopyOnEscapeMDKind;
1750 /// The Metadata Kind for clang.arc.no_objc_arc_exceptions metadata.
1751 unsigned NoObjCARCExceptionsMDKind;
1753 Constant *getRetainRVCallee(Module *M);
1754 Constant *getAutoreleaseRVCallee(Module *M);
1755 Constant *getReleaseCallee(Module *M);
1756 Constant *getRetainCallee(Module *M);
1757 Constant *getRetainBlockCallee(Module *M);
1758 Constant *getAutoreleaseCallee(Module *M);
1760 bool IsRetainBlockOptimizable(const Instruction *Inst);
1762 void OptimizeRetainCall(Function &F, Instruction *Retain);
1763 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1764 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1765 InstructionClass &Class);
1766 void OptimizeIndividualCalls(Function &F);
1768 void CheckForCFGHazards(const BasicBlock *BB,
1769 DenseMap<const BasicBlock *, BBState> &BBStates,
1770 BBState &MyStates) const;
1771 bool VisitInstructionBottomUp(Instruction *Inst,
1773 MapVector<Value *, RRInfo> &Retains,
1775 bool VisitBottomUp(BasicBlock *BB,
1776 DenseMap<const BasicBlock *, BBState> &BBStates,
1777 MapVector<Value *, RRInfo> &Retains);
1778 bool VisitInstructionTopDown(Instruction *Inst,
1779 DenseMap<Value *, RRInfo> &Releases,
1781 bool VisitTopDown(BasicBlock *BB,
1782 DenseMap<const BasicBlock *, BBState> &BBStates,
1783 DenseMap<Value *, RRInfo> &Releases);
1784 bool Visit(Function &F,
1785 DenseMap<const BasicBlock *, BBState> &BBStates,
1786 MapVector<Value *, RRInfo> &Retains,
1787 DenseMap<Value *, RRInfo> &Releases);
1789 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1790 MapVector<Value *, RRInfo> &Retains,
1791 DenseMap<Value *, RRInfo> &Releases,
1792 SmallVectorImpl<Instruction *> &DeadInsts,
1795 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1796 MapVector<Value *, RRInfo> &Retains,
1797 DenseMap<Value *, RRInfo> &Releases,
1800 void OptimizeWeakCalls(Function &F);
1802 bool OptimizeSequences(Function &F);
1804 void OptimizeReturns(Function &F);
1806 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1807 virtual bool doInitialization(Module &M);
1808 virtual bool runOnFunction(Function &F);
1809 virtual void releaseMemory();
1813 ObjCARCOpt() : FunctionPass(ID) {
1814 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1819 char ObjCARCOpt::ID = 0;
1820 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1821 "objc-arc", "ObjC ARC optimization", false, false)
1822 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1823 INITIALIZE_PASS_END(ObjCARCOpt,
1824 "objc-arc", "ObjC ARC optimization", false, false)
1826 Pass *llvm::createObjCARCOptPass() {
1827 return new ObjCARCOpt();
1830 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1831 AU.addRequired<ObjCARCAliasAnalysis>();
1832 AU.addRequired<AliasAnalysis>();
1833 // ARC optimization doesn't currently split critical edges.
1834 AU.setPreservesCFG();
1837 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1838 // Without the magic metadata tag, we have to assume this might be an
1839 // objc_retainBlock call inserted to convert a block pointer to an id,
1840 // in which case it really is needed.
1841 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1844 // If the pointer "escapes" (not including being used in a call),
1845 // the copy may be needed.
1846 if (DoesObjCBlockEscape(Inst))
1849 // Otherwise, it's not needed.
1853 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1854 if (!RetainRVCallee) {
1855 LLVMContext &C = M->getContext();
1856 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1857 Type *Params[] = { I8X };
1858 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1859 AttributeSet Attribute =
1860 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1861 Attribute::get(C, Attribute::NoUnwind));
1863 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1866 return RetainRVCallee;
1869 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1870 if (!AutoreleaseRVCallee) {
1871 LLVMContext &C = M->getContext();
1872 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1873 Type *Params[] = { I8X };
1874 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1875 AttributeSet Attribute =
1876 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1877 Attribute::get(C, Attribute::NoUnwind));
1878 AutoreleaseRVCallee =
1879 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1882 return AutoreleaseRVCallee;
1885 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1886 if (!ReleaseCallee) {
1887 LLVMContext &C = M->getContext();
1888 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1889 AttributeSet Attribute =
1890 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1891 Attribute::get(C, Attribute::NoUnwind));
1893 M->getOrInsertFunction(
1895 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1898 return ReleaseCallee;
1901 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1902 if (!RetainCallee) {
1903 LLVMContext &C = M->getContext();
1904 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1905 AttributeSet Attribute =
1906 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1907 Attribute::get(C, Attribute::NoUnwind));
1909 M->getOrInsertFunction(
1911 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1914 return RetainCallee;
1917 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1918 if (!RetainBlockCallee) {
1919 LLVMContext &C = M->getContext();
1920 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1921 // objc_retainBlock is not nounwind because it calls user copy constructors
1922 // which could theoretically throw.
1924 M->getOrInsertFunction(
1926 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1929 return RetainBlockCallee;
1932 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1933 if (!AutoreleaseCallee) {
1934 LLVMContext &C = M->getContext();
1935 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1936 AttributeSet Attribute =
1937 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1938 Attribute::get(C, Attribute::NoUnwind));
1940 M->getOrInsertFunction(
1942 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1945 return AutoreleaseCallee;
1948 /// Test whether the given value is possible a reference-counted pointer,
1949 /// including tests which utilize AliasAnalysis.
1950 static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
1951 // First make the rudimentary check.
1952 if (!IsPotentialUse(Op))
1955 // Objects in constant memory are not reference-counted.
1956 if (AA.pointsToConstantMemory(Op))
1959 // Pointers in constant memory are not pointing to reference-counted objects.
1960 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1961 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1964 // Otherwise assume the worst.
1968 /// Test whether the given instruction can result in a reference count
1969 /// modification (positive or negative) for the pointer's object.
1971 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1972 ProvenanceAnalysis &PA, InstructionClass Class) {
1974 case IC_Autorelease:
1975 case IC_AutoreleaseRV:
1977 // These operations never directly modify a reference count.
1982 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1983 assert(CS && "Only calls can alter reference counts!");
1985 // See if AliasAnalysis can help us with the call.
1986 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1987 if (AliasAnalysis::onlyReadsMemory(MRB))
1989 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1990 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1992 const Value *Op = *I;
1993 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
1999 // Assume the worst.
2003 /// Test whether the given instruction can "use" the given pointer's object in a
2004 /// way that requires the reference count to be positive.
2006 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
2007 InstructionClass Class) {
2008 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
2009 if (Class == IC_Call)
2012 // Consider various instructions which may have pointer arguments which are
2014 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
2015 // Comparing a pointer with null, or any other constant, isn't really a use,
2016 // because we don't care what the pointer points to, or about the values
2017 // of any other dynamic reference-counted pointers.
2018 if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
2020 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
2021 // For calls, just check the arguments (and not the callee operand).
2022 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
2023 OE = CS.arg_end(); OI != OE; ++OI) {
2024 const Value *Op = *OI;
2025 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
2029 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
2030 // Special-case stores, because we don't care about the stored value, just
2031 // the store address.
2032 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
2033 // If we can't tell what the underlying object was, assume there is a
2035 return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
2038 // Check each operand for a match.
2039 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
2041 const Value *Op = *OI;
2042 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
2048 /// Test whether the given instruction can autorelease any pointer or cause an
2049 /// autoreleasepool pop.
2051 CanInterruptRV(InstructionClass Class) {
2053 case IC_AutoreleasepoolPop:
2056 case IC_Autorelease:
2057 case IC_AutoreleaseRV:
2058 case IC_FusedRetainAutorelease:
2059 case IC_FusedRetainAutoreleaseRV:
2067 /// \enum DependenceKind
2068 /// \brief Defines different dependence kinds among various ARC constructs.
2070 /// There are several kinds of dependence-like concepts in use here.
2072 enum DependenceKind {
2073 NeedsPositiveRetainCount,
2074 AutoreleasePoolBoundary,
2075 CanChangeRetainCount,
2076 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
2077 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
2078 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
2082 /// Test if there can be dependencies on Inst through Arg. This function only
2083 /// tests dependencies relevant for removing pairs of calls.
2085 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2086 ProvenanceAnalysis &PA) {
2087 // If we've reached the definition of Arg, stop.
2092 case NeedsPositiveRetainCount: {
2093 InstructionClass Class = GetInstructionClass(Inst);
2095 case IC_AutoreleasepoolPop:
2096 case IC_AutoreleasepoolPush:
2100 return CanUse(Inst, Arg, PA, Class);
2104 case AutoreleasePoolBoundary: {
2105 InstructionClass Class = GetInstructionClass(Inst);
2107 case IC_AutoreleasepoolPop:
2108 case IC_AutoreleasepoolPush:
2109 // These mark the end and begin of an autorelease pool scope.
2112 // Nothing else does this.
2117 case CanChangeRetainCount: {
2118 InstructionClass Class = GetInstructionClass(Inst);
2120 case IC_AutoreleasepoolPop:
2121 // Conservatively assume this can decrement any count.
2123 case IC_AutoreleasepoolPush:
2127 return CanAlterRefCount(Inst, Arg, PA, Class);
2131 case RetainAutoreleaseDep:
2132 switch (GetBasicInstructionClass(Inst)) {
2133 case IC_AutoreleasepoolPop:
2134 case IC_AutoreleasepoolPush:
2135 // Don't merge an objc_autorelease with an objc_retain inside a different
2136 // autoreleasepool scope.
2140 // Check for a retain of the same pointer for merging.
2141 return GetObjCArg(Inst) == Arg;
2143 // Nothing else matters for objc_retainAutorelease formation.
2147 case RetainAutoreleaseRVDep: {
2148 InstructionClass Class = GetBasicInstructionClass(Inst);
2152 // Check for a retain of the same pointer for merging.
2153 return GetObjCArg(Inst) == Arg;
2155 // Anything that can autorelease interrupts
2156 // retainAutoreleaseReturnValue formation.
2157 return CanInterruptRV(Class);
2162 return CanInterruptRV(GetBasicInstructionClass(Inst));
2165 llvm_unreachable("Invalid dependence flavor");
2168 /// Walk up the CFG from StartPos (which is in StartBB) and find local and
2169 /// non-local dependencies on Arg.
2171 /// TODO: Cache results?
2173 FindDependencies(DependenceKind Flavor,
2175 BasicBlock *StartBB, Instruction *StartInst,
2176 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2177 SmallPtrSet<const BasicBlock *, 4> &Visited,
2178 ProvenanceAnalysis &PA) {
2179 BasicBlock::iterator StartPos = StartInst;
2181 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2182 Worklist.push_back(std::make_pair(StartBB, StartPos));
2184 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2185 Worklist.pop_back_val();
2186 BasicBlock *LocalStartBB = Pair.first;
2187 BasicBlock::iterator LocalStartPos = Pair.second;
2188 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2190 if (LocalStartPos == StartBBBegin) {
2191 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2193 // If we've reached the function entry, produce a null dependence.
2194 DependingInstructions.insert(0);
2196 // Add the predecessors to the worklist.
2198 BasicBlock *PredBB = *PI;
2199 if (Visited.insert(PredBB))
2200 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2201 } while (++PI != PE);
2205 Instruction *Inst = --LocalStartPos;
2206 if (Depends(Flavor, Inst, Arg, PA)) {
2207 DependingInstructions.insert(Inst);
2211 } while (!Worklist.empty());
2213 // Determine whether the original StartBB post-dominates all of the blocks we
2214 // visited. If not, insert a sentinal indicating that most optimizations are
2216 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2217 E = Visited.end(); I != E; ++I) {
2218 const BasicBlock *BB = *I;
2221 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2222 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2223 const BasicBlock *Succ = *SI;
2224 if (Succ != StartBB && !Visited.count(Succ)) {
2225 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2232 static bool isNullOrUndef(const Value *V) {
2233 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2236 static bool isNoopInstruction(const Instruction *I) {
2237 return isa<BitCastInst>(I) ||
2238 (isa<GetElementPtrInst>(I) &&
2239 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2242 /// Turn objc_retain into objc_retainAutoreleasedReturnValue if the operand is a
2245 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
2246 ImmutableCallSite CS(GetObjCArg(Retain));
2247 const Instruction *Call = CS.getInstruction();
2249 if (Call->getParent() != Retain->getParent()) return;
2251 // Check that the call is next to the retain.
2252 BasicBlock::const_iterator I = Call;
2254 while (isNoopInstruction(I)) ++I;
2258 // Turn it to an objc_retainAutoreleasedReturnValue..
2262 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
2263 "objc_retain => objc_retainAutoreleasedReturnValue"
2264 " since the operand is a return value.\n"
2266 << *Retain << "\n");
2268 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2270 DEBUG(dbgs() << " New: "
2271 << *Retain << "\n");
2274 /// Turn objc_retainAutoreleasedReturnValue into objc_retain if the operand is
2275 /// not a return value. Or, if it can be paired with an
2276 /// objc_autoreleaseReturnValue, delete the pair and return true.
2278 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
2279 // Check for the argument being from an immediately preceding call or invoke.
2280 const Value *Arg = GetObjCArg(RetainRV);
2281 ImmutableCallSite CS(Arg);
2282 if (const Instruction *Call = CS.getInstruction()) {
2283 if (Call->getParent() == RetainRV->getParent()) {
2284 BasicBlock::const_iterator I = Call;
2286 while (isNoopInstruction(I)) ++I;
2287 if (&*I == RetainRV)
2289 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
2290 BasicBlock *RetainRVParent = RetainRV->getParent();
2291 if (II->getNormalDest() == RetainRVParent) {
2292 BasicBlock::const_iterator I = RetainRVParent->begin();
2293 while (isNoopInstruction(I)) ++I;
2294 if (&*I == RetainRV)
2300 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2301 // pointer. In this case, we can delete the pair.
2302 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2304 do --I; while (I != Begin && isNoopInstruction(I));
2305 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2306 GetObjCArg(I) == Arg) {
2310 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
2311 << " Erasing " << *RetainRV
2314 EraseInstruction(I);
2315 EraseInstruction(RetainRV);
2320 // Turn it to a plain objc_retain.
2324 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
2325 "objc_retainAutoreleasedReturnValue => "
2326 "objc_retain since the operand is not a return value.\n"
2328 << *RetainRV << "\n");
2330 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2332 DEBUG(dbgs() << " New: "
2333 << *RetainRV << "\n");
2338 /// Turn objc_autoreleaseReturnValue into objc_autorelease if the result is not
2339 /// used as a return value.
2341 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
2342 InstructionClass &Class) {
2343 // Check for a return of the pointer value.
2344 const Value *Ptr = GetObjCArg(AutoreleaseRV);
2345 SmallVector<const Value *, 2> Users;
2346 Users.push_back(Ptr);
2348 Ptr = Users.pop_back_val();
2349 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2351 const User *I = *UI;
2352 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2354 if (isa<BitCastInst>(I))
2357 } while (!Users.empty());
2362 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
2363 "objc_autoreleaseReturnValue => "
2364 "objc_autorelease since its operand is not used as a return "
2367 << *AutoreleaseRV << "\n");
2369 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
2371 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2372 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
2373 Class = IC_Autorelease;
2375 DEBUG(dbgs() << " New: "
2376 << *AutoreleaseRV << "\n");
2380 /// Visit each call, one at a time, and make simplifications without doing any
2381 /// additional analysis.
2382 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2383 // Reset all the flags in preparation for recomputing them.
2384 UsedInThisFunction = 0;
2386 // Visit all objc_* calls in F.
2387 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2388 Instruction *Inst = &*I++;
2390 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: " <<
2393 InstructionClass Class = GetBasicInstructionClass(Inst);
2398 // Delete no-op casts. These function calls have special semantics, but
2399 // the semantics are entirely implemented via lowering in the front-end,
2400 // so by the time they reach the optimizer, they are just no-op calls
2401 // which return their argument.
2403 // There are gray areas here, as the ability to cast reference-counted
2404 // pointers to raw void* and back allows code to break ARC assumptions,
2405 // however these are currently considered to be unimportant.
2409 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
2410 " " << *Inst << "\n");
2411 EraseInstruction(Inst);
2414 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2417 case IC_LoadWeakRetained:
2419 case IC_DestroyWeak: {
2420 CallInst *CI = cast<CallInst>(Inst);
2421 if (isNullOrUndef(CI->getArgOperand(0))) {
2423 Type *Ty = CI->getArgOperand(0)->getType();
2424 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2425 Constant::getNullValue(Ty),
2427 llvm::Value *NewValue = UndefValue::get(CI->getType());
2428 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2429 "pointer-to-weak-pointer is undefined behavior.\n"
2433 CI->replaceAllUsesWith(NewValue);
2434 CI->eraseFromParent();
2441 CallInst *CI = cast<CallInst>(Inst);
2442 if (isNullOrUndef(CI->getArgOperand(0)) ||
2443 isNullOrUndef(CI->getArgOperand(1))) {
2445 Type *Ty = CI->getArgOperand(0)->getType();
2446 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2447 Constant::getNullValue(Ty),
2450 llvm::Value *NewValue = UndefValue::get(CI->getType());
2451 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2452 "pointer-to-weak-pointer is undefined behavior.\n"
2457 CI->replaceAllUsesWith(NewValue);
2458 CI->eraseFromParent();
2464 OptimizeRetainCall(F, Inst);
2467 if (OptimizeRetainRVCall(F, Inst))
2470 case IC_AutoreleaseRV:
2471 OptimizeAutoreleaseRVCall(F, Inst, Class);
2475 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2476 if (IsAutorelease(Class) && Inst->use_empty()) {
2477 CallInst *Call = cast<CallInst>(Inst);
2478 const Value *Arg = Call->getArgOperand(0);
2479 Arg = FindSingleUseIdentifiedObject(Arg);
2484 // Create the declaration lazily.
2485 LLVMContext &C = Inst->getContext();
2487 CallInst::Create(getReleaseCallee(F.getParent()),
2488 Call->getArgOperand(0), "", Call);
2489 NewCall->setMetadata(ImpreciseReleaseMDKind,
2490 MDNode::get(C, ArrayRef<Value *>()));
2492 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
2493 "objc_autorelease(x) with objc_release(x) since x is "
2494 "otherwise unused.\n"
2495 " Old: " << *Call <<
2499 EraseInstruction(Call);
2505 // For functions which can never be passed stack arguments, add
2507 if (IsAlwaysTail(Class)) {
2509 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
2510 " to function since it can never be passed stack args: " << *Inst <<
2512 cast<CallInst>(Inst)->setTailCall();
2515 // Ensure that functions that can never have a "tail" keyword due to the
2516 // semantics of ARC truly do not do so.
2517 if (IsNeverTail(Class)) {
2519 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail "
2520 "keyword from function: " << *Inst <<
2522 cast<CallInst>(Inst)->setTailCall(false);
2525 // Set nounwind as needed.
2526 if (IsNoThrow(Class)) {
2528 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
2529 " class. Setting nounwind on: " << *Inst << "\n");
2530 cast<CallInst>(Inst)->setDoesNotThrow();
2533 if (!IsNoopOnNull(Class)) {
2534 UsedInThisFunction |= 1 << Class;
2538 const Value *Arg = GetObjCArg(Inst);
2540 // ARC calls with null are no-ops. Delete them.
2541 if (isNullOrUndef(Arg)) {
2544 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
2545 " null are no-ops. Erasing: " << *Inst << "\n");
2546 EraseInstruction(Inst);
2550 // Keep track of which of retain, release, autorelease, and retain_block
2551 // are actually present in this function.
2552 UsedInThisFunction |= 1 << Class;
2554 // If Arg is a PHI, and one or more incoming values to the
2555 // PHI are null, and the call is control-equivalent to the PHI, and there
2556 // are no relevant side effects between the PHI and the call, the call
2557 // could be pushed up to just those paths with non-null incoming values.
2558 // For now, don't bother splitting critical edges for this.
2559 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2560 Worklist.push_back(std::make_pair(Inst, Arg));
2562 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2566 const PHINode *PN = dyn_cast<PHINode>(Arg);
2569 // Determine if the PHI has any null operands, or any incoming
2571 bool HasNull = false;
2572 bool HasCriticalEdges = false;
2573 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2575 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2576 if (isNullOrUndef(Incoming))
2578 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2579 .getNumSuccessors() != 1) {
2580 HasCriticalEdges = true;
2584 // If we have null operands and no critical edges, optimize.
2585 if (!HasCriticalEdges && HasNull) {
2586 SmallPtrSet<Instruction *, 4> DependingInstructions;
2587 SmallPtrSet<const BasicBlock *, 4> Visited;
2589 // Check that there is nothing that cares about the reference
2590 // count between the call and the phi.
2593 case IC_RetainBlock:
2594 // These can always be moved up.
2597 // These can't be moved across things that care about the retain
2599 FindDependencies(NeedsPositiveRetainCount, Arg,
2600 Inst->getParent(), Inst,
2601 DependingInstructions, Visited, PA);
2603 case IC_Autorelease:
2604 // These can't be moved across autorelease pool scope boundaries.
2605 FindDependencies(AutoreleasePoolBoundary, Arg,
2606 Inst->getParent(), Inst,
2607 DependingInstructions, Visited, PA);
2610 case IC_AutoreleaseRV:
2611 // Don't move these; the RV optimization depends on the autoreleaseRV
2612 // being tail called, and the retainRV being immediately after a call
2613 // (which might still happen if we get lucky with codegen layout, but
2614 // it's not worth taking the chance).
2617 llvm_unreachable("Invalid dependence flavor");
2620 if (DependingInstructions.size() == 1 &&
2621 *DependingInstructions.begin() == PN) {
2624 // Clone the call into each predecessor that has a non-null value.
2625 CallInst *CInst = cast<CallInst>(Inst);
2626 Type *ParamTy = CInst->getArgOperand(0)->getType();
2627 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2629 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2630 if (!isNullOrUndef(Incoming)) {
2631 CallInst *Clone = cast<CallInst>(CInst->clone());
2632 Value *Op = PN->getIncomingValue(i);
2633 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2634 if (Op->getType() != ParamTy)
2635 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2636 Clone->setArgOperand(0, Op);
2637 Clone->insertBefore(InsertPos);
2639 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
2642 "clone at " << *InsertPos << "\n");
2643 Worklist.push_back(std::make_pair(Clone, Incoming));
2646 // Erase the original call.
2647 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
2648 EraseInstruction(CInst);
2652 } while (!Worklist.empty());
2654 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
2657 /// Check for critical edges, loop boundaries, irreducible control flow, or
2658 /// other CFG structures where moving code across the edge would result in it
2659 /// being executed more.
2661 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2662 DenseMap<const BasicBlock *, BBState> &BBStates,
2663 BBState &MyStates) const {
2664 // If any top-down local-use or possible-dec has a succ which is earlier in
2665 // the sequence, forget it.
2666 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
2667 E = MyStates.top_down_ptr_end(); I != E; ++I)
2668 switch (I->second.GetSeq()) {
2671 const Value *Arg = I->first;
2672 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2673 bool SomeSuccHasSame = false;
2674 bool AllSuccsHaveSame = true;
2675 PtrState &S = I->second;
2676 succ_const_iterator SI(TI), SE(TI, false);
2678 // If the terminator is an invoke marked with the
2679 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2680 // ignored, for ARC purposes.
2681 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
2682 DEBUG(dbgs() << "ObjCARCOpt::CheckForCFGHazards: Found an invoke "
2683 "terminator marked with "
2684 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
2689 for (; SI != SE; ++SI) {
2690 Sequence SuccSSeq = S_None;
2691 bool SuccSRRIKnownSafe = false;
2692 // If VisitBottomUp has pointer information for this successor, take
2693 // what we know about it.
2694 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2696 assert(BBI != BBStates.end());
2697 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2698 SuccSSeq = SuccS.GetSeq();
2699 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2702 case S_CanRelease: {
2703 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2704 S.ClearSequenceProgress();
2710 SomeSuccHasSame = true;
2714 case S_MovableRelease:
2715 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2716 AllSuccsHaveSame = false;
2719 llvm_unreachable("bottom-up pointer in retain state!");
2722 // If the state at the other end of any of the successor edges
2723 // matches the current state, require all edges to match. This
2724 // guards against loops in the middle of a sequence.
2725 if (SomeSuccHasSame && !AllSuccsHaveSame)
2726 S.ClearSequenceProgress();
2729 case S_CanRelease: {
2730 const Value *Arg = I->first;
2731 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2732 bool SomeSuccHasSame = false;
2733 bool AllSuccsHaveSame = true;
2734 PtrState &S = I->second;
2735 succ_const_iterator SI(TI), SE(TI, false);
2737 // If the terminator is an invoke marked with the
2738 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2739 // ignored, for ARC purposes.
2740 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
2741 DEBUG(dbgs() << "ObjCARCOpt::CheckForCFGHazards: Found an invoke "
2742 "terminator marked with "
2743 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
2748 for (; SI != SE; ++SI) {
2749 Sequence SuccSSeq = S_None;
2750 bool SuccSRRIKnownSafe = false;
2751 // If VisitBottomUp has pointer information for this successor, take
2752 // what we know about it.
2753 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2755 assert(BBI != BBStates.end());
2756 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2757 SuccSSeq = SuccS.GetSeq();
2758 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2761 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2762 S.ClearSequenceProgress();
2768 SomeSuccHasSame = true;
2772 case S_MovableRelease:
2774 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2775 AllSuccsHaveSame = false;
2778 llvm_unreachable("bottom-up pointer in retain state!");
2781 // If the state at the other end of any of the successor edges
2782 // matches the current state, require all edges to match. This
2783 // guards against loops in the middle of a sequence.
2784 if (SomeSuccHasSame && !AllSuccsHaveSame)
2785 S.ClearSequenceProgress();
2792 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
2794 MapVector<Value *, RRInfo> &Retains,
2795 BBState &MyStates) {
2796 bool NestingDetected = false;
2797 InstructionClass Class = GetInstructionClass(Inst);
2798 const Value *Arg = 0;
2802 Arg = GetObjCArg(Inst);
2804 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2806 // If we see two releases in a row on the same pointer. If so, make
2807 // a note, and we'll cicle back to revisit it after we've
2808 // hopefully eliminated the second release, which may allow us to
2809 // eliminate the first release too.
2810 // Theoretically we could implement removal of nested retain+release
2811 // pairs by making PtrState hold a stack of states, but this is
2812 // simple and avoids adding overhead for the non-nested case.
2813 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
2814 DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested "
2815 "releases (i.e. a release pair)\n");
2816 NestingDetected = true;
2819 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2820 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
2821 S.RRI.ReleaseMetadata = ReleaseMetadata;
2822 S.RRI.KnownSafe = S.IsKnownIncremented();
2823 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2824 S.RRI.Calls.insert(Inst);
2826 S.SetKnownPositiveRefCount();
2829 case IC_RetainBlock:
2830 // An objc_retainBlock call with just a use may need to be kept,
2831 // because it may be copying a block from the stack to the heap.
2832 if (!IsRetainBlockOptimizable(Inst))
2837 Arg = GetObjCArg(Inst);
2839 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2840 S.SetKnownPositiveRefCount();
2842 switch (S.GetSeq()) {
2845 case S_MovableRelease:
2847 S.RRI.ReverseInsertPts.clear();
2850 // Don't do retain+release tracking for IC_RetainRV, because it's
2851 // better to let it remain as the first instruction after a call.
2852 if (Class != IC_RetainRV) {
2853 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2854 Retains[Inst] = S.RRI;
2856 S.ClearSequenceProgress();
2861 llvm_unreachable("bottom-up pointer in retain state!");
2863 return NestingDetected;
2865 case IC_AutoreleasepoolPop:
2866 // Conservatively, clear MyStates for all known pointers.
2867 MyStates.clearBottomUpPointers();
2868 return NestingDetected;
2869 case IC_AutoreleasepoolPush:
2871 // These are irrelevant.
2872 return NestingDetected;
2877 // Consider any other possible effects of this instruction on each
2878 // pointer being tracked.
2879 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2880 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2881 const Value *Ptr = MI->first;
2883 continue; // Handled above.
2884 PtrState &S = MI->second;
2885 Sequence Seq = S.GetSeq();
2887 // Check for possible releases.
2888 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2892 S.SetSeq(S_CanRelease);
2896 case S_MovableRelease:
2901 llvm_unreachable("bottom-up pointer in retain state!");
2905 // Check for possible direct uses.
2908 case S_MovableRelease:
2909 if (CanUse(Inst, Ptr, PA, Class)) {
2910 assert(S.RRI.ReverseInsertPts.empty());
2911 // If this is an invoke instruction, we're scanning it as part of
2912 // one of its successor blocks, since we can't insert code after it
2913 // in its own block, and we don't want to split critical edges.
2914 if (isa<InvokeInst>(Inst))
2915 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2917 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2919 } else if (Seq == S_Release &&
2920 (Class == IC_User || Class == IC_CallOrUser)) {
2921 // Non-movable releases depend on any possible objc pointer use.
2923 assert(S.RRI.ReverseInsertPts.empty());
2924 // As above; handle invoke specially.
2925 if (isa<InvokeInst>(Inst))
2926 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2928 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2932 if (CanUse(Inst, Ptr, PA, Class))
2940 llvm_unreachable("bottom-up pointer in retain state!");
2944 return NestingDetected;
2948 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2949 DenseMap<const BasicBlock *, BBState> &BBStates,
2950 MapVector<Value *, RRInfo> &Retains) {
2951 bool NestingDetected = false;
2952 BBState &MyStates = BBStates[BB];
2954 // Merge the states from each successor to compute the initial state
2955 // for the current block.
2956 BBState::edge_iterator SI(MyStates.succ_begin()),
2957 SE(MyStates.succ_end());
2959 const BasicBlock *Succ = *SI;
2960 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2961 assert(I != BBStates.end());
2962 MyStates.InitFromSucc(I->second);
2964 for (; SI != SE; ++SI) {
2966 I = BBStates.find(Succ);
2967 assert(I != BBStates.end());
2968 MyStates.MergeSucc(I->second);
2972 // Visit all the instructions, bottom-up.
2973 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2974 Instruction *Inst = llvm::prior(I);
2976 // Invoke instructions are visited as part of their successors (below).
2977 if (isa<InvokeInst>(Inst))
2980 DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n");
2982 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2985 // If there's a predecessor with an invoke, visit the invoke as if it were
2986 // part of this block, since we can't insert code after an invoke in its own
2987 // block, and we don't want to split critical edges.
2988 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2989 PE(MyStates.pred_end()); PI != PE; ++PI) {
2990 BasicBlock *Pred = *PI;
2991 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2992 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
2995 return NestingDetected;
2999 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
3000 DenseMap<Value *, RRInfo> &Releases,
3001 BBState &MyStates) {
3002 bool NestingDetected = false;
3003 InstructionClass Class = GetInstructionClass(Inst);
3004 const Value *Arg = 0;
3007 case IC_RetainBlock:
3008 // An objc_retainBlock call with just a use may need to be kept,
3009 // because it may be copying a block from the stack to the heap.
3010 if (!IsRetainBlockOptimizable(Inst))
3015 Arg = GetObjCArg(Inst);
3017 PtrState &S = MyStates.getPtrTopDownState(Arg);
3019 // Don't do retain+release tracking for IC_RetainRV, because it's
3020 // better to let it remain as the first instruction after a call.
3021 if (Class != IC_RetainRV) {
3022 // If we see two retains in a row on the same pointer. If so, make
3023 // a note, and we'll cicle back to revisit it after we've
3024 // hopefully eliminated the second retain, which may allow us to
3025 // eliminate the first retain too.
3026 // Theoretically we could implement removal of nested retain+release
3027 // pairs by making PtrState hold a stack of states, but this is
3028 // simple and avoids adding overhead for the non-nested case.
3029 if (S.GetSeq() == S_Retain)
3030 NestingDetected = true;
3032 S.ResetSequenceProgress(S_Retain);
3033 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
3034 S.RRI.KnownSafe = S.IsKnownIncremented();
3035 S.RRI.Calls.insert(Inst);
3038 S.SetKnownPositiveRefCount();
3040 // A retain can be a potential use; procede to the generic checking
3045 Arg = GetObjCArg(Inst);
3047 PtrState &S = MyStates.getPtrTopDownState(Arg);
3050 switch (S.GetSeq()) {
3053 S.RRI.ReverseInsertPts.clear();
3056 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
3057 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
3058 Releases[Inst] = S.RRI;
3059 S.ClearSequenceProgress();
3065 case S_MovableRelease:
3066 llvm_unreachable("top-down pointer in release state!");
3070 case IC_AutoreleasepoolPop:
3071 // Conservatively, clear MyStates for all known pointers.
3072 MyStates.clearTopDownPointers();
3073 return NestingDetected;
3074 case IC_AutoreleasepoolPush:
3076 // These are irrelevant.
3077 return NestingDetected;
3082 // Consider any other possible effects of this instruction on each
3083 // pointer being tracked.
3084 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
3085 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
3086 const Value *Ptr = MI->first;
3088 continue; // Handled above.
3089 PtrState &S = MI->second;
3090 Sequence Seq = S.GetSeq();
3092 // Check for possible releases.
3093 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
3097 S.SetSeq(S_CanRelease);
3098 assert(S.RRI.ReverseInsertPts.empty());
3099 S.RRI.ReverseInsertPts.insert(Inst);
3101 // One call can't cause a transition from S_Retain to S_CanRelease
3102 // and S_CanRelease to S_Use. If we've made the first transition,
3111 case S_MovableRelease:
3112 llvm_unreachable("top-down pointer in release state!");
3116 // Check for possible direct uses.
3119 if (CanUse(Inst, Ptr, PA, Class))
3128 case S_MovableRelease:
3129 llvm_unreachable("top-down pointer in release state!");
3133 return NestingDetected;
3137 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
3138 DenseMap<const BasicBlock *, BBState> &BBStates,
3139 DenseMap<Value *, RRInfo> &Releases) {
3140 bool NestingDetected = false;
3141 BBState &MyStates = BBStates[BB];
3143 // Merge the states from each predecessor to compute the initial state
3144 // for the current block.
3145 BBState::edge_iterator PI(MyStates.pred_begin()),
3146 PE(MyStates.pred_end());
3148 const BasicBlock *Pred = *PI;
3149 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
3150 assert(I != BBStates.end());
3151 MyStates.InitFromPred(I->second);
3153 for (; PI != PE; ++PI) {
3155 I = BBStates.find(Pred);
3156 assert(I != BBStates.end());
3157 MyStates.MergePred(I->second);
3161 // Visit all the instructions, top-down.
3162 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3163 Instruction *Inst = I;
3165 DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n");
3167 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
3170 CheckForCFGHazards(BB, BBStates, MyStates);
3171 return NestingDetected;
3175 ComputePostOrders(Function &F,
3176 SmallVectorImpl<BasicBlock *> &PostOrder,
3177 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
3178 unsigned NoObjCARCExceptionsMDKind,
3179 DenseMap<const BasicBlock *, BBState> &BBStates) {
3180 /// The visited set, for doing DFS walks.
3181 SmallPtrSet<BasicBlock *, 16> Visited;
3183 // Do DFS, computing the PostOrder.
3184 SmallPtrSet<BasicBlock *, 16> OnStack;
3185 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
3187 // Functions always have exactly one entry block, and we don't have
3188 // any other block that we treat like an entry block.
3189 BasicBlock *EntryBB = &F.getEntryBlock();
3190 BBState &MyStates = BBStates[EntryBB];
3191 MyStates.SetAsEntry();
3192 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
3193 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
3194 Visited.insert(EntryBB);
3195 OnStack.insert(EntryBB);
3198 BasicBlock *CurrBB = SuccStack.back().first;
3199 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3200 succ_iterator SE(TI, false);
3202 // If the terminator is an invoke marked with the
3203 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
3204 // ignored, for ARC purposes.
3205 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
3206 DEBUG(dbgs() << "ObjCARCOpt::ComputePostOrders: Found an invoke "
3207 "terminator marked with "
3208 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
3213 while (SuccStack.back().second != SE) {
3214 BasicBlock *SuccBB = *SuccStack.back().second++;
3215 if (Visited.insert(SuccBB)) {
3216 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3217 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
3218 BBStates[CurrBB].addSucc(SuccBB);
3219 BBState &SuccStates = BBStates[SuccBB];
3220 SuccStates.addPred(CurrBB);
3221 OnStack.insert(SuccBB);
3225 if (!OnStack.count(SuccBB)) {
3226 BBStates[CurrBB].addSucc(SuccBB);
3227 BBStates[SuccBB].addPred(CurrBB);
3230 OnStack.erase(CurrBB);
3231 PostOrder.push_back(CurrBB);
3232 SuccStack.pop_back();
3233 } while (!SuccStack.empty());
3237 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
3238 // Functions may have many exits, and there also blocks which we treat
3239 // as exits due to ignored edges.
3240 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3241 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3242 BasicBlock *ExitBB = I;
3243 BBState &MyStates = BBStates[ExitBB];
3244 if (!MyStates.isExit())
3247 MyStates.SetAsExit();
3249 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
3250 Visited.insert(ExitBB);
3251 while (!PredStack.empty()) {
3252 reverse_dfs_next_succ:
3253 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3254 while (PredStack.back().second != PE) {
3255 BasicBlock *BB = *PredStack.back().second++;
3256 if (Visited.insert(BB)) {
3257 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
3258 goto reverse_dfs_next_succ;
3261 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3266 // Visit the function both top-down and bottom-up.
3268 ObjCARCOpt::Visit(Function &F,
3269 DenseMap<const BasicBlock *, BBState> &BBStates,
3270 MapVector<Value *, RRInfo> &Retains,
3271 DenseMap<Value *, RRInfo> &Releases) {
3273 // Use reverse-postorder traversals, because we magically know that loops
3274 // will be well behaved, i.e. they won't repeatedly call retain on a single
3275 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3276 // class here because we want the reverse-CFG postorder to consider each
3277 // function exit point, and we want to ignore selected cycle edges.
3278 SmallVector<BasicBlock *, 16> PostOrder;
3279 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
3280 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3281 NoObjCARCExceptionsMDKind,
3284 // Use reverse-postorder on the reverse CFG for bottom-up.
3285 bool BottomUpNestingDetected = false;
3286 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3287 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3289 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
3291 // Use reverse-postorder for top-down.
3292 bool TopDownNestingDetected = false;
3293 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3294 PostOrder.rbegin(), E = PostOrder.rend();
3296 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
3298 return TopDownNestingDetected && BottomUpNestingDetected;
3301 /// Move the calls in RetainsToMove and ReleasesToMove.
3302 void ObjCARCOpt::MoveCalls(Value *Arg,
3303 RRInfo &RetainsToMove,
3304 RRInfo &ReleasesToMove,
3305 MapVector<Value *, RRInfo> &Retains,
3306 DenseMap<Value *, RRInfo> &Releases,
3307 SmallVectorImpl<Instruction *> &DeadInsts,
3309 Type *ArgTy = Arg->getType();
3310 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
3312 // Insert the new retain and release calls.
3313 for (SmallPtrSet<Instruction *, 2>::const_iterator
3314 PI = ReleasesToMove.ReverseInsertPts.begin(),
3315 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3316 Instruction *InsertPt = *PI;
3317 Value *MyArg = ArgTy == ParamTy ? Arg :
3318 new BitCastInst(Arg, ParamTy, "", InsertPt);
3320 CallInst::Create(RetainsToMove.IsRetainBlock ?
3321 getRetainBlockCallee(M) : getRetainCallee(M),
3322 MyArg, "", InsertPt);
3323 Call->setDoesNotThrow();
3324 if (RetainsToMove.IsRetainBlock)
3325 Call->setMetadata(CopyOnEscapeMDKind,
3326 MDNode::get(M->getContext(), ArrayRef<Value *>()));
3328 Call->setTailCall();
3330 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
3332 " At insertion point: " << *InsertPt
3335 for (SmallPtrSet<Instruction *, 2>::const_iterator
3336 PI = RetainsToMove.ReverseInsertPts.begin(),
3337 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3338 Instruction *InsertPt = *PI;
3339 Value *MyArg = ArgTy == ParamTy ? Arg :
3340 new BitCastInst(Arg, ParamTy, "", InsertPt);
3341 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3343 // Attach a clang.imprecise_release metadata tag, if appropriate.
3344 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3345 Call->setMetadata(ImpreciseReleaseMDKind, M);
3346 Call->setDoesNotThrow();
3347 if (ReleasesToMove.IsTailCallRelease)
3348 Call->setTailCall();
3350 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
3352 " At insertion point: " << *InsertPt
3356 // Delete the original retain and release calls.
3357 for (SmallPtrSet<Instruction *, 2>::const_iterator
3358 AI = RetainsToMove.Calls.begin(),
3359 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3360 Instruction *OrigRetain = *AI;
3361 Retains.blot(OrigRetain);
3362 DeadInsts.push_back(OrigRetain);
3363 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
3366 for (SmallPtrSet<Instruction *, 2>::const_iterator
3367 AI = ReleasesToMove.Calls.begin(),
3368 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3369 Instruction *OrigRelease = *AI;
3370 Releases.erase(OrigRelease);
3371 DeadInsts.push_back(OrigRelease);
3372 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
3377 /// Identify pairings between the retains and releases, and delete and/or move
3380 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3382 MapVector<Value *, RRInfo> &Retains,
3383 DenseMap<Value *, RRInfo> &Releases,
3385 bool AnyPairsCompletelyEliminated = false;
3386 RRInfo RetainsToMove;
3387 RRInfo ReleasesToMove;
3388 SmallVector<Instruction *, 4> NewRetains;
3389 SmallVector<Instruction *, 4> NewReleases;
3390 SmallVector<Instruction *, 8> DeadInsts;
3392 // Visit each retain.
3393 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
3394 E = Retains.end(); I != E; ++I) {
3395 Value *V = I->first;
3396 if (!V) continue; // blotted
3398 Instruction *Retain = cast<Instruction>(V);
3400 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
3403 Value *Arg = GetObjCArg(Retain);
3405 // If the object being released is in static or stack storage, we know it's
3406 // not being managed by ObjC reference counting, so we can delete pairs
3407 // regardless of what possible decrements or uses lie between them.
3408 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
3410 // A constant pointer can't be pointing to an object on the heap. It may
3411 // be reference-counted, but it won't be deleted.
3412 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3413 if (const GlobalVariable *GV =
3414 dyn_cast<GlobalVariable>(
3415 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3416 if (GV->isConstant())
3419 // If a pair happens in a region where it is known that the reference count
3420 // is already incremented, we can similarly ignore possible decrements.
3421 bool KnownSafeTD = true, KnownSafeBU = true;
3423 // Connect the dots between the top-down-collected RetainsToMove and
3424 // bottom-up-collected ReleasesToMove to form sets of related calls.
3425 // This is an iterative process so that we connect multiple releases
3426 // to multiple retains if needed.
3427 unsigned OldDelta = 0;
3428 unsigned NewDelta = 0;
3429 unsigned OldCount = 0;
3430 unsigned NewCount = 0;
3431 bool FirstRelease = true;
3432 bool FirstRetain = true;
3433 NewRetains.push_back(Retain);
3435 for (SmallVectorImpl<Instruction *>::const_iterator
3436 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3437 Instruction *NewRetain = *NI;
3438 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3439 assert(It != Retains.end());
3440 const RRInfo &NewRetainRRI = It->second;
3441 KnownSafeTD &= NewRetainRRI.KnownSafe;
3442 for (SmallPtrSet<Instruction *, 2>::const_iterator
3443 LI = NewRetainRRI.Calls.begin(),
3444 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3445 Instruction *NewRetainRelease = *LI;
3446 DenseMap<Value *, RRInfo>::const_iterator Jt =
3447 Releases.find(NewRetainRelease);
3448 if (Jt == Releases.end())
3450 const RRInfo &NewRetainReleaseRRI = Jt->second;
3451 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3452 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3454 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3456 // Merge the ReleaseMetadata and IsTailCallRelease values.
3458 ReleasesToMove.ReleaseMetadata =
3459 NewRetainReleaseRRI.ReleaseMetadata;
3460 ReleasesToMove.IsTailCallRelease =
3461 NewRetainReleaseRRI.IsTailCallRelease;
3462 FirstRelease = false;
3464 if (ReleasesToMove.ReleaseMetadata !=
3465 NewRetainReleaseRRI.ReleaseMetadata)
3466 ReleasesToMove.ReleaseMetadata = 0;
3467 if (ReleasesToMove.IsTailCallRelease !=
3468 NewRetainReleaseRRI.IsTailCallRelease)
3469 ReleasesToMove.IsTailCallRelease = false;
3472 // Collect the optimal insertion points.
3474 for (SmallPtrSet<Instruction *, 2>::const_iterator
3475 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3476 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3478 Instruction *RIP = *RI;
3479 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3480 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3482 NewReleases.push_back(NewRetainRelease);
3487 if (NewReleases.empty()) break;
3489 // Back the other way.
3490 for (SmallVectorImpl<Instruction *>::const_iterator
3491 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3492 Instruction *NewRelease = *NI;
3493 DenseMap<Value *, RRInfo>::const_iterator It =
3494 Releases.find(NewRelease);
3495 assert(It != Releases.end());
3496 const RRInfo &NewReleaseRRI = It->second;
3497 KnownSafeBU &= NewReleaseRRI.KnownSafe;
3498 for (SmallPtrSet<Instruction *, 2>::const_iterator
3499 LI = NewReleaseRRI.Calls.begin(),
3500 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3501 Instruction *NewReleaseRetain = *LI;
3502 MapVector<Value *, RRInfo>::const_iterator Jt =
3503 Retains.find(NewReleaseRetain);
3504 if (Jt == Retains.end())
3506 const RRInfo &NewReleaseRetainRRI = Jt->second;
3507 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3508 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3509 unsigned PathCount =
3510 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3511 OldDelta += PathCount;
3512 OldCount += PathCount;
3514 // Merge the IsRetainBlock values.
3516 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3517 FirstRetain = false;
3518 } else if (ReleasesToMove.IsRetainBlock !=
3519 NewReleaseRetainRRI.IsRetainBlock)
3520 // It's not possible to merge the sequences if one uses
3521 // objc_retain and the other uses objc_retainBlock.
3524 // Collect the optimal insertion points.
3526 for (SmallPtrSet<Instruction *, 2>::const_iterator
3527 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3528 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3530 Instruction *RIP = *RI;
3531 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3532 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3533 NewDelta += PathCount;
3534 NewCount += PathCount;
3537 NewRetains.push_back(NewReleaseRetain);
3541 NewReleases.clear();
3542 if (NewRetains.empty()) break;
3545 // If the pointer is known incremented or nested, we can safely delete the
3546 // pair regardless of what's between them.
3547 if (KnownSafeTD || KnownSafeBU) {
3548 RetainsToMove.ReverseInsertPts.clear();
3549 ReleasesToMove.ReverseInsertPts.clear();
3552 // Determine whether the new insertion points we computed preserve the
3553 // balance of retain and release calls through the program.
3554 // TODO: If the fully aggressive solution isn't valid, try to find a
3555 // less aggressive solution which is.
3560 // Determine whether the original call points are balanced in the retain and
3561 // release calls through the program. If not, conservatively don't touch
3563 // TODO: It's theoretically possible to do code motion in this case, as
3564 // long as the existing imbalances are maintained.
3568 // Ok, everything checks out and we're all set. Let's move some code!
3570 assert(OldCount != 0 && "Unreachable code?");
3571 AnyPairsCompletelyEliminated = NewCount == 0;
3572 NumRRs += OldCount - NewCount;
3573 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3574 Retains, Releases, DeadInsts, M);
3577 NewReleases.clear();
3579 RetainsToMove.clear();
3580 ReleasesToMove.clear();
3583 // Now that we're done moving everything, we can delete the newly dead
3584 // instructions, as we no longer need them as insert points.
3585 while (!DeadInsts.empty())
3586 EraseInstruction(DeadInsts.pop_back_val());
3588 return AnyPairsCompletelyEliminated;
3591 /// Weak pointer optimizations.
3592 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3593 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3594 // itself because it uses AliasAnalysis and we need to do provenance
3596 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3597 Instruction *Inst = &*I++;
3599 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
3602 InstructionClass Class = GetBasicInstructionClass(Inst);
3603 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3606 // Delete objc_loadWeak calls with no users.
3607 if (Class == IC_LoadWeak && Inst->use_empty()) {
3608 Inst->eraseFromParent();
3612 // TODO: For now, just look for an earlier available version of this value
3613 // within the same block. Theoretically, we could do memdep-style non-local
3614 // analysis too, but that would want caching. A better approach would be to
3615 // use the technique that EarlyCSE uses.
3616 inst_iterator Current = llvm::prior(I);
3617 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3618 for (BasicBlock::iterator B = CurrentBB->begin(),
3619 J = Current.getInstructionIterator();
3621 Instruction *EarlierInst = &*llvm::prior(J);
3622 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3623 switch (EarlierClass) {
3625 case IC_LoadWeakRetained: {
3626 // If this is loading from the same pointer, replace this load's value
3628 CallInst *Call = cast<CallInst>(Inst);
3629 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3630 Value *Arg = Call->getArgOperand(0);
3631 Value *EarlierArg = EarlierCall->getArgOperand(0);
3632 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3633 case AliasAnalysis::MustAlias:
3635 // If the load has a builtin retain, insert a plain retain for it.
3636 if (Class == IC_LoadWeakRetained) {
3638 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3642 // Zap the fully redundant load.
3643 Call->replaceAllUsesWith(EarlierCall);
3644 Call->eraseFromParent();
3646 case AliasAnalysis::MayAlias:
3647 case AliasAnalysis::PartialAlias:
3649 case AliasAnalysis::NoAlias:
3656 // If this is storing to the same pointer and has the same size etc.
3657 // replace this load's value with the stored value.
3658 CallInst *Call = cast<CallInst>(Inst);
3659 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3660 Value *Arg = Call->getArgOperand(0);
3661 Value *EarlierArg = EarlierCall->getArgOperand(0);
3662 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3663 case AliasAnalysis::MustAlias:
3665 // If the load has a builtin retain, insert a plain retain for it.
3666 if (Class == IC_LoadWeakRetained) {
3668 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3672 // Zap the fully redundant load.
3673 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3674 Call->eraseFromParent();
3676 case AliasAnalysis::MayAlias:
3677 case AliasAnalysis::PartialAlias:
3679 case AliasAnalysis::NoAlias:
3686 // TOOD: Grab the copied value.
3688 case IC_AutoreleasepoolPush:
3691 // Weak pointers are only modified through the weak entry points
3692 // (and arbitrary calls, which could call the weak entry points).
3695 // Anything else could modify the weak pointer.
3702 // Then, for each destroyWeak with an alloca operand, check to see if
3703 // the alloca and all its users can be zapped.
3704 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3705 Instruction *Inst = &*I++;
3706 InstructionClass Class = GetBasicInstructionClass(Inst);
3707 if (Class != IC_DestroyWeak)
3710 CallInst *Call = cast<CallInst>(Inst);
3711 Value *Arg = Call->getArgOperand(0);
3712 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3713 for (Value::use_iterator UI = Alloca->use_begin(),
3714 UE = Alloca->use_end(); UI != UE; ++UI) {
3715 const Instruction *UserInst = cast<Instruction>(*UI);
3716 switch (GetBasicInstructionClass(UserInst)) {
3719 case IC_DestroyWeak:
3726 for (Value::use_iterator UI = Alloca->use_begin(),
3727 UE = Alloca->use_end(); UI != UE; ) {
3728 CallInst *UserInst = cast<CallInst>(*UI++);
3729 switch (GetBasicInstructionClass(UserInst)) {
3732 // These functions return their second argument.
3733 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3735 case IC_DestroyWeak:
3739 llvm_unreachable("alloca really is used!");
3741 UserInst->eraseFromParent();
3743 Alloca->eraseFromParent();
3748 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
3752 /// Identify program paths which execute sequences of retains and releases which
3753 /// can be eliminated.
3754 bool ObjCARCOpt::OptimizeSequences(Function &F) {
3755 /// Releases, Retains - These are used to store the results of the main flow
3756 /// analysis. These use Value* as the key instead of Instruction* so that the
3757 /// map stays valid when we get around to rewriting code and calls get
3758 /// replaced by arguments.
3759 DenseMap<Value *, RRInfo> Releases;
3760 MapVector<Value *, RRInfo> Retains;
3762 /// This is used during the traversal of the function to track the
3763 /// states for each identified object at each block.
3764 DenseMap<const BasicBlock *, BBState> BBStates;
3766 // Analyze the CFG of the function, and all instructions.
3767 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3770 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3774 /// Look for this pattern:
3776 /// %call = call i8* @something(...)
3777 /// %2 = call i8* @objc_retain(i8* %call)
3778 /// %3 = call i8* @objc_autorelease(i8* %2)
3781 /// And delete the retain and autorelease.
3783 /// Otherwise if it's just this:
3785 /// %3 = call i8* @objc_autorelease(i8* %2)
3788 /// convert the autorelease to autoreleaseRV.
3789 void ObjCARCOpt::OptimizeReturns(Function &F) {
3790 if (!F.getReturnType()->isPointerTy())
3793 SmallPtrSet<Instruction *, 4> DependingInstructions;
3794 SmallPtrSet<const BasicBlock *, 4> Visited;
3795 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3796 BasicBlock *BB = FI;
3797 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3799 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
3803 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3804 FindDependencies(NeedsPositiveRetainCount, Arg,
3805 BB, Ret, DependingInstructions, Visited, PA);
3806 if (DependingInstructions.size() != 1)
3810 CallInst *Autorelease =
3811 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3814 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3815 if (!IsAutorelease(AutoreleaseClass))
3817 if (GetObjCArg(Autorelease) != Arg)
3820 DependingInstructions.clear();
3823 // Check that there is nothing that can affect the reference
3824 // count between the autorelease and the retain.
3825 FindDependencies(CanChangeRetainCount, Arg,
3826 BB, Autorelease, DependingInstructions, Visited, PA);
3827 if (DependingInstructions.size() != 1)
3832 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3834 // Check that we found a retain with the same argument.
3836 !IsRetain(GetBasicInstructionClass(Retain)) ||
3837 GetObjCArg(Retain) != Arg)
3840 DependingInstructions.clear();
3843 // Convert the autorelease to an autoreleaseRV, since it's
3844 // returning the value.
3845 if (AutoreleaseClass == IC_Autorelease) {
3846 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
3847 "=> autoreleaseRV since it's returning a value.\n"
3848 " In: " << *Autorelease
3850 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3851 DEBUG(dbgs() << " Out: " << *Autorelease
3853 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
3854 AutoreleaseClass = IC_AutoreleaseRV;
3857 // Check that there is nothing that can affect the reference
3858 // count between the retain and the call.
3859 // Note that Retain need not be in BB.
3860 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3861 DependingInstructions, Visited, PA);
3862 if (DependingInstructions.size() != 1)
3867 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3869 // Check that the pointer is the return value of the call.
3870 if (!Call || Arg != Call)
3873 // Check that the call is a regular call.
3874 InstructionClass Class = GetBasicInstructionClass(Call);
3875 if (Class != IC_CallOrUser && Class != IC_Call)
3878 // If so, we can zap the retain and autorelease.
3881 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
3883 << *Autorelease << "\n");
3884 EraseInstruction(Retain);
3885 EraseInstruction(Autorelease);
3891 DependingInstructions.clear();
3895 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
3899 bool ObjCARCOpt::doInitialization(Module &M) {
3903 // If nothing in the Module uses ARC, don't do anything.
3904 Run = ModuleHasARC(M);
3908 // Identify the imprecise release metadata kind.
3909 ImpreciseReleaseMDKind =
3910 M.getContext().getMDKindID("clang.imprecise_release");
3911 CopyOnEscapeMDKind =
3912 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3913 NoObjCARCExceptionsMDKind =
3914 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3916 // Intuitively, objc_retain and others are nocapture, however in practice
3917 // they are not, because they return their argument value. And objc_release
3918 // calls finalizers which can have arbitrary side effects.
3920 // These are initialized lazily.
3922 AutoreleaseRVCallee = 0;
3925 RetainBlockCallee = 0;
3926 AutoreleaseCallee = 0;
3931 bool ObjCARCOpt::runOnFunction(Function &F) {
3935 // If nothing in the Module uses ARC, don't do anything.
3941 DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
3943 PA.setAA(&getAnalysis<AliasAnalysis>());
3945 // This pass performs several distinct transformations. As a compile-time aid
3946 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3947 // library functions aren't declared.
3949 // Preliminary optimizations. This also computs UsedInThisFunction.
3950 OptimizeIndividualCalls(F);
3952 // Optimizations for weak pointers.
3953 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3954 (1 << IC_LoadWeakRetained) |
3955 (1 << IC_StoreWeak) |
3956 (1 << IC_InitWeak) |
3957 (1 << IC_CopyWeak) |
3958 (1 << IC_MoveWeak) |
3959 (1 << IC_DestroyWeak)))
3960 OptimizeWeakCalls(F);
3962 // Optimizations for retain+release pairs.
3963 if (UsedInThisFunction & ((1 << IC_Retain) |
3964 (1 << IC_RetainRV) |
3965 (1 << IC_RetainBlock)))
3966 if (UsedInThisFunction & (1 << IC_Release))
3967 // Run OptimizeSequences until it either stops making changes or
3968 // no retain+release pair nesting is detected.
3969 while (OptimizeSequences(F)) {}
3971 // Optimizations if objc_autorelease is used.
3972 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3973 (1 << IC_AutoreleaseRV)))
3976 DEBUG(dbgs() << "\n");
3981 void ObjCARCOpt::releaseMemory() {
3987 /// \defgroup ARCContract ARC Contraction.
3990 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
3991 // dominated by single calls.
3993 #include "llvm/Analysis/Dominators.h"
3994 #include "llvm/IR/InlineAsm.h"
3995 #include "llvm/IR/Operator.h"
3997 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
4000 /// \brief Late ARC optimizations
4002 /// These change the IR in a way that makes it difficult to be analyzed by
4003 /// ObjCARCOpt, so it's run late.
4004 class ObjCARCContract : public FunctionPass {
4008 ProvenanceAnalysis PA;
4010 /// A flag indicating whether this optimization pass should run.
4013 /// Declarations for ObjC runtime functions, for use in creating calls to
4014 /// them. These are initialized lazily to avoid cluttering up the Module
4015 /// with unused declarations.
4017 /// Declaration for objc_storeStrong().
4018 Constant *StoreStrongCallee;
4019 /// Declaration for objc_retainAutorelease().
4020 Constant *RetainAutoreleaseCallee;
4021 /// Declaration for objc_retainAutoreleaseReturnValue().
4022 Constant *RetainAutoreleaseRVCallee;
4024 /// The inline asm string to insert between calls and RetainRV calls to make
4025 /// the optimization work on targets which need it.
4026 const MDString *RetainRVMarker;
4028 /// The set of inserted objc_storeStrong calls. If at the end of walking the
4029 /// function we have found no alloca instructions, these calls can be marked
4031 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
4033 Constant *getStoreStrongCallee(Module *M);
4034 Constant *getRetainAutoreleaseCallee(Module *M);
4035 Constant *getRetainAutoreleaseRVCallee(Module *M);
4037 bool ContractAutorelease(Function &F, Instruction *Autorelease,
4038 InstructionClass Class,
4039 SmallPtrSet<Instruction *, 4>
4040 &DependingInstructions,
4041 SmallPtrSet<const BasicBlock *, 4>
4044 void ContractRelease(Instruction *Release,
4045 inst_iterator &Iter);
4047 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
4048 virtual bool doInitialization(Module &M);
4049 virtual bool runOnFunction(Function &F);
4053 ObjCARCContract() : FunctionPass(ID) {
4054 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
4059 char ObjCARCContract::ID = 0;
4060 INITIALIZE_PASS_BEGIN(ObjCARCContract,
4061 "objc-arc-contract", "ObjC ARC contraction", false, false)
4062 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
4063 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
4064 INITIALIZE_PASS_END(ObjCARCContract,
4065 "objc-arc-contract", "ObjC ARC contraction", false, false)
4067 Pass *llvm::createObjCARCContractPass() {
4068 return new ObjCARCContract();
4071 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
4072 AU.addRequired<AliasAnalysis>();
4073 AU.addRequired<DominatorTree>();
4074 AU.setPreservesCFG();
4077 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
4078 if (!StoreStrongCallee) {
4079 LLVMContext &C = M->getContext();
4080 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4081 Type *I8XX = PointerType::getUnqual(I8X);
4082 Type *Params[] = { I8XX, I8X };
4084 AttributeSet Attribute = AttributeSet()
4085 .addAttr(M->getContext(), AttributeSet::FunctionIndex,
4086 Attribute::get(C, Attribute::NoUnwind))
4087 .addAttr(M->getContext(), 1, Attribute::get(C, Attribute::NoCapture));
4090 M->getOrInsertFunction(
4092 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
4095 return StoreStrongCallee;
4098 Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
4099 if (!RetainAutoreleaseCallee) {
4100 LLVMContext &C = M->getContext();
4101 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4102 Type *Params[] = { I8X };
4103 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
4104 AttributeSet Attribute =
4105 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
4106 Attribute::get(C, Attribute::NoUnwind));
4107 RetainAutoreleaseCallee =
4108 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
4110 return RetainAutoreleaseCallee;
4113 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
4114 if (!RetainAutoreleaseRVCallee) {
4115 LLVMContext &C = M->getContext();
4116 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4117 Type *Params[] = { I8X };
4118 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
4119 AttributeSet Attribute =
4120 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
4121 Attribute::get(C, Attribute::NoUnwind));
4122 RetainAutoreleaseRVCallee =
4123 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
4126 return RetainAutoreleaseRVCallee;
4129 /// Merge an autorelease with a retain into a fused call.
4131 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
4132 InstructionClass Class,
4133 SmallPtrSet<Instruction *, 4>
4134 &DependingInstructions,
4135 SmallPtrSet<const BasicBlock *, 4>
4137 const Value *Arg = GetObjCArg(Autorelease);
4139 // Check that there are no instructions between the retain and the autorelease
4140 // (such as an autorelease_pop) which may change the count.
4141 CallInst *Retain = 0;
4142 if (Class == IC_AutoreleaseRV)
4143 FindDependencies(RetainAutoreleaseRVDep, Arg,
4144 Autorelease->getParent(), Autorelease,
4145 DependingInstructions, Visited, PA);
4147 FindDependencies(RetainAutoreleaseDep, Arg,
4148 Autorelease->getParent(), Autorelease,
4149 DependingInstructions, Visited, PA);
4152 if (DependingInstructions.size() != 1) {
4153 DependingInstructions.clear();
4157 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
4158 DependingInstructions.clear();
4161 GetBasicInstructionClass(Retain) != IC_Retain ||
4162 GetObjCArg(Retain) != Arg)
4168 DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing "
4169 "retain/autorelease. Erasing: " << *Autorelease << "\n"
4171 << *Retain << "\n");
4173 if (Class == IC_AutoreleaseRV)
4174 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
4176 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
4178 DEBUG(dbgs() << " New Retain: "
4179 << *Retain << "\n");
4181 EraseInstruction(Autorelease);
4185 /// Attempt to merge an objc_release with a store, load, and objc_retain to form
4186 /// an objc_storeStrong. This can be a little tricky because the instructions
4187 /// don't always appear in order, and there may be unrelated intervening
4189 void ObjCARCContract::ContractRelease(Instruction *Release,
4190 inst_iterator &Iter) {
4191 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
4192 if (!Load || !Load->isSimple()) return;
4194 // For now, require everything to be in one basic block.
4195 BasicBlock *BB = Release->getParent();
4196 if (Load->getParent() != BB) return;
4198 // Walk down to find the store and the release, which may be in either order.
4199 BasicBlock::iterator I = Load, End = BB->end();
4201 AliasAnalysis::Location Loc = AA->getLocation(Load);
4202 StoreInst *Store = 0;
4203 bool SawRelease = false;
4204 for (; !Store || !SawRelease; ++I) {
4208 Instruction *Inst = I;
4209 if (Inst == Release) {
4214 InstructionClass Class = GetBasicInstructionClass(Inst);
4216 // Unrelated retains are harmless.
4217 if (IsRetain(Class))
4221 // The store is the point where we're going to put the objc_storeStrong,
4222 // so make sure there are no uses after it.
4223 if (CanUse(Inst, Load, PA, Class))
4225 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
4226 // We are moving the load down to the store, so check for anything
4227 // else which writes to the memory between the load and the store.
4228 Store = dyn_cast<StoreInst>(Inst);
4229 if (!Store || !Store->isSimple()) return;
4230 if (Store->getPointerOperand() != Loc.Ptr) return;
4234 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
4236 // Walk up to find the retain.
4238 BasicBlock::iterator Begin = BB->begin();
4239 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
4241 Instruction *Retain = I;
4242 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
4243 if (GetObjCArg(Retain) != New) return;
4248 LLVMContext &C = Release->getContext();
4249 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4250 Type *I8XX = PointerType::getUnqual(I8X);
4252 Value *Args[] = { Load->getPointerOperand(), New };
4253 if (Args[0]->getType() != I8XX)
4254 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
4255 if (Args[1]->getType() != I8X)
4256 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
4257 CallInst *StoreStrong =
4258 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
4260 StoreStrong->setDoesNotThrow();
4261 StoreStrong->setDebugLoc(Store->getDebugLoc());
4263 // We can't set the tail flag yet, because we haven't yet determined
4264 // whether there are any escaping allocas. Remember this call, so that
4265 // we can set the tail flag once we know it's safe.
4266 StoreStrongCalls.insert(StoreStrong);
4268 if (&*Iter == Store) ++Iter;
4269 Store->eraseFromParent();
4270 Release->eraseFromParent();
4271 EraseInstruction(Retain);
4272 if (Load->use_empty())
4273 Load->eraseFromParent();
4276 bool ObjCARCContract::doInitialization(Module &M) {
4277 // If nothing in the Module uses ARC, don't do anything.
4278 Run = ModuleHasARC(M);
4282 // These are initialized lazily.
4283 StoreStrongCallee = 0;
4284 RetainAutoreleaseCallee = 0;
4285 RetainAutoreleaseRVCallee = 0;
4287 // Initialize RetainRVMarker.
4289 if (NamedMDNode *NMD =
4290 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4291 if (NMD->getNumOperands() == 1) {
4292 const MDNode *N = NMD->getOperand(0);
4293 if (N->getNumOperands() == 1)
4294 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4301 bool ObjCARCContract::runOnFunction(Function &F) {
4305 // If nothing in the Module uses ARC, don't do anything.
4310 AA = &getAnalysis<AliasAnalysis>();
4311 DT = &getAnalysis<DominatorTree>();
4313 PA.setAA(&getAnalysis<AliasAnalysis>());
4315 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4316 // keyword. Be conservative if the function has variadic arguments.
4317 // It seems that functions which "return twice" are also unsafe for the
4318 // "tail" argument, because they are setjmp, which could need to
4319 // return to an earlier stack state.
4320 bool TailOkForStoreStrongs = !F.isVarArg() &&
4321 !F.callsFunctionThatReturnsTwice();
4323 // For ObjC library calls which return their argument, replace uses of the
4324 // argument with uses of the call return value, if it dominates the use. This
4325 // reduces register pressure.
4326 SmallPtrSet<Instruction *, 4> DependingInstructions;
4327 SmallPtrSet<const BasicBlock *, 4> Visited;
4328 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4329 Instruction *Inst = &*I++;
4331 DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
4333 // Only these library routines return their argument. In particular,
4334 // objc_retainBlock does not necessarily return its argument.
4335 InstructionClass Class = GetBasicInstructionClass(Inst);
4338 case IC_FusedRetainAutorelease:
4339 case IC_FusedRetainAutoreleaseRV:
4341 case IC_Autorelease:
4342 case IC_AutoreleaseRV:
4343 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4347 // If we're compiling for a target which needs a special inline-asm
4348 // marker to do the retainAutoreleasedReturnValue optimization,
4350 if (!RetainRVMarker)
4352 BasicBlock::iterator BBI = Inst;
4353 BasicBlock *InstParent = Inst->getParent();
4355 // Step up to see if the call immediately precedes the RetainRV call.
4356 // If it's an invoke, we have to cross a block boundary. And we have
4357 // to carefully dodge no-op instructions.
4359 if (&*BBI == InstParent->begin()) {
4360 BasicBlock *Pred = InstParent->getSinglePredecessor();
4362 goto decline_rv_optimization;
4363 BBI = Pred->getTerminator();
4367 } while (isNoopInstruction(BBI));
4369 if (&*BBI == GetObjCArg(Inst)) {
4370 DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
4371 "retainAutoreleasedReturnValue optimization.\n");
4374 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4375 /*isVarArg=*/false),
4376 RetainRVMarker->getString(),
4377 /*Constraints=*/"", /*hasSideEffects=*/true);
4378 CallInst::Create(IA, "", Inst);
4380 decline_rv_optimization:
4384 // objc_initWeak(p, null) => *p = null
4385 CallInst *CI = cast<CallInst>(Inst);
4386 if (isNullOrUndef(CI->getArgOperand(1))) {
4388 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4390 new StoreInst(Null, CI->getArgOperand(0), CI);
4392 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
4393 << " New = " << *Null << "\n");
4395 CI->replaceAllUsesWith(Null);
4396 CI->eraseFromParent();
4401 ContractRelease(Inst, I);
4404 // Be conservative if the function has any alloca instructions.
4405 // Technically we only care about escaping alloca instructions,
4406 // but this is sufficient to handle some interesting cases.
4407 if (isa<AllocaInst>(Inst))
4408 TailOkForStoreStrongs = false;
4414 DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n");
4416 // Don't use GetObjCArg because we don't want to look through bitcasts
4417 // and such; to do the replacement, the argument must have type i8*.
4418 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4420 // If we're compiling bugpointed code, don't get in trouble.
4421 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4423 // Look through the uses of the pointer.
4424 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4426 Use &U = UI.getUse();
4427 unsigned OperandNo = UI.getOperandNo();
4428 ++UI; // Increment UI now, because we may unlink its element.
4430 // If the call's return value dominates a use of the call's argument
4431 // value, rewrite the use to use the return value. We check for
4432 // reachability here because an unreachable call is considered to
4433 // trivially dominate itself, which would lead us to rewriting its
4434 // argument in terms of its return value, which would lead to
4435 // infinite loops in GetObjCArg.
4436 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
4438 Instruction *Replacement = Inst;
4439 Type *UseTy = U.get()->getType();
4440 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
4441 // For PHI nodes, insert the bitcast in the predecessor block.
4442 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4443 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
4444 if (Replacement->getType() != UseTy)
4445 Replacement = new BitCastInst(Replacement, UseTy, "",
4447 // While we're here, rewrite all edges for this PHI, rather
4448 // than just one use at a time, to minimize the number of
4449 // bitcasts we emit.
4450 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4451 if (PHI->getIncomingBlock(i) == BB) {
4452 // Keep the UI iterator valid.
4453 if (&PHI->getOperandUse(
4454 PHINode::getOperandNumForIncomingValue(i)) ==
4457 PHI->setIncomingValue(i, Replacement);
4460 if (Replacement->getType() != UseTy)
4461 Replacement = new BitCastInst(Replacement, UseTy, "",
4462 cast<Instruction>(U.getUser()));
4468 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
4469 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4470 Arg = BI->getOperand(0);
4471 else if (isa<GEPOperator>(Arg) &&
4472 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4473 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4474 else if (isa<GlobalAlias>(Arg) &&
4475 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4476 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4482 // If this function has no escaping allocas or suspicious vararg usage,
4483 // objc_storeStrong calls can be marked with the "tail" keyword.
4484 if (TailOkForStoreStrongs)
4485 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
4486 E = StoreStrongCalls.end(); I != E; ++I)
4487 (*I)->setTailCall();
4488 StoreStrongCalls.clear();