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
11 // Automatic Reference Counting and is a system for managing reference counts
12 // for objects in Objective C.
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/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
38 // A handy option to enable/disable all optimizations in this file.
39 static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
41 //===----------------------------------------------------------------------===//
43 //===----------------------------------------------------------------------===//
46 /// MapVector - An associative container with fast insertion-order
47 /// (deterministic) iteration over its elements. Plus the special
49 template<class KeyT, class ValueT>
51 /// Map - Map keys to indices in Vector.
52 typedef DenseMap<KeyT, size_t> MapTy;
55 /// Vector - Keys and values.
56 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
60 typedef typename VectorTy::iterator iterator;
61 typedef typename VectorTy::const_iterator const_iterator;
62 iterator begin() { return Vector.begin(); }
63 iterator end() { return Vector.end(); }
64 const_iterator begin() const { return Vector.begin(); }
65 const_iterator end() const { return Vector.end(); }
69 assert(Vector.size() >= Map.size()); // May differ due to blotting.
70 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
72 assert(I->second < Vector.size());
73 assert(Vector[I->second].first == I->first);
75 for (typename VectorTy::const_iterator I = Vector.begin(),
76 E = Vector.end(); I != E; ++I)
78 (Map.count(I->first) &&
79 Map[I->first] == size_t(I - Vector.begin())));
83 ValueT &operator[](const KeyT &Arg) {
84 std::pair<typename MapTy::iterator, bool> Pair =
85 Map.insert(std::make_pair(Arg, size_t(0)));
87 size_t Num = Vector.size();
88 Pair.first->second = Num;
89 Vector.push_back(std::make_pair(Arg, ValueT()));
90 return Vector[Num].second;
92 return Vector[Pair.first->second].second;
95 std::pair<iterator, bool>
96 insert(const std::pair<KeyT, ValueT> &InsertPair) {
97 std::pair<typename MapTy::iterator, bool> Pair =
98 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
100 size_t Num = Vector.size();
101 Pair.first->second = Num;
102 Vector.push_back(InsertPair);
103 return std::make_pair(Vector.begin() + Num, true);
105 return std::make_pair(Vector.begin() + Pair.first->second, false);
108 const_iterator find(const KeyT &Key) const {
109 typename MapTy::const_iterator It = Map.find(Key);
110 if (It == Map.end()) return Vector.end();
111 return Vector.begin() + It->second;
114 /// blot - This is similar to erase, but instead of removing the element
115 /// from the vector, it just zeros out the key in the vector. This leaves
116 /// iterators intact, but clients must be prepared for zeroed-out keys when
118 void blot(const KeyT &Key) {
119 typename MapTy::iterator It = Map.find(Key);
120 if (It == Map.end()) return;
121 Vector[It->second].first = KeyT();
132 //===----------------------------------------------------------------------===//
134 //===----------------------------------------------------------------------===//
136 #include "llvm/ADT/StringSwitch.h"
137 #include "llvm/Analysis/ValueTracking.h"
138 #include "llvm/IR/Intrinsics.h"
139 #include "llvm/IR/Module.h"
140 #include "llvm/Support/CallSite.h"
141 #include "llvm/Transforms/Utils/Local.h"
144 /// InstructionClass - 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 /// IsPotentialUse - Test whether the given value is possible a
173 /// reference-counted pointer.
174 static bool IsPotentialUse(const Value *Op) {
175 // Pointers to static or stack storage are not reference-counted pointers.
176 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
178 // Special arguments are not reference-counted.
179 if (const Argument *Arg = dyn_cast<Argument>(Op))
180 if (Arg->hasByValAttr() ||
181 Arg->hasNestAttr() ||
182 Arg->hasStructRetAttr())
184 // Only consider values with pointer types.
185 // It seemes intuitive to exclude function pointer types as well, since
186 // functions are never reference-counted, however clang occasionally
187 // bitcasts reference-counted pointers to function-pointer type
189 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
192 // Conservatively assume anything else is a potential use.
196 /// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind
197 /// of construct CS is.
198 static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
199 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
201 if (IsPotentialUse(*I))
202 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
204 return CS.onlyReadsMemory() ? IC_None : IC_Call;
207 /// GetFunctionClass - Determine if F is one of the special known Functions.
208 /// If it isn't, return IC_CallOrUser.
209 static InstructionClass GetFunctionClass(const Function *F) {
210 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
214 return StringSwitch<InstructionClass>(F->getName())
215 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
216 .Default(IC_CallOrUser);
219 const Argument *A0 = AI++;
221 // Argument is a pointer.
222 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
223 Type *ETy = PTy->getElementType();
225 if (ETy->isIntegerTy(8))
226 return StringSwitch<InstructionClass>(F->getName())
227 .Case("objc_retain", IC_Retain)
228 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
229 .Case("objc_retainBlock", IC_RetainBlock)
230 .Case("objc_release", IC_Release)
231 .Case("objc_autorelease", IC_Autorelease)
232 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
233 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
234 .Case("objc_retainedObject", IC_NoopCast)
235 .Case("objc_unretainedObject", IC_NoopCast)
236 .Case("objc_unretainedPointer", IC_NoopCast)
237 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
238 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
239 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
240 .Default(IC_CallOrUser);
243 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
244 if (Pte->getElementType()->isIntegerTy(8))
245 return StringSwitch<InstructionClass>(F->getName())
246 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
247 .Case("objc_loadWeak", IC_LoadWeak)
248 .Case("objc_destroyWeak", IC_DestroyWeak)
249 .Default(IC_CallOrUser);
252 // Two arguments, first is i8**.
253 const Argument *A1 = AI++;
255 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
256 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
257 if (Pte->getElementType()->isIntegerTy(8))
258 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
259 Type *ETy1 = PTy1->getElementType();
260 // Second argument is i8*
261 if (ETy1->isIntegerTy(8))
262 return StringSwitch<InstructionClass>(F->getName())
263 .Case("objc_storeWeak", IC_StoreWeak)
264 .Case("objc_initWeak", IC_InitWeak)
265 .Case("objc_storeStrong", IC_StoreStrong)
266 .Default(IC_CallOrUser);
267 // Second argument is i8**.
268 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
269 if (Pte1->getElementType()->isIntegerTy(8))
270 return StringSwitch<InstructionClass>(F->getName())
271 .Case("objc_moveWeak", IC_MoveWeak)
272 .Case("objc_copyWeak", IC_CopyWeak)
273 .Default(IC_CallOrUser);
277 return IC_CallOrUser;
280 /// GetInstructionClass - Determine what kind of construct V is.
281 static InstructionClass GetInstructionClass(const Value *V) {
282 if (const Instruction *I = dyn_cast<Instruction>(V)) {
283 // Any instruction other than bitcast and gep with a pointer operand have a
284 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
285 // to a subsequent use, rather than using it themselves, in this sense.
286 // As a short cut, several other opcodes are known to have no pointer
287 // operands of interest. And ret is never followed by a release, so it's
288 // not interesting to examine.
289 switch (I->getOpcode()) {
290 case Instruction::Call: {
291 const CallInst *CI = cast<CallInst>(I);
292 // Check for calls to special functions.
293 if (const Function *F = CI->getCalledFunction()) {
294 InstructionClass Class = GetFunctionClass(F);
295 if (Class != IC_CallOrUser)
298 // None of the intrinsic functions do objc_release. For intrinsics, the
299 // only question is whether or not they may be users.
300 switch (F->getIntrinsicID()) {
301 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
302 case Intrinsic::stacksave: case Intrinsic::stackrestore:
303 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
304 case Intrinsic::objectsize: case Intrinsic::prefetch:
305 case Intrinsic::stackprotector:
306 case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
307 case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
308 case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
309 case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
310 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
311 case Intrinsic::invariant_start: case Intrinsic::invariant_end:
312 // Don't let dbg info affect our results.
313 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
314 // Short cut: Some intrinsics obviously don't use ObjC pointers.
320 return GetCallSiteClass(CI);
322 case Instruction::Invoke:
323 return GetCallSiteClass(cast<InvokeInst>(I));
324 case Instruction::BitCast:
325 case Instruction::GetElementPtr:
326 case Instruction::Select: case Instruction::PHI:
327 case Instruction::Ret: case Instruction::Br:
328 case Instruction::Switch: case Instruction::IndirectBr:
329 case Instruction::Alloca: case Instruction::VAArg:
330 case Instruction::Add: case Instruction::FAdd:
331 case Instruction::Sub: case Instruction::FSub:
332 case Instruction::Mul: case Instruction::FMul:
333 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
334 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
335 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
336 case Instruction::And: case Instruction::Or: case Instruction::Xor:
337 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
338 case Instruction::IntToPtr: case Instruction::FCmp:
339 case Instruction::FPTrunc: case Instruction::FPExt:
340 case Instruction::FPToUI: case Instruction::FPToSI:
341 case Instruction::UIToFP: case Instruction::SIToFP:
342 case Instruction::InsertElement: case Instruction::ExtractElement:
343 case Instruction::ShuffleVector:
344 case Instruction::ExtractValue:
346 case Instruction::ICmp:
347 // Comparing a pointer with null, or any other constant, isn't an
348 // interesting use, because we don't care what the pointer points to, or
349 // about the values of any other dynamic reference-counted pointers.
350 if (IsPotentialUse(I->getOperand(1)))
354 // For anything else, check all the operands.
355 // Note that this includes both operands of a Store: while the first
356 // operand isn't actually being dereferenced, it is being stored to
357 // memory where we can no longer track who might read it and dereference
358 // it, so we have to consider it potentially used.
359 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
361 if (IsPotentialUse(*OI))
366 // Otherwise, it's totally inert for ARC purposes.
370 /// GetBasicInstructionClass - Determine what kind of construct V is. This is
371 /// similar to GetInstructionClass except that it only detects objc runtine
372 /// calls. This allows it to be faster.
373 static InstructionClass GetBasicInstructionClass(const Value *V) {
374 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
375 if (const Function *F = CI->getCalledFunction())
376 return GetFunctionClass(F);
377 // Otherwise, be conservative.
378 return IC_CallOrUser;
381 // Otherwise, be conservative.
382 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
385 /// IsRetain - Test if the given class is objc_retain or
387 static bool IsRetain(InstructionClass Class) {
388 return Class == IC_Retain ||
389 Class == IC_RetainRV;
392 /// IsAutorelease - Test if the given class is objc_autorelease or
394 static bool IsAutorelease(InstructionClass Class) {
395 return Class == IC_Autorelease ||
396 Class == IC_AutoreleaseRV;
399 /// IsForwarding - Test if the given class represents instructions which return
400 /// their argument verbatim.
401 static bool IsForwarding(InstructionClass Class) {
402 // objc_retainBlock technically doesn't always return its argument
403 // verbatim, but it doesn't matter for our purposes here.
404 return Class == IC_Retain ||
405 Class == IC_RetainRV ||
406 Class == IC_Autorelease ||
407 Class == IC_AutoreleaseRV ||
408 Class == IC_RetainBlock ||
409 Class == IC_NoopCast;
412 /// IsNoopOnNull - Test if the given class represents instructions which do
413 /// nothing if passed a null pointer.
414 static bool IsNoopOnNull(InstructionClass Class) {
415 return Class == IC_Retain ||
416 Class == IC_RetainRV ||
417 Class == IC_Release ||
418 Class == IC_Autorelease ||
419 Class == IC_AutoreleaseRV ||
420 Class == IC_RetainBlock;
423 /// IsAlwaysTail - Test if the given class represents instructions which are
424 /// always safe to mark with the "tail" keyword.
425 static bool IsAlwaysTail(InstructionClass Class) {
426 // IC_RetainBlock may be given a stack argument.
427 return Class == IC_Retain ||
428 Class == IC_RetainRV ||
429 Class == IC_AutoreleaseRV;
432 /// \brief Test if the given class represents instructions which are never safe
433 /// to mark with the "tail" keyword.
434 static bool IsNeverTail(InstructionClass Class) {
435 /// It is never safe to tail call objc_autorelease since by tail calling
436 /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
437 /// fast autoreleasing causing our object to be potentially reclaimed from the
438 /// autorelease pool which violates the semantics of __autoreleasing types in
440 return Class == IC_Autorelease;
443 /// IsNoThrow - Test if the given class represents instructions which are always
444 /// safe to mark with the nounwind attribute..
445 static bool IsNoThrow(InstructionClass Class) {
446 // objc_retainBlock is not nounwind because it calls user copy constructors
447 // which could theoretically throw.
448 return Class == IC_Retain ||
449 Class == IC_RetainRV ||
450 Class == IC_Release ||
451 Class == IC_Autorelease ||
452 Class == IC_AutoreleaseRV ||
453 Class == IC_AutoreleasepoolPush ||
454 Class == IC_AutoreleasepoolPop;
457 /// EraseInstruction - Erase the given instruction. Many ObjC calls return their
458 /// argument verbatim, so if it's such a call and the return value has users,
459 /// replace them with the argument value.
460 static void EraseInstruction(Instruction *CI) {
461 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
463 bool Unused = CI->use_empty();
466 // Replace the return value with the argument.
467 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
468 "Can't delete non-forwarding instruction with users!");
469 CI->replaceAllUsesWith(OldArg);
472 CI->eraseFromParent();
475 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
478 /// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
479 /// also knows how to look through objc_retain and objc_autorelease calls, which
480 /// we know to return their argument verbatim.
481 static const Value *GetUnderlyingObjCPtr(const Value *V) {
483 V = GetUnderlyingObject(V);
484 if (!IsForwarding(GetBasicInstructionClass(V)))
486 V = cast<CallInst>(V)->getArgOperand(0);
492 /// StripPointerCastsAndObjCCalls - This is a wrapper around
493 /// Value::stripPointerCasts which also knows how to look through objc_retain
494 /// and objc_autorelease calls, which we know to return their argument verbatim.
495 static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
497 V = V->stripPointerCasts();
498 if (!IsForwarding(GetBasicInstructionClass(V)))
500 V = cast<CallInst>(V)->getArgOperand(0);
505 /// StripPointerCastsAndObjCCalls - This is a wrapper around
506 /// Value::stripPointerCasts which also knows how to look through objc_retain
507 /// and objc_autorelease calls, which we know to return their argument verbatim.
508 static Value *StripPointerCastsAndObjCCalls(Value *V) {
510 V = V->stripPointerCasts();
511 if (!IsForwarding(GetBasicInstructionClass(V)))
513 V = cast<CallInst>(V)->getArgOperand(0);
518 /// GetObjCArg - Assuming the given instruction is one of the special calls such
519 /// as objc_retain or objc_release, return the argument value, stripped of no-op
520 /// casts and forwarding calls.
521 static Value *GetObjCArg(Value *Inst) {
522 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
525 /// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
526 /// isObjCIdentifiedObject, except that it uses special knowledge of
527 /// ObjC conventions...
528 static bool IsObjCIdentifiedObject(const Value *V) {
529 // Assume that call results and arguments have their own "provenance".
530 // Constants (including GlobalVariables) and Allocas are never
531 // reference-counted.
532 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
533 isa<Argument>(V) || isa<Constant>(V) ||
537 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
538 const Value *Pointer =
539 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
540 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
541 // A constant pointer can't be pointing to an object on the heap. It may
542 // be reference-counted, but it won't be deleted.
543 if (GV->isConstant())
545 StringRef Name = GV->getName();
546 // These special variables are known to hold values which are not
547 // reference-counted pointers.
548 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
549 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
550 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
551 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
552 Name.startswith("\01l_objc_msgSend_fixup_"))
560 /// FindSingleUseIdentifiedObject - This is similar to
561 /// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
562 /// 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 /// ModuleHasARC - Test if the given module looks interesting to run ARC
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 /// DoesObjCBlockEscape - Test whether the given pointer, which is an
618 /// Objective C block pointer, does not "escape". This differs from regular
619 /// escape analysis in that a use as an argument to a call is not considered
621 static bool DoesObjCBlockEscape(const Value *BlockPtr) {
622 // Walk the def-use chains.
623 SmallVector<const Value *, 4> Worklist;
624 Worklist.push_back(BlockPtr);
626 const Value *V = Worklist.pop_back_val();
627 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
629 const User *UUser = *UI;
630 // Special - Use by a call (callee or argument) is not considered
632 switch (GetBasicInstructionClass(UUser)) {
637 case IC_AutoreleaseRV:
638 // These special functions make copies of their pointer arguments.
642 // Use by an instruction which copies the value is an escape if the
643 // result is an escape.
644 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
645 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
646 Worklist.push_back(UUser);
649 // Use by a load is not an escape.
650 if (isa<LoadInst>(UUser))
652 // Use by a store is not an escape if the use is the address.
653 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
654 if (V != SI->getValueOperand())
658 // Regular calls and other stuff are not considered escapes.
661 // Otherwise, conservatively assume an escape.
664 } while (!Worklist.empty());
670 //===----------------------------------------------------------------------===//
671 // ARC AliasAnalysis.
672 //===----------------------------------------------------------------------===//
674 #include "llvm/Analysis/AliasAnalysis.h"
675 #include "llvm/Analysis/Passes.h"
676 #include "llvm/Pass.h"
679 /// ObjCARCAliasAnalysis - This is a simple alias analysis
680 /// implementation that uses knowledge of ARC constructs to answer queries.
682 /// TODO: This class could be generalized to know about other ObjC-specific
683 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
684 /// even though their offsets are dynamic.
685 class ObjCARCAliasAnalysis : public ImmutablePass,
686 public AliasAnalysis {
688 static char ID; // Class identification, replacement for typeinfo
689 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
690 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
694 virtual void initializePass() {
695 InitializeAliasAnalysis(this);
698 /// getAdjustedAnalysisPointer - This method is used when a pass implements
699 /// an analysis interface through multiple inheritance. If needed, it
700 /// should override this to adjust the this pointer as needed for the
701 /// specified pass info.
702 virtual void *getAdjustedAnalysisPointer(const void *PI) {
703 if (PI == &AliasAnalysis::ID)
704 return static_cast<AliasAnalysis *>(this);
708 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
709 virtual AliasResult alias(const Location &LocA, const Location &LocB);
710 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
711 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
712 virtual ModRefBehavior getModRefBehavior(const Function *F);
713 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
714 const Location &Loc);
715 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
716 ImmutableCallSite CS2);
718 } // End of anonymous namespace
720 // Register this pass...
721 char ObjCARCAliasAnalysis::ID = 0;
722 INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
723 "ObjC-ARC-Based Alias Analysis", false, true, false)
725 ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
726 return new ObjCARCAliasAnalysis();
730 ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
731 AU.setPreservesAll();
732 AliasAnalysis::getAnalysisUsage(AU);
735 AliasAnalysis::AliasResult
736 ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
738 return AliasAnalysis::alias(LocA, LocB);
740 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
741 // precise alias query.
742 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
743 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
745 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
746 Location(SB, LocB.Size, LocB.TBAATag));
747 if (Result != MayAlias)
750 // If that failed, climb to the underlying object, including climbing through
751 // ObjC-specific no-ops, and try making an imprecise alias query.
752 const Value *UA = GetUnderlyingObjCPtr(SA);
753 const Value *UB = GetUnderlyingObjCPtr(SB);
754 if (UA != SA || UB != SB) {
755 Result = AliasAnalysis::alias(Location(UA), Location(UB));
756 // We can't use MustAlias or PartialAlias results here because
757 // GetUnderlyingObjCPtr may return an offsetted pointer value.
758 if (Result == NoAlias)
762 // If that failed, fail. We don't need to chain here, since that's covered
763 // by the earlier precise query.
768 ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
771 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
773 // First, strip off no-ops, including ObjC-specific no-ops, and try making
774 // a precise alias query.
775 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
776 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
780 // If that failed, climb to the underlying object, including climbing through
781 // ObjC-specific no-ops, and try making an imprecise alias query.
782 const Value *U = GetUnderlyingObjCPtr(S);
784 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
786 // If that failed, fail. We don't need to chain here, since that's covered
787 // by the earlier precise query.
791 AliasAnalysis::ModRefBehavior
792 ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
793 // We have nothing to do. Just chain to the next AliasAnalysis.
794 return AliasAnalysis::getModRefBehavior(CS);
797 AliasAnalysis::ModRefBehavior
798 ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
800 return AliasAnalysis::getModRefBehavior(F);
802 switch (GetFunctionClass(F)) {
804 return DoesNotAccessMemory;
809 return AliasAnalysis::getModRefBehavior(F);
812 AliasAnalysis::ModRefResult
813 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
815 return AliasAnalysis::getModRefInfo(CS, Loc);
817 switch (GetBasicInstructionClass(CS.getInstruction())) {
821 case IC_AutoreleaseRV:
823 case IC_AutoreleasepoolPush:
824 case IC_FusedRetainAutorelease:
825 case IC_FusedRetainAutoreleaseRV:
826 // These functions don't access any memory visible to the compiler.
827 // Note that this doesn't include objc_retainBlock, because it updates
828 // pointers when it copies block data.
834 return AliasAnalysis::getModRefInfo(CS, Loc);
837 AliasAnalysis::ModRefResult
838 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
839 ImmutableCallSite CS2) {
840 // TODO: Theoretically we could check for dependencies between objc_* calls
841 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
842 return AliasAnalysis::getModRefInfo(CS1, CS2);
845 //===----------------------------------------------------------------------===//
847 //===----------------------------------------------------------------------===//
849 #include "llvm/Support/InstIterator.h"
850 #include "llvm/Transforms/Scalar.h"
853 /// ObjCARCExpand - Early ARC transformations.
854 class ObjCARCExpand : public FunctionPass {
855 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
856 virtual bool doInitialization(Module &M);
857 virtual bool runOnFunction(Function &F);
859 /// Run - A flag indicating whether this optimization pass should run.
864 ObjCARCExpand() : FunctionPass(ID) {
865 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
870 char ObjCARCExpand::ID = 0;
871 INITIALIZE_PASS(ObjCARCExpand,
872 "objc-arc-expand", "ObjC ARC expansion", false, false)
874 Pass *llvm::createObjCARCExpandPass() {
875 return new ObjCARCExpand();
878 void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
879 AU.setPreservesCFG();
882 bool ObjCARCExpand::doInitialization(Module &M) {
883 Run = ModuleHasARC(M);
887 bool ObjCARCExpand::runOnFunction(Function &F) {
891 // If nothing in the Module uses ARC, don't do anything.
895 bool Changed = false;
897 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
898 Instruction *Inst = &*I;
900 DEBUG(dbgs() << "ObjCARCExpand: Visiting: " << *Inst << "\n");
902 switch (GetBasicInstructionClass(Inst)) {
906 case IC_AutoreleaseRV:
907 case IC_FusedRetainAutorelease:
908 case IC_FusedRetainAutoreleaseRV: {
909 // These calls return their argument verbatim, as a low-level
910 // optimization. However, this makes high-level optimizations
911 // harder. Undo any uses of this optimization that the front-end
912 // emitted here. We'll redo them in the contract pass.
914 Value *Value = cast<CallInst>(Inst)->getArgOperand(0);
915 DEBUG(dbgs() << "ObjCARCExpand: Old = " << *Inst << "\n"
916 " New = " << *Value << "\n");
917 Inst->replaceAllUsesWith(Value);
925 DEBUG(dbgs() << "ObjCARCExpand: Finished List.\n\n");
930 //===----------------------------------------------------------------------===//
931 // ARC autorelease pool elimination.
932 //===----------------------------------------------------------------------===//
934 #include "llvm/ADT/STLExtras.h"
935 #include "llvm/IR/Constants.h"
938 /// ObjCARCAPElim - Autorelease pool elimination.
939 class ObjCARCAPElim : public ModulePass {
940 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
941 virtual bool runOnModule(Module &M);
943 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
944 static bool OptimizeBB(BasicBlock *BB);
948 ObjCARCAPElim() : ModulePass(ID) {
949 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
954 char ObjCARCAPElim::ID = 0;
955 INITIALIZE_PASS(ObjCARCAPElim,
957 "ObjC ARC autorelease pool elimination",
960 Pass *llvm::createObjCARCAPElimPass() {
961 return new ObjCARCAPElim();
964 void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
965 AU.setPreservesCFG();
968 /// MayAutorelease - Interprocedurally determine if calls made by the
969 /// given call site can possibly produce autoreleases.
970 bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
971 if (const Function *Callee = CS.getCalledFunction()) {
972 if (Callee->isDeclaration() || Callee->mayBeOverridden())
974 for (Function::const_iterator I = Callee->begin(), E = Callee->end();
976 const BasicBlock *BB = I;
977 for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
979 if (ImmutableCallSite JCS = ImmutableCallSite(J))
980 // This recursion depth limit is arbitrary. It's just great
981 // enough to cover known interesting testcases.
983 !JCS.onlyReadsMemory() &&
984 MayAutorelease(JCS, Depth + 1))
993 bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
994 bool Changed = false;
996 Instruction *Push = 0;
997 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
998 Instruction *Inst = I++;
999 switch (GetBasicInstructionClass(Inst)) {
1000 case IC_AutoreleasepoolPush:
1003 case IC_AutoreleasepoolPop:
1004 // If this pop matches a push and nothing in between can autorelease,
1006 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
1008 DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop autorelease pair:\n"
1009 << " Pop: " << *Inst << "\n"
1010 << " Push: " << *Push << "\n");
1011 Inst->eraseFromParent();
1012 Push->eraseFromParent();
1017 if (MayAutorelease(ImmutableCallSite(Inst)))
1028 bool ObjCARCAPElim::runOnModule(Module &M) {
1032 // If nothing in the Module uses ARC, don't do anything.
1033 if (!ModuleHasARC(M))
1036 // Find the llvm.global_ctors variable, as the first step in
1037 // identifying the global constructors. In theory, unnecessary autorelease
1038 // pools could occur anywhere, but in practice it's pretty rare. Global
1039 // ctors are a place where autorelease pools get inserted automatically,
1040 // so it's pretty common for them to be unnecessary, and it's pretty
1041 // profitable to eliminate them.
1042 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1046 assert(GV->hasDefinitiveInitializer() &&
1047 "llvm.global_ctors is uncooperative!");
1049 bool Changed = false;
1051 // Dig the constructor functions out of GV's initializer.
1052 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1053 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1056 // llvm.global_ctors is an array of pairs where the second members
1057 // are constructor functions.
1058 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1059 // If the user used a constructor function with the wrong signature and
1060 // it got bitcasted or whatever, look the other way.
1063 // Only look at function definitions.
1064 if (F->isDeclaration())
1066 // Only look at functions with one basic block.
1067 if (llvm::next(F->begin()) != F->end())
1069 // Ok, a single-block constructor function definition. Try to optimize it.
1070 Changed |= OptimizeBB(F->begin());
1076 //===----------------------------------------------------------------------===//
1077 // ARC optimization.
1078 //===----------------------------------------------------------------------===//
1080 // TODO: On code like this:
1083 // stuff_that_cannot_release()
1084 // objc_autorelease(%x)
1085 // stuff_that_cannot_release()
1087 // stuff_that_cannot_release()
1088 // objc_autorelease(%x)
1090 // The second retain and autorelease can be deleted.
1092 // TODO: It should be possible to delete
1093 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
1094 // pairs if nothing is actually autoreleased between them. Also, autorelease
1095 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1096 // after inlining) can be turned into plain release calls.
1098 // TODO: Critical-edge splitting. If the optimial insertion point is
1099 // a critical edge, the current algorithm has to fail, because it doesn't
1100 // know how to split edges. It should be possible to make the optimizer
1101 // think in terms of edges, rather than blocks, and then split critical
1104 // TODO: OptimizeSequences could generalized to be Interprocedural.
1106 // TODO: Recognize that a bunch of other objc runtime calls have
1107 // non-escaping arguments and non-releasing arguments, and may be
1108 // non-autoreleasing.
1110 // TODO: Sink autorelease calls as far as possible. Unfortunately we
1111 // usually can't sink them past other calls, which would be the main
1112 // case where it would be useful.
1114 // TODO: The pointer returned from objc_loadWeakRetained is retained.
1116 // TODO: Delete release+retain pairs (rare).
1118 #include "llvm/ADT/SmallPtrSet.h"
1119 #include "llvm/ADT/Statistic.h"
1120 #include "llvm/IR/LLVMContext.h"
1121 #include "llvm/Support/CFG.h"
1123 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1124 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1125 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1126 STATISTIC(NumRets, "Number of return value forwarding "
1127 "retain+autoreleaes eliminated");
1128 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1129 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1132 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1133 /// uses many of the same techniques, except it uses special ObjC-specific
1134 /// reasoning about pointer relationships.
1135 class ProvenanceAnalysis {
1138 typedef std::pair<const Value *, const Value *> ValuePairTy;
1139 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1140 CachedResultsTy CachedResults;
1142 bool relatedCheck(const Value *A, const Value *B);
1143 bool relatedSelect(const SelectInst *A, const Value *B);
1144 bool relatedPHI(const PHINode *A, const Value *B);
1146 void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1147 ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1150 ProvenanceAnalysis() {}
1152 void setAA(AliasAnalysis *aa) { AA = aa; }
1154 AliasAnalysis *getAA() const { return AA; }
1156 bool related(const Value *A, const Value *B);
1159 CachedResults.clear();
1164 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1165 // If the values are Selects with the same condition, we can do a more precise
1166 // check: just check for relations between the values on corresponding arms.
1167 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
1168 if (A->getCondition() == SB->getCondition())
1169 return related(A->getTrueValue(), SB->getTrueValue()) ||
1170 related(A->getFalseValue(), SB->getFalseValue());
1172 // Check both arms of the Select node individually.
1173 return related(A->getTrueValue(), B) ||
1174 related(A->getFalseValue(), B);
1177 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1178 // If the values are PHIs in the same block, we can do a more precise as well
1179 // as efficient check: just check for relations between the values on
1180 // corresponding edges.
1181 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1182 if (PNB->getParent() == A->getParent()) {
1183 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1184 if (related(A->getIncomingValue(i),
1185 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1190 // Check each unique source of the PHI node against B.
1191 SmallPtrSet<const Value *, 4> UniqueSrc;
1192 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1193 const Value *PV1 = A->getIncomingValue(i);
1194 if (UniqueSrc.insert(PV1) && related(PV1, B))
1198 // All of the arms checked out.
1202 /// isStoredObjCPointer - Test if the value of P, or any value covered by its
1203 /// provenance, is ever stored within the function (not counting callees).
1204 static bool isStoredObjCPointer(const Value *P) {
1205 SmallPtrSet<const Value *, 8> Visited;
1206 SmallVector<const Value *, 8> Worklist;
1207 Worklist.push_back(P);
1210 P = Worklist.pop_back_val();
1211 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1213 const User *Ur = *UI;
1214 if (isa<StoreInst>(Ur)) {
1215 if (UI.getOperandNo() == 0)
1216 // The pointer is stored.
1218 // The pointed is stored through.
1221 if (isa<CallInst>(Ur))
1222 // The pointer is passed as an argument, ignore this.
1224 if (isa<PtrToIntInst>(P))
1225 // Assume the worst.
1227 if (Visited.insert(Ur))
1228 Worklist.push_back(Ur);
1230 } while (!Worklist.empty());
1232 // Everything checked out.
1236 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1237 // Skip past provenance pass-throughs.
1238 A = GetUnderlyingObjCPtr(A);
1239 B = GetUnderlyingObjCPtr(B);
1245 // Ask regular AliasAnalysis, for a first approximation.
1246 switch (AA->alias(A, B)) {
1247 case AliasAnalysis::NoAlias:
1249 case AliasAnalysis::MustAlias:
1250 case AliasAnalysis::PartialAlias:
1252 case AliasAnalysis::MayAlias:
1256 bool AIsIdentified = IsObjCIdentifiedObject(A);
1257 bool BIsIdentified = IsObjCIdentifiedObject(B);
1259 // An ObjC-Identified object can't alias a load if it is never locally stored.
1260 if (AIsIdentified) {
1261 // Check for an obvious escape.
1262 if (isa<LoadInst>(B))
1263 return isStoredObjCPointer(A);
1264 if (BIsIdentified) {
1265 // Check for an obvious escape.
1266 if (isa<LoadInst>(A))
1267 return isStoredObjCPointer(B);
1268 // Both pointers are identified and escapes aren't an evident problem.
1271 } else if (BIsIdentified) {
1272 // Check for an obvious escape.
1273 if (isa<LoadInst>(A))
1274 return isStoredObjCPointer(B);
1277 // Special handling for PHI and Select.
1278 if (const PHINode *PN = dyn_cast<PHINode>(A))
1279 return relatedPHI(PN, B);
1280 if (const PHINode *PN = dyn_cast<PHINode>(B))
1281 return relatedPHI(PN, A);
1282 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1283 return relatedSelect(S, B);
1284 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1285 return relatedSelect(S, A);
1291 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1292 // Begin by inserting a conservative value into the map. If the insertion
1293 // fails, we have the answer already. If it succeeds, leave it there until we
1294 // compute the real answer to guard against recursive queries.
1295 if (A > B) std::swap(A, B);
1296 std::pair<CachedResultsTy::iterator, bool> Pair =
1297 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1299 return Pair.first->second;
1301 bool Result = relatedCheck(A, B);
1302 CachedResults[ValuePairTy(A, B)] = Result;
1307 // Sequence - A sequence of states that a pointer may go through in which an
1308 // objc_retain and objc_release are actually needed.
1311 S_Retain, ///< objc_retain(x)
1312 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1313 S_Use, ///< any use of x
1314 S_Stop, ///< like S_Release, but code motion is stopped
1315 S_Release, ///< objc_release(x)
1316 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1320 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1324 if (A == S_None || B == S_None)
1327 if (A > B) std::swap(A, B);
1329 // Choose the side which is further along in the sequence.
1330 if ((A == S_Retain || A == S_CanRelease) &&
1331 (B == S_CanRelease || B == S_Use))
1334 // Choose the side which is further along in the sequence.
1335 if ((A == S_Use || A == S_CanRelease) &&
1336 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
1338 // If both sides are releases, choose the more conservative one.
1339 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1341 if (A == S_Release && B == S_MovableRelease)
1349 /// RRInfo - Unidirectional information about either a
1350 /// retain-decrement-use-release sequence or release-use-decrement-retain
1351 /// reverese sequence.
1353 /// KnownSafe - After an objc_retain, the reference count of the referenced
1354 /// object is known to be positive. Similarly, before an objc_release, the
1355 /// reference count of the referenced object is known to be positive. If
1356 /// there are retain-release pairs in code regions where the retain count
1357 /// is known to be positive, they can be eliminated, regardless of any side
1358 /// effects between them.
1360 /// Also, a retain+release pair nested within another retain+release
1361 /// pair all on the known same pointer value can be eliminated, regardless
1362 /// of any intervening side effects.
1364 /// KnownSafe is true when either of these conditions is satisfied.
1367 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1368 /// opposed to objc_retain calls).
1371 /// IsTailCallRelease - True of the objc_release calls are all marked
1372 /// with the "tail" keyword.
1373 bool IsTailCallRelease;
1375 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1376 /// a clang.imprecise_release tag, this is the metadata tag.
1377 MDNode *ReleaseMetadata;
1379 /// Calls - For a top-down sequence, the set of objc_retains or
1380 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1381 SmallPtrSet<Instruction *, 2> Calls;
1383 /// ReverseInsertPts - The set of optimal insert positions for
1384 /// moving calls in the opposite sequence.
1385 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1388 KnownSafe(false), IsRetainBlock(false),
1389 IsTailCallRelease(false),
1390 ReleaseMetadata(0) {}
1396 void RRInfo::clear() {
1398 IsRetainBlock = false;
1399 IsTailCallRelease = false;
1400 ReleaseMetadata = 0;
1402 ReverseInsertPts.clear();
1406 /// PtrState - This class summarizes several per-pointer runtime properties
1407 /// which are propogated through the flow graph.
1409 /// KnownPositiveRefCount - True if the reference count is known to
1411 bool KnownPositiveRefCount;
1413 /// Partial - True of we've seen an opportunity for partial RR elimination,
1414 /// such as pushing calls into a CFG triangle or into one side of a
1418 /// Seq - The current position in the sequence.
1422 /// RRI - Unidirectional information about the current sequence.
1423 /// TODO: Encapsulate this better.
1426 PtrState() : KnownPositiveRefCount(false), Partial(false),
1429 void SetKnownPositiveRefCount() {
1430 KnownPositiveRefCount = true;
1433 void ClearRefCount() {
1434 KnownPositiveRefCount = false;
1437 bool IsKnownIncremented() const {
1438 return KnownPositiveRefCount;
1441 void SetSeq(Sequence NewSeq) {
1445 Sequence GetSeq() const {
1449 void ClearSequenceProgress() {
1450 ResetSequenceProgress(S_None);
1453 void ResetSequenceProgress(Sequence NewSeq) {
1459 void Merge(const PtrState &Other, bool TopDown);
1464 PtrState::Merge(const PtrState &Other, bool TopDown) {
1465 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1466 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
1468 // We can't merge a plain objc_retain with an objc_retainBlock.
1469 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1472 // If we're not in a sequence (anymore), drop all associated state.
1473 if (Seq == S_None) {
1476 } else if (Partial || Other.Partial) {
1477 // If we're doing a merge on a path that's previously seen a partial
1478 // merge, conservatively drop the sequence, to avoid doing partial
1479 // RR elimination. If the branch predicates for the two merge differ,
1480 // mixing them is unsafe.
1481 ClearSequenceProgress();
1483 // Conservatively merge the ReleaseMetadata information.
1484 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1485 RRI.ReleaseMetadata = 0;
1487 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
1488 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1489 Other.RRI.IsTailCallRelease;
1490 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1492 // Merge the insert point sets. If there are any differences,
1493 // that makes this a partial merge.
1494 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
1495 for (SmallPtrSet<Instruction *, 2>::const_iterator
1496 I = Other.RRI.ReverseInsertPts.begin(),
1497 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1498 Partial |= RRI.ReverseInsertPts.insert(*I);
1503 /// BBState - Per-BasicBlock state.
1505 /// TopDownPathCount - The number of unique control paths from the entry
1506 /// which can reach this block.
1507 unsigned TopDownPathCount;
1509 /// BottomUpPathCount - The number of unique control paths to exits
1510 /// from this block.
1511 unsigned BottomUpPathCount;
1513 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1514 typedef MapVector<const Value *, PtrState> MapTy;
1516 /// PerPtrTopDown - The top-down traversal uses this to record information
1517 /// known about a pointer at the bottom of each block.
1518 MapTy PerPtrTopDown;
1520 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1521 /// known about a pointer at the top of each block.
1522 MapTy PerPtrBottomUp;
1524 /// Preds, Succs - Effective successors and predecessors of the current
1525 /// block (this ignores ignorable edges and ignored backedges).
1526 SmallVector<BasicBlock *, 2> Preds;
1527 SmallVector<BasicBlock *, 2> Succs;
1530 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1532 typedef MapTy::iterator ptr_iterator;
1533 typedef MapTy::const_iterator ptr_const_iterator;
1535 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1536 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1537 ptr_const_iterator top_down_ptr_begin() const {
1538 return PerPtrTopDown.begin();
1540 ptr_const_iterator top_down_ptr_end() const {
1541 return PerPtrTopDown.end();
1544 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1545 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1546 ptr_const_iterator bottom_up_ptr_begin() const {
1547 return PerPtrBottomUp.begin();
1549 ptr_const_iterator bottom_up_ptr_end() const {
1550 return PerPtrBottomUp.end();
1553 /// SetAsEntry - Mark this block as being an entry block, which has one
1554 /// path from the entry by definition.
1555 void SetAsEntry() { TopDownPathCount = 1; }
1557 /// SetAsExit - Mark this block as being an exit block, which has one
1558 /// path to an exit by definition.
1559 void SetAsExit() { BottomUpPathCount = 1; }
1561 PtrState &getPtrTopDownState(const Value *Arg) {
1562 return PerPtrTopDown[Arg];
1565 PtrState &getPtrBottomUpState(const Value *Arg) {
1566 return PerPtrBottomUp[Arg];
1569 void clearBottomUpPointers() {
1570 PerPtrBottomUp.clear();
1573 void clearTopDownPointers() {
1574 PerPtrTopDown.clear();
1577 void InitFromPred(const BBState &Other);
1578 void InitFromSucc(const BBState &Other);
1579 void MergePred(const BBState &Other);
1580 void MergeSucc(const BBState &Other);
1582 /// GetAllPathCount - Return the number of possible unique paths from an
1583 /// entry to an exit which pass through this block. This is only valid
1584 /// after both the top-down and bottom-up traversals are complete.
1585 unsigned GetAllPathCount() const {
1586 assert(TopDownPathCount != 0);
1587 assert(BottomUpPathCount != 0);
1588 return TopDownPathCount * BottomUpPathCount;
1591 // Specialized CFG utilities.
1592 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
1593 edge_iterator pred_begin() { return Preds.begin(); }
1594 edge_iterator pred_end() { return Preds.end(); }
1595 edge_iterator succ_begin() { return Succs.begin(); }
1596 edge_iterator succ_end() { return Succs.end(); }
1598 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1599 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1601 bool isExit() const { return Succs.empty(); }
1605 void BBState::InitFromPred(const BBState &Other) {
1606 PerPtrTopDown = Other.PerPtrTopDown;
1607 TopDownPathCount = Other.TopDownPathCount;
1610 void BBState::InitFromSucc(const BBState &Other) {
1611 PerPtrBottomUp = Other.PerPtrBottomUp;
1612 BottomUpPathCount = Other.BottomUpPathCount;
1615 /// MergePred - The top-down traversal uses this to merge information about
1616 /// predecessors to form the initial state for a new block.
1617 void BBState::MergePred(const BBState &Other) {
1618 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1619 // loop backedge. Loop backedges are special.
1620 TopDownPathCount += Other.TopDownPathCount;
1622 // Check for overflow. If we have overflow, fall back to conservative behavior.
1623 if (TopDownPathCount < Other.TopDownPathCount) {
1624 clearTopDownPointers();
1628 // For each entry in the other set, if our set has an entry with the same key,
1629 // merge the entries. Otherwise, copy the entry and merge it with an empty
1631 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1632 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1633 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1634 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1638 // For each entry in our set, if the other set doesn't have an entry with the
1639 // same key, force it to merge with an empty entry.
1640 for (ptr_iterator MI = top_down_ptr_begin(),
1641 ME = top_down_ptr_end(); MI != ME; ++MI)
1642 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1643 MI->second.Merge(PtrState(), /*TopDown=*/true);
1646 /// MergeSucc - The bottom-up traversal uses this to merge information about
1647 /// successors to form the initial state for a new block.
1648 void BBState::MergeSucc(const BBState &Other) {
1649 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1650 // loop backedge. Loop backedges are special.
1651 BottomUpPathCount += Other.BottomUpPathCount;
1653 // Check for overflow. If we have overflow, fall back to conservative behavior.
1654 if (BottomUpPathCount < Other.BottomUpPathCount) {
1655 clearBottomUpPointers();
1659 // For each entry in the other set, if our set has an entry with the
1660 // same key, merge the entries. Otherwise, copy the entry and merge
1661 // it with an empty entry.
1662 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1663 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1664 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1665 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1669 // For each entry in our set, if the other set doesn't have an entry
1670 // with the same key, force it to merge with an empty entry.
1671 for (ptr_iterator MI = bottom_up_ptr_begin(),
1672 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1673 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1674 MI->second.Merge(PtrState(), /*TopDown=*/false);
1678 /// ObjCARCOpt - The main ARC optimization pass.
1679 class ObjCARCOpt : public FunctionPass {
1681 ProvenanceAnalysis PA;
1683 /// Run - A flag indicating whether this optimization pass should run.
1686 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1687 /// functions, for use in creating calls to them. These are initialized
1688 /// lazily to avoid cluttering up the Module with unused declarations.
1689 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
1690 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
1692 /// UsedInThisFunciton - Flags which determine whether each of the
1693 /// interesting runtine functions is in fact used in the current function.
1694 unsigned UsedInThisFunction;
1696 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1698 unsigned ImpreciseReleaseMDKind;
1700 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
1702 unsigned CopyOnEscapeMDKind;
1704 /// NoObjCARCExceptionsMDKind - The Metadata Kind for
1705 /// clang.arc.no_objc_arc_exceptions metadata.
1706 unsigned NoObjCARCExceptionsMDKind;
1708 Constant *getRetainRVCallee(Module *M);
1709 Constant *getAutoreleaseRVCallee(Module *M);
1710 Constant *getReleaseCallee(Module *M);
1711 Constant *getRetainCallee(Module *M);
1712 Constant *getRetainBlockCallee(Module *M);
1713 Constant *getAutoreleaseCallee(Module *M);
1715 bool IsRetainBlockOptimizable(const Instruction *Inst);
1717 void OptimizeRetainCall(Function &F, Instruction *Retain);
1718 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1719 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1720 void OptimizeIndividualCalls(Function &F);
1722 void CheckForCFGHazards(const BasicBlock *BB,
1723 DenseMap<const BasicBlock *, BBState> &BBStates,
1724 BBState &MyStates) const;
1725 bool VisitInstructionBottomUp(Instruction *Inst,
1727 MapVector<Value *, RRInfo> &Retains,
1729 bool VisitBottomUp(BasicBlock *BB,
1730 DenseMap<const BasicBlock *, BBState> &BBStates,
1731 MapVector<Value *, RRInfo> &Retains);
1732 bool VisitInstructionTopDown(Instruction *Inst,
1733 DenseMap<Value *, RRInfo> &Releases,
1735 bool VisitTopDown(BasicBlock *BB,
1736 DenseMap<const BasicBlock *, BBState> &BBStates,
1737 DenseMap<Value *, RRInfo> &Releases);
1738 bool Visit(Function &F,
1739 DenseMap<const BasicBlock *, BBState> &BBStates,
1740 MapVector<Value *, RRInfo> &Retains,
1741 DenseMap<Value *, RRInfo> &Releases);
1743 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1744 MapVector<Value *, RRInfo> &Retains,
1745 DenseMap<Value *, RRInfo> &Releases,
1746 SmallVectorImpl<Instruction *> &DeadInsts,
1749 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1750 MapVector<Value *, RRInfo> &Retains,
1751 DenseMap<Value *, RRInfo> &Releases,
1754 void OptimizeWeakCalls(Function &F);
1756 bool OptimizeSequences(Function &F);
1758 void OptimizeReturns(Function &F);
1760 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1761 virtual bool doInitialization(Module &M);
1762 virtual bool runOnFunction(Function &F);
1763 virtual void releaseMemory();
1767 ObjCARCOpt() : FunctionPass(ID) {
1768 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1773 char ObjCARCOpt::ID = 0;
1774 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1775 "objc-arc", "ObjC ARC optimization", false, false)
1776 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1777 INITIALIZE_PASS_END(ObjCARCOpt,
1778 "objc-arc", "ObjC ARC optimization", false, false)
1780 Pass *llvm::createObjCARCOptPass() {
1781 return new ObjCARCOpt();
1784 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1785 AU.addRequired<ObjCARCAliasAnalysis>();
1786 AU.addRequired<AliasAnalysis>();
1787 // ARC optimization doesn't currently split critical edges.
1788 AU.setPreservesCFG();
1791 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1792 // Without the magic metadata tag, we have to assume this might be an
1793 // objc_retainBlock call inserted to convert a block pointer to an id,
1794 // in which case it really is needed.
1795 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1798 // If the pointer "escapes" (not including being used in a call),
1799 // the copy may be needed.
1800 if (DoesObjCBlockEscape(Inst))
1803 // Otherwise, it's not needed.
1807 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1808 if (!RetainRVCallee) {
1809 LLVMContext &C = M->getContext();
1810 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1811 Type *Params[] = { I8X };
1812 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1813 AttributeSet Attribute =
1814 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1815 Attribute::get(C, Attribute::NoUnwind));
1817 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1820 return RetainRVCallee;
1823 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1824 if (!AutoreleaseRVCallee) {
1825 LLVMContext &C = M->getContext();
1826 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1827 Type *Params[] = { I8X };
1828 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1829 AttributeSet Attribute =
1830 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1831 Attribute::get(C, Attribute::NoUnwind));
1832 AutoreleaseRVCallee =
1833 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1836 return AutoreleaseRVCallee;
1839 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1840 if (!ReleaseCallee) {
1841 LLVMContext &C = M->getContext();
1842 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1843 AttributeSet Attribute =
1844 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1845 Attribute::get(C, Attribute::NoUnwind));
1847 M->getOrInsertFunction(
1849 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1852 return ReleaseCallee;
1855 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1856 if (!RetainCallee) {
1857 LLVMContext &C = M->getContext();
1858 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1859 AttributeSet Attribute =
1860 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1861 Attribute::get(C, Attribute::NoUnwind));
1863 M->getOrInsertFunction(
1865 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1868 return RetainCallee;
1871 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1872 if (!RetainBlockCallee) {
1873 LLVMContext &C = M->getContext();
1874 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1875 // objc_retainBlock is not nounwind because it calls user copy constructors
1876 // which could theoretically throw.
1878 M->getOrInsertFunction(
1880 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1883 return RetainBlockCallee;
1886 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1887 if (!AutoreleaseCallee) {
1888 LLVMContext &C = M->getContext();
1889 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1890 AttributeSet Attribute =
1891 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1892 Attribute::get(C, Attribute::NoUnwind));
1894 M->getOrInsertFunction(
1896 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1899 return AutoreleaseCallee;
1902 /// IsPotentialUse - Test whether the given value is possible a
1903 /// reference-counted pointer, including tests which utilize AliasAnalysis.
1904 static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
1905 // First make the rudimentary check.
1906 if (!IsPotentialUse(Op))
1909 // Objects in constant memory are not reference-counted.
1910 if (AA.pointsToConstantMemory(Op))
1913 // Pointers in constant memory are not pointing to reference-counted objects.
1914 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1915 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1918 // Otherwise assume the worst.
1922 /// CanAlterRefCount - Test whether the given instruction can result in a
1923 /// reference count modification (positive or negative) for the pointer's
1926 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1927 ProvenanceAnalysis &PA, InstructionClass Class) {
1929 case IC_Autorelease:
1930 case IC_AutoreleaseRV:
1932 // These operations never directly modify a reference count.
1937 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1938 assert(CS && "Only calls can alter reference counts!");
1940 // See if AliasAnalysis can help us with the call.
1941 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1942 if (AliasAnalysis::onlyReadsMemory(MRB))
1944 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1945 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1947 const Value *Op = *I;
1948 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
1954 // Assume the worst.
1958 /// CanUse - Test whether the given instruction can "use" the given pointer's
1959 /// object in a way that requires the reference count to be positive.
1961 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1962 InstructionClass Class) {
1963 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1964 if (Class == IC_Call)
1967 // Consider various instructions which may have pointer arguments which are
1969 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1970 // Comparing a pointer with null, or any other constant, isn't really a use,
1971 // because we don't care what the pointer points to, or about the values
1972 // of any other dynamic reference-counted pointers.
1973 if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
1975 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1976 // For calls, just check the arguments (and not the callee operand).
1977 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1978 OE = CS.arg_end(); OI != OE; ++OI) {
1979 const Value *Op = *OI;
1980 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
1984 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1985 // Special-case stores, because we don't care about the stored value, just
1986 // the store address.
1987 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1988 // If we can't tell what the underlying object was, assume there is a
1990 return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
1993 // Check each operand for a match.
1994 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1996 const Value *Op = *OI;
1997 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
2003 /// CanInterruptRV - Test whether the given instruction can autorelease
2004 /// any pointer or cause an autoreleasepool pop.
2006 CanInterruptRV(InstructionClass Class) {
2008 case IC_AutoreleasepoolPop:
2011 case IC_Autorelease:
2012 case IC_AutoreleaseRV:
2013 case IC_FusedRetainAutorelease:
2014 case IC_FusedRetainAutoreleaseRV:
2022 /// DependenceKind - There are several kinds of dependence-like concepts in
2024 enum DependenceKind {
2025 NeedsPositiveRetainCount,
2026 AutoreleasePoolBoundary,
2027 CanChangeRetainCount,
2028 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
2029 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
2030 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
2034 /// Depends - Test if there can be dependencies on Inst through Arg. This
2035 /// function only tests dependencies relevant for removing pairs of calls.
2037 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2038 ProvenanceAnalysis &PA) {
2039 // If we've reached the definition of Arg, stop.
2044 case NeedsPositiveRetainCount: {
2045 InstructionClass Class = GetInstructionClass(Inst);
2047 case IC_AutoreleasepoolPop:
2048 case IC_AutoreleasepoolPush:
2052 return CanUse(Inst, Arg, PA, Class);
2056 case AutoreleasePoolBoundary: {
2057 InstructionClass Class = GetInstructionClass(Inst);
2059 case IC_AutoreleasepoolPop:
2060 case IC_AutoreleasepoolPush:
2061 // These mark the end and begin of an autorelease pool scope.
2064 // Nothing else does this.
2069 case CanChangeRetainCount: {
2070 InstructionClass Class = GetInstructionClass(Inst);
2072 case IC_AutoreleasepoolPop:
2073 // Conservatively assume this can decrement any count.
2075 case IC_AutoreleasepoolPush:
2079 return CanAlterRefCount(Inst, Arg, PA, Class);
2083 case RetainAutoreleaseDep:
2084 switch (GetBasicInstructionClass(Inst)) {
2085 case IC_AutoreleasepoolPop:
2086 case IC_AutoreleasepoolPush:
2087 // Don't merge an objc_autorelease with an objc_retain inside a different
2088 // autoreleasepool scope.
2092 // Check for a retain of the same pointer for merging.
2093 return GetObjCArg(Inst) == Arg;
2095 // Nothing else matters for objc_retainAutorelease formation.
2099 case RetainAutoreleaseRVDep: {
2100 InstructionClass Class = GetBasicInstructionClass(Inst);
2104 // Check for a retain of the same pointer for merging.
2105 return GetObjCArg(Inst) == Arg;
2107 // Anything that can autorelease interrupts
2108 // retainAutoreleaseReturnValue formation.
2109 return CanInterruptRV(Class);
2114 return CanInterruptRV(GetBasicInstructionClass(Inst));
2117 llvm_unreachable("Invalid dependence flavor");
2120 /// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2121 /// find local and non-local dependencies on Arg.
2122 /// TODO: Cache results?
2124 FindDependencies(DependenceKind Flavor,
2126 BasicBlock *StartBB, Instruction *StartInst,
2127 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2128 SmallPtrSet<const BasicBlock *, 4> &Visited,
2129 ProvenanceAnalysis &PA) {
2130 BasicBlock::iterator StartPos = StartInst;
2132 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2133 Worklist.push_back(std::make_pair(StartBB, StartPos));
2135 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2136 Worklist.pop_back_val();
2137 BasicBlock *LocalStartBB = Pair.first;
2138 BasicBlock::iterator LocalStartPos = Pair.second;
2139 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2141 if (LocalStartPos == StartBBBegin) {
2142 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2144 // If we've reached the function entry, produce a null dependence.
2145 DependingInstructions.insert(0);
2147 // Add the predecessors to the worklist.
2149 BasicBlock *PredBB = *PI;
2150 if (Visited.insert(PredBB))
2151 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2152 } while (++PI != PE);
2156 Instruction *Inst = --LocalStartPos;
2157 if (Depends(Flavor, Inst, Arg, PA)) {
2158 DependingInstructions.insert(Inst);
2162 } while (!Worklist.empty());
2164 // Determine whether the original StartBB post-dominates all of the blocks we
2165 // visited. If not, insert a sentinal indicating that most optimizations are
2167 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2168 E = Visited.end(); I != E; ++I) {
2169 const BasicBlock *BB = *I;
2172 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2173 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2174 const BasicBlock *Succ = *SI;
2175 if (Succ != StartBB && !Visited.count(Succ)) {
2176 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2183 static bool isNullOrUndef(const Value *V) {
2184 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2187 static bool isNoopInstruction(const Instruction *I) {
2188 return isa<BitCastInst>(I) ||
2189 (isa<GetElementPtrInst>(I) &&
2190 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2193 /// OptimizeRetainCall - Turn objc_retain into
2194 /// objc_retainAutoreleasedReturnValue if the operand is a return value.
2196 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
2197 ImmutableCallSite CS(GetObjCArg(Retain));
2198 const Instruction *Call = CS.getInstruction();
2200 if (Call->getParent() != Retain->getParent()) return;
2202 // Check that the call is next to the retain.
2203 BasicBlock::const_iterator I = Call;
2205 while (isNoopInstruction(I)) ++I;
2209 // Turn it to an objc_retainAutoreleasedReturnValue..
2213 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
2214 "objc_retainAutoreleasedReturnValue => "
2215 "objc_retain since the operand is not a return value.\n"
2217 << *Retain << "\n");
2219 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2221 DEBUG(dbgs() << " New: "
2222 << *Retain << "\n");
2225 /// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
2226 /// objc_retain if the operand is not a return value. Or, if it can be paired
2227 /// with an objc_autoreleaseReturnValue, delete the pair and return true.
2229 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
2230 // Check for the argument being from an immediately preceding call or invoke.
2231 const Value *Arg = GetObjCArg(RetainRV);
2232 ImmutableCallSite CS(Arg);
2233 if (const Instruction *Call = CS.getInstruction()) {
2234 if (Call->getParent() == RetainRV->getParent()) {
2235 BasicBlock::const_iterator I = Call;
2237 while (isNoopInstruction(I)) ++I;
2238 if (&*I == RetainRV)
2240 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
2241 BasicBlock *RetainRVParent = RetainRV->getParent();
2242 if (II->getNormalDest() == RetainRVParent) {
2243 BasicBlock::const_iterator I = RetainRVParent->begin();
2244 while (isNoopInstruction(I)) ++I;
2245 if (&*I == RetainRV)
2251 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2252 // pointer. In this case, we can delete the pair.
2253 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2255 do --I; while (I != Begin && isNoopInstruction(I));
2256 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2257 GetObjCArg(I) == Arg) {
2261 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
2262 << " Erasing " << *RetainRV
2265 EraseInstruction(I);
2266 EraseInstruction(RetainRV);
2271 // Turn it to a plain objc_retain.
2275 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
2276 "objc_retainAutoreleasedReturnValue => "
2277 "objc_retain since the operand is not a return value.\n"
2279 << *RetainRV << "\n");
2281 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2283 DEBUG(dbgs() << " New: "
2284 << *RetainRV << "\n");
2289 /// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2290 /// objc_autorelease if the result is not used as a return value.
2292 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
2293 // Check for a return of the pointer value.
2294 const Value *Ptr = GetObjCArg(AutoreleaseRV);
2295 SmallVector<const Value *, 2> Users;
2296 Users.push_back(Ptr);
2298 Ptr = Users.pop_back_val();
2299 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2301 const User *I = *UI;
2302 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2304 if (isa<BitCastInst>(I))
2307 } while (!Users.empty());
2312 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
2313 "objc_autoreleaseReturnValue => "
2314 "objc_autorelease since its operand is not used as a return "
2317 << *AutoreleaseRV << "\n");
2319 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
2321 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2322 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
2324 DEBUG(dbgs() << " New: "
2325 << *AutoreleaseRV << "\n");
2329 /// OptimizeIndividualCalls - Visit each call, one at a time, and make
2330 /// simplifications without doing any additional analysis.
2331 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2332 // Reset all the flags in preparation for recomputing them.
2333 UsedInThisFunction = 0;
2335 // Visit all objc_* calls in F.
2336 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2337 Instruction *Inst = &*I++;
2339 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: " <<
2342 InstructionClass Class = GetBasicInstructionClass(Inst);
2347 // Delete no-op casts. These function calls have special semantics, but
2348 // the semantics are entirely implemented via lowering in the front-end,
2349 // so by the time they reach the optimizer, they are just no-op calls
2350 // which return their argument.
2352 // There are gray areas here, as the ability to cast reference-counted
2353 // pointers to raw void* and back allows code to break ARC assumptions,
2354 // however these are currently considered to be unimportant.
2358 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
2359 " " << *Inst << "\n");
2360 EraseInstruction(Inst);
2363 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2366 case IC_LoadWeakRetained:
2368 case IC_DestroyWeak: {
2369 CallInst *CI = cast<CallInst>(Inst);
2370 if (isNullOrUndef(CI->getArgOperand(0))) {
2372 Type *Ty = CI->getArgOperand(0)->getType();
2373 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2374 Constant::getNullValue(Ty),
2376 llvm::Value *NewValue = UndefValue::get(CI->getType());
2377 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2378 "pointer-to-weak-pointer is undefined behavior.\n"
2382 CI->replaceAllUsesWith(NewValue);
2383 CI->eraseFromParent();
2390 CallInst *CI = cast<CallInst>(Inst);
2391 if (isNullOrUndef(CI->getArgOperand(0)) ||
2392 isNullOrUndef(CI->getArgOperand(1))) {
2394 Type *Ty = CI->getArgOperand(0)->getType();
2395 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2396 Constant::getNullValue(Ty),
2399 llvm::Value *NewValue = UndefValue::get(CI->getType());
2400 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2401 "pointer-to-weak-pointer is undefined behavior.\n"
2406 CI->replaceAllUsesWith(NewValue);
2407 CI->eraseFromParent();
2413 OptimizeRetainCall(F, Inst);
2416 if (OptimizeRetainRVCall(F, Inst))
2419 case IC_AutoreleaseRV:
2420 OptimizeAutoreleaseRVCall(F, Inst);
2424 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2425 if (IsAutorelease(Class) && Inst->use_empty()) {
2426 CallInst *Call = cast<CallInst>(Inst);
2427 const Value *Arg = Call->getArgOperand(0);
2428 Arg = FindSingleUseIdentifiedObject(Arg);
2433 // Create the declaration lazily.
2434 LLVMContext &C = Inst->getContext();
2436 CallInst::Create(getReleaseCallee(F.getParent()),
2437 Call->getArgOperand(0), "", Call);
2438 NewCall->setMetadata(ImpreciseReleaseMDKind,
2439 MDNode::get(C, ArrayRef<Value *>()));
2441 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
2442 "objc_autorelease(x) with objc_release(x) since x is "
2443 "otherwise unused.\n"
2444 " Old: " << *Call <<
2448 EraseInstruction(Call);
2454 // For functions which can never be passed stack arguments, add
2456 if (IsAlwaysTail(Class)) {
2458 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
2459 " to function since it can never be passed stack args: " << *Inst <<
2461 cast<CallInst>(Inst)->setTailCall();
2464 // Ensure that functions that can never have a "tail" keyword due to the
2465 // semantics of ARC truly do not do so.
2466 if (IsNeverTail(Class)) {
2468 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail keyword"
2469 " from function: " << *Inst <<
2471 cast<CallInst>(Inst)->setTailCall(false);
2474 // Set nounwind as needed.
2475 if (IsNoThrow(Class)) {
2477 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
2478 " class. Setting nounwind on: " << *Inst << "\n");
2479 cast<CallInst>(Inst)->setDoesNotThrow();
2482 if (!IsNoopOnNull(Class)) {
2483 UsedInThisFunction |= 1 << Class;
2487 const Value *Arg = GetObjCArg(Inst);
2489 // ARC calls with null are no-ops. Delete them.
2490 if (isNullOrUndef(Arg)) {
2493 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
2494 " null are no-ops. Erasing: " << *Inst << "\n");
2495 EraseInstruction(Inst);
2499 // Keep track of which of retain, release, autorelease, and retain_block
2500 // are actually present in this function.
2501 UsedInThisFunction |= 1 << Class;
2503 // If Arg is a PHI, and one or more incoming values to the
2504 // PHI are null, and the call is control-equivalent to the PHI, and there
2505 // are no relevant side effects between the PHI and the call, the call
2506 // could be pushed up to just those paths with non-null incoming values.
2507 // For now, don't bother splitting critical edges for this.
2508 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2509 Worklist.push_back(std::make_pair(Inst, Arg));
2511 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2515 const PHINode *PN = dyn_cast<PHINode>(Arg);
2518 // Determine if the PHI has any null operands, or any incoming
2520 bool HasNull = false;
2521 bool HasCriticalEdges = false;
2522 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2524 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2525 if (isNullOrUndef(Incoming))
2527 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2528 .getNumSuccessors() != 1) {
2529 HasCriticalEdges = true;
2533 // If we have null operands and no critical edges, optimize.
2534 if (!HasCriticalEdges && HasNull) {
2535 SmallPtrSet<Instruction *, 4> DependingInstructions;
2536 SmallPtrSet<const BasicBlock *, 4> Visited;
2538 // Check that there is nothing that cares about the reference
2539 // count between the call and the phi.
2542 case IC_RetainBlock:
2543 // These can always be moved up.
2546 // These can't be moved across things that care about the retain
2548 FindDependencies(NeedsPositiveRetainCount, Arg,
2549 Inst->getParent(), Inst,
2550 DependingInstructions, Visited, PA);
2552 case IC_Autorelease:
2553 // These can't be moved across autorelease pool scope boundaries.
2554 FindDependencies(AutoreleasePoolBoundary, Arg,
2555 Inst->getParent(), Inst,
2556 DependingInstructions, Visited, PA);
2559 case IC_AutoreleaseRV:
2560 // Don't move these; the RV optimization depends on the autoreleaseRV
2561 // being tail called, and the retainRV being immediately after a call
2562 // (which might still happen if we get lucky with codegen layout, but
2563 // it's not worth taking the chance).
2566 llvm_unreachable("Invalid dependence flavor");
2569 if (DependingInstructions.size() == 1 &&
2570 *DependingInstructions.begin() == PN) {
2573 // Clone the call into each predecessor that has a non-null value.
2574 CallInst *CInst = cast<CallInst>(Inst);
2575 Type *ParamTy = CInst->getArgOperand(0)->getType();
2576 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2578 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2579 if (!isNullOrUndef(Incoming)) {
2580 CallInst *Clone = cast<CallInst>(CInst->clone());
2581 Value *Op = PN->getIncomingValue(i);
2582 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2583 if (Op->getType() != ParamTy)
2584 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2585 Clone->setArgOperand(0, Op);
2586 Clone->insertBefore(InsertPos);
2588 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
2591 "clone at " << *InsertPos << "\n");
2592 Worklist.push_back(std::make_pair(Clone, Incoming));
2595 // Erase the original call.
2596 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
2597 EraseInstruction(CInst);
2601 } while (!Worklist.empty());
2603 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished Queue.\n\n");
2608 /// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2609 /// control flow, or other CFG structures where moving code across the edge
2610 /// would result in it being executed more.
2612 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2613 DenseMap<const BasicBlock *, BBState> &BBStates,
2614 BBState &MyStates) const {
2615 // If any top-down local-use or possible-dec has a succ which is earlier in
2616 // the sequence, forget it.
2617 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
2618 E = MyStates.top_down_ptr_end(); I != E; ++I)
2619 switch (I->second.GetSeq()) {
2622 const Value *Arg = I->first;
2623 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2624 bool SomeSuccHasSame = false;
2625 bool AllSuccsHaveSame = true;
2626 PtrState &S = I->second;
2627 succ_const_iterator SI(TI), SE(TI, false);
2629 // If the terminator is an invoke marked with the
2630 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2631 // ignored, for ARC purposes.
2632 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2635 for (; SI != SE; ++SI) {
2636 Sequence SuccSSeq = S_None;
2637 bool SuccSRRIKnownSafe = false;
2638 // If VisitBottomUp has pointer information for this successor, take
2639 // what we know about it.
2640 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2642 assert(BBI != BBStates.end());
2643 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2644 SuccSSeq = SuccS.GetSeq();
2645 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2648 case S_CanRelease: {
2649 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2650 S.ClearSequenceProgress();
2656 SomeSuccHasSame = true;
2660 case S_MovableRelease:
2661 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2662 AllSuccsHaveSame = false;
2665 llvm_unreachable("bottom-up pointer in retain state!");
2668 // If the state at the other end of any of the successor edges
2669 // matches the current state, require all edges to match. This
2670 // guards against loops in the middle of a sequence.
2671 if (SomeSuccHasSame && !AllSuccsHaveSame)
2672 S.ClearSequenceProgress();
2675 case S_CanRelease: {
2676 const Value *Arg = I->first;
2677 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2678 bool SomeSuccHasSame = false;
2679 bool AllSuccsHaveSame = true;
2680 PtrState &S = I->second;
2681 succ_const_iterator SI(TI), SE(TI, false);
2683 // If the terminator is an invoke marked with the
2684 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2685 // ignored, for ARC purposes.
2686 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
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 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2703 S.ClearSequenceProgress();
2709 SomeSuccHasSame = true;
2713 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();
2733 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
2735 MapVector<Value *, RRInfo> &Retains,
2736 BBState &MyStates) {
2737 bool NestingDetected = false;
2738 InstructionClass Class = GetInstructionClass(Inst);
2739 const Value *Arg = 0;
2743 Arg = GetObjCArg(Inst);
2745 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2747 // If we see two releases in a row on the same pointer. If so, make
2748 // a note, and we'll cicle back to revisit it after we've
2749 // hopefully eliminated the second release, which may allow us to
2750 // eliminate the first release too.
2751 // Theoretically we could implement removal of nested retain+release
2752 // pairs by making PtrState hold a stack of states, but this is
2753 // simple and avoids adding overhead for the non-nested case.
2754 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2755 NestingDetected = true;
2757 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2758 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
2759 S.RRI.ReleaseMetadata = ReleaseMetadata;
2760 S.RRI.KnownSafe = S.IsKnownIncremented();
2761 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2762 S.RRI.Calls.insert(Inst);
2764 S.SetKnownPositiveRefCount();
2767 case IC_RetainBlock:
2768 // An objc_retainBlock call with just a use may need to be kept,
2769 // because it may be copying a block from the stack to the heap.
2770 if (!IsRetainBlockOptimizable(Inst))
2775 Arg = GetObjCArg(Inst);
2777 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2778 S.SetKnownPositiveRefCount();
2780 switch (S.GetSeq()) {
2783 case S_MovableRelease:
2785 S.RRI.ReverseInsertPts.clear();
2788 // Don't do retain+release tracking for IC_RetainRV, because it's
2789 // better to let it remain as the first instruction after a call.
2790 if (Class != IC_RetainRV) {
2791 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2792 Retains[Inst] = S.RRI;
2794 S.ClearSequenceProgress();
2799 llvm_unreachable("bottom-up pointer in retain state!");
2801 return NestingDetected;
2803 case IC_AutoreleasepoolPop:
2804 // Conservatively, clear MyStates for all known pointers.
2805 MyStates.clearBottomUpPointers();
2806 return NestingDetected;
2807 case IC_AutoreleasepoolPush:
2809 // These are irrelevant.
2810 return NestingDetected;
2815 // Consider any other possible effects of this instruction on each
2816 // pointer being tracked.
2817 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2818 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2819 const Value *Ptr = MI->first;
2821 continue; // Handled above.
2822 PtrState &S = MI->second;
2823 Sequence Seq = S.GetSeq();
2825 // Check for possible releases.
2826 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2830 S.SetSeq(S_CanRelease);
2834 case S_MovableRelease:
2839 llvm_unreachable("bottom-up pointer in retain state!");
2843 // Check for possible direct uses.
2846 case S_MovableRelease:
2847 if (CanUse(Inst, Ptr, PA, Class)) {
2848 assert(S.RRI.ReverseInsertPts.empty());
2849 // If this is an invoke instruction, we're scanning it as part of
2850 // one of its successor blocks, since we can't insert code after it
2851 // in its own block, and we don't want to split critical edges.
2852 if (isa<InvokeInst>(Inst))
2853 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2855 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2857 } else if (Seq == S_Release &&
2858 (Class == IC_User || Class == IC_CallOrUser)) {
2859 // Non-movable releases depend on any possible objc pointer use.
2861 assert(S.RRI.ReverseInsertPts.empty());
2862 // As above; handle invoke specially.
2863 if (isa<InvokeInst>(Inst))
2864 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2866 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2870 if (CanUse(Inst, Ptr, PA, Class))
2878 llvm_unreachable("bottom-up pointer in retain state!");
2882 return NestingDetected;
2886 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2887 DenseMap<const BasicBlock *, BBState> &BBStates,
2888 MapVector<Value *, RRInfo> &Retains) {
2889 bool NestingDetected = false;
2890 BBState &MyStates = BBStates[BB];
2892 // Merge the states from each successor to compute the initial state
2893 // for the current block.
2894 BBState::edge_iterator SI(MyStates.succ_begin()),
2895 SE(MyStates.succ_end());
2897 const BasicBlock *Succ = *SI;
2898 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2899 assert(I != BBStates.end());
2900 MyStates.InitFromSucc(I->second);
2902 for (; SI != SE; ++SI) {
2904 I = BBStates.find(Succ);
2905 assert(I != BBStates.end());
2906 MyStates.MergeSucc(I->second);
2910 // Visit all the instructions, bottom-up.
2911 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2912 Instruction *Inst = llvm::prior(I);
2914 // Invoke instructions are visited as part of their successors (below).
2915 if (isa<InvokeInst>(Inst))
2918 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2921 // If there's a predecessor with an invoke, visit the invoke as if it were
2922 // part of this block, since we can't insert code after an invoke in its own
2923 // block, and we don't want to split critical edges.
2924 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2925 PE(MyStates.pred_end()); PI != PE; ++PI) {
2926 BasicBlock *Pred = *PI;
2927 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2928 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
2931 return NestingDetected;
2935 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2936 DenseMap<Value *, RRInfo> &Releases,
2937 BBState &MyStates) {
2938 bool NestingDetected = false;
2939 InstructionClass Class = GetInstructionClass(Inst);
2940 const Value *Arg = 0;
2943 case IC_RetainBlock:
2944 // An objc_retainBlock call with just a use may need to be kept,
2945 // because it may be copying a block from the stack to the heap.
2946 if (!IsRetainBlockOptimizable(Inst))
2951 Arg = GetObjCArg(Inst);
2953 PtrState &S = MyStates.getPtrTopDownState(Arg);
2955 // Don't do retain+release tracking for IC_RetainRV, because it's
2956 // better to let it remain as the first instruction after a call.
2957 if (Class != IC_RetainRV) {
2958 // If we see two retains in a row on the same pointer. If so, make
2959 // a note, and we'll cicle back to revisit it after we've
2960 // hopefully eliminated the second retain, which may allow us to
2961 // eliminate the first retain too.
2962 // Theoretically we could implement removal of nested retain+release
2963 // pairs by making PtrState hold a stack of states, but this is
2964 // simple and avoids adding overhead for the non-nested case.
2965 if (S.GetSeq() == S_Retain)
2966 NestingDetected = true;
2968 S.ResetSequenceProgress(S_Retain);
2969 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2970 S.RRI.KnownSafe = S.IsKnownIncremented();
2971 S.RRI.Calls.insert(Inst);
2974 S.SetKnownPositiveRefCount();
2976 // A retain can be a potential use; procede to the generic checking
2981 Arg = GetObjCArg(Inst);
2983 PtrState &S = MyStates.getPtrTopDownState(Arg);
2986 switch (S.GetSeq()) {
2989 S.RRI.ReverseInsertPts.clear();
2992 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2993 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2994 Releases[Inst] = S.RRI;
2995 S.ClearSequenceProgress();
3001 case S_MovableRelease:
3002 llvm_unreachable("top-down pointer in release state!");
3006 case IC_AutoreleasepoolPop:
3007 // Conservatively, clear MyStates for all known pointers.
3008 MyStates.clearTopDownPointers();
3009 return NestingDetected;
3010 case IC_AutoreleasepoolPush:
3012 // These are irrelevant.
3013 return NestingDetected;
3018 // Consider any other possible effects of this instruction on each
3019 // pointer being tracked.
3020 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
3021 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
3022 const Value *Ptr = MI->first;
3024 continue; // Handled above.
3025 PtrState &S = MI->second;
3026 Sequence Seq = S.GetSeq();
3028 // Check for possible releases.
3029 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
3033 S.SetSeq(S_CanRelease);
3034 assert(S.RRI.ReverseInsertPts.empty());
3035 S.RRI.ReverseInsertPts.insert(Inst);
3037 // One call can't cause a transition from S_Retain to S_CanRelease
3038 // and S_CanRelease to S_Use. If we've made the first transition,
3047 case S_MovableRelease:
3048 llvm_unreachable("top-down pointer in release state!");
3052 // Check for possible direct uses.
3055 if (CanUse(Inst, Ptr, PA, Class))
3064 case S_MovableRelease:
3065 llvm_unreachable("top-down pointer in release state!");
3069 return NestingDetected;
3073 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
3074 DenseMap<const BasicBlock *, BBState> &BBStates,
3075 DenseMap<Value *, RRInfo> &Releases) {
3076 bool NestingDetected = false;
3077 BBState &MyStates = BBStates[BB];
3079 // Merge the states from each predecessor to compute the initial state
3080 // for the current block.
3081 BBState::edge_iterator PI(MyStates.pred_begin()),
3082 PE(MyStates.pred_end());
3084 const BasicBlock *Pred = *PI;
3085 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
3086 assert(I != BBStates.end());
3087 MyStates.InitFromPred(I->second);
3089 for (; PI != PE; ++PI) {
3091 I = BBStates.find(Pred);
3092 assert(I != BBStates.end());
3093 MyStates.MergePred(I->second);
3097 // Visit all the instructions, top-down.
3098 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3099 Instruction *Inst = I;
3100 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
3103 CheckForCFGHazards(BB, BBStates, MyStates);
3104 return NestingDetected;
3108 ComputePostOrders(Function &F,
3109 SmallVectorImpl<BasicBlock *> &PostOrder,
3110 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
3111 unsigned NoObjCARCExceptionsMDKind,
3112 DenseMap<const BasicBlock *, BBState> &BBStates) {
3113 /// Visited - The visited set, for doing DFS walks.
3114 SmallPtrSet<BasicBlock *, 16> Visited;
3116 // Do DFS, computing the PostOrder.
3117 SmallPtrSet<BasicBlock *, 16> OnStack;
3118 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
3120 // Functions always have exactly one entry block, and we don't have
3121 // any other block that we treat like an entry block.
3122 BasicBlock *EntryBB = &F.getEntryBlock();
3123 BBState &MyStates = BBStates[EntryBB];
3124 MyStates.SetAsEntry();
3125 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
3126 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
3127 Visited.insert(EntryBB);
3128 OnStack.insert(EntryBB);
3131 BasicBlock *CurrBB = SuccStack.back().first;
3132 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3133 succ_iterator SE(TI, false);
3135 // If the terminator is an invoke marked with the
3136 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
3137 // ignored, for ARC purposes.
3138 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
3141 while (SuccStack.back().second != SE) {
3142 BasicBlock *SuccBB = *SuccStack.back().second++;
3143 if (Visited.insert(SuccBB)) {
3144 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3145 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
3146 BBStates[CurrBB].addSucc(SuccBB);
3147 BBState &SuccStates = BBStates[SuccBB];
3148 SuccStates.addPred(CurrBB);
3149 OnStack.insert(SuccBB);
3153 if (!OnStack.count(SuccBB)) {
3154 BBStates[CurrBB].addSucc(SuccBB);
3155 BBStates[SuccBB].addPred(CurrBB);
3158 OnStack.erase(CurrBB);
3159 PostOrder.push_back(CurrBB);
3160 SuccStack.pop_back();
3161 } while (!SuccStack.empty());
3165 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
3166 // Functions may have many exits, and there also blocks which we treat
3167 // as exits due to ignored edges.
3168 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3169 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3170 BasicBlock *ExitBB = I;
3171 BBState &MyStates = BBStates[ExitBB];
3172 if (!MyStates.isExit())
3175 MyStates.SetAsExit();
3177 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
3178 Visited.insert(ExitBB);
3179 while (!PredStack.empty()) {
3180 reverse_dfs_next_succ:
3181 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3182 while (PredStack.back().second != PE) {
3183 BasicBlock *BB = *PredStack.back().second++;
3184 if (Visited.insert(BB)) {
3185 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
3186 goto reverse_dfs_next_succ;
3189 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3194 // Visit - Visit the function both top-down and bottom-up.
3196 ObjCARCOpt::Visit(Function &F,
3197 DenseMap<const BasicBlock *, BBState> &BBStates,
3198 MapVector<Value *, RRInfo> &Retains,
3199 DenseMap<Value *, RRInfo> &Releases) {
3201 // Use reverse-postorder traversals, because we magically know that loops
3202 // will be well behaved, i.e. they won't repeatedly call retain on a single
3203 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3204 // class here because we want the reverse-CFG postorder to consider each
3205 // function exit point, and we want to ignore selected cycle edges.
3206 SmallVector<BasicBlock *, 16> PostOrder;
3207 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
3208 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3209 NoObjCARCExceptionsMDKind,
3212 // Use reverse-postorder on the reverse CFG for bottom-up.
3213 bool BottomUpNestingDetected = false;
3214 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3215 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3217 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
3219 // Use reverse-postorder for top-down.
3220 bool TopDownNestingDetected = false;
3221 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3222 PostOrder.rbegin(), E = PostOrder.rend();
3224 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
3226 return TopDownNestingDetected && BottomUpNestingDetected;
3229 /// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
3230 void ObjCARCOpt::MoveCalls(Value *Arg,
3231 RRInfo &RetainsToMove,
3232 RRInfo &ReleasesToMove,
3233 MapVector<Value *, RRInfo> &Retains,
3234 DenseMap<Value *, RRInfo> &Releases,
3235 SmallVectorImpl<Instruction *> &DeadInsts,
3237 Type *ArgTy = Arg->getType();
3238 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
3240 // Insert the new retain and release calls.
3241 for (SmallPtrSet<Instruction *, 2>::const_iterator
3242 PI = ReleasesToMove.ReverseInsertPts.begin(),
3243 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3244 Instruction *InsertPt = *PI;
3245 Value *MyArg = ArgTy == ParamTy ? Arg :
3246 new BitCastInst(Arg, ParamTy, "", InsertPt);
3248 CallInst::Create(RetainsToMove.IsRetainBlock ?
3249 getRetainBlockCallee(M) : getRetainCallee(M),
3250 MyArg, "", InsertPt);
3251 Call->setDoesNotThrow();
3252 if (RetainsToMove.IsRetainBlock)
3253 Call->setMetadata(CopyOnEscapeMDKind,
3254 MDNode::get(M->getContext(), ArrayRef<Value *>()));
3256 Call->setTailCall();
3258 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
3260 " At insertion point: " << *InsertPt
3263 for (SmallPtrSet<Instruction *, 2>::const_iterator
3264 PI = RetainsToMove.ReverseInsertPts.begin(),
3265 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3266 Instruction *InsertPt = *PI;
3267 Value *MyArg = ArgTy == ParamTy ? Arg :
3268 new BitCastInst(Arg, ParamTy, "", InsertPt);
3269 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3271 // Attach a clang.imprecise_release metadata tag, if appropriate.
3272 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3273 Call->setMetadata(ImpreciseReleaseMDKind, M);
3274 Call->setDoesNotThrow();
3275 if (ReleasesToMove.IsTailCallRelease)
3276 Call->setTailCall();
3278 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
3280 " At insertion point: " << *InsertPt
3284 // Delete the original retain and release calls.
3285 for (SmallPtrSet<Instruction *, 2>::const_iterator
3286 AI = RetainsToMove.Calls.begin(),
3287 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3288 Instruction *OrigRetain = *AI;
3289 Retains.blot(OrigRetain);
3290 DeadInsts.push_back(OrigRetain);
3291 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
3294 for (SmallPtrSet<Instruction *, 2>::const_iterator
3295 AI = ReleasesToMove.Calls.begin(),
3296 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3297 Instruction *OrigRelease = *AI;
3298 Releases.erase(OrigRelease);
3299 DeadInsts.push_back(OrigRelease);
3300 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
3305 /// PerformCodePlacement - Identify pairings between the retains and releases,
3306 /// and delete and/or move them.
3308 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3310 MapVector<Value *, RRInfo> &Retains,
3311 DenseMap<Value *, RRInfo> &Releases,
3313 bool AnyPairsCompletelyEliminated = false;
3314 RRInfo RetainsToMove;
3315 RRInfo ReleasesToMove;
3316 SmallVector<Instruction *, 4> NewRetains;
3317 SmallVector<Instruction *, 4> NewReleases;
3318 SmallVector<Instruction *, 8> DeadInsts;
3320 // Visit each retain.
3321 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
3322 E = Retains.end(); I != E; ++I) {
3323 Value *V = I->first;
3324 if (!V) continue; // blotted
3326 Instruction *Retain = cast<Instruction>(V);
3328 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
3331 Value *Arg = GetObjCArg(Retain);
3333 // If the object being released is in static or stack storage, we know it's
3334 // not being managed by ObjC reference counting, so we can delete pairs
3335 // regardless of what possible decrements or uses lie between them.
3336 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
3338 // A constant pointer can't be pointing to an object on the heap. It may
3339 // be reference-counted, but it won't be deleted.
3340 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3341 if (const GlobalVariable *GV =
3342 dyn_cast<GlobalVariable>(
3343 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3344 if (GV->isConstant())
3347 // If a pair happens in a region where it is known that the reference count
3348 // is already incremented, we can similarly ignore possible decrements.
3349 bool KnownSafeTD = true, KnownSafeBU = true;
3351 // Connect the dots between the top-down-collected RetainsToMove and
3352 // bottom-up-collected ReleasesToMove to form sets of related calls.
3353 // This is an iterative process so that we connect multiple releases
3354 // to multiple retains if needed.
3355 unsigned OldDelta = 0;
3356 unsigned NewDelta = 0;
3357 unsigned OldCount = 0;
3358 unsigned NewCount = 0;
3359 bool FirstRelease = true;
3360 bool FirstRetain = true;
3361 NewRetains.push_back(Retain);
3363 for (SmallVectorImpl<Instruction *>::const_iterator
3364 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3365 Instruction *NewRetain = *NI;
3366 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3367 assert(It != Retains.end());
3368 const RRInfo &NewRetainRRI = It->second;
3369 KnownSafeTD &= NewRetainRRI.KnownSafe;
3370 for (SmallPtrSet<Instruction *, 2>::const_iterator
3371 LI = NewRetainRRI.Calls.begin(),
3372 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3373 Instruction *NewRetainRelease = *LI;
3374 DenseMap<Value *, RRInfo>::const_iterator Jt =
3375 Releases.find(NewRetainRelease);
3376 if (Jt == Releases.end())
3378 const RRInfo &NewRetainReleaseRRI = Jt->second;
3379 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3380 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3382 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3384 // Merge the ReleaseMetadata and IsTailCallRelease values.
3386 ReleasesToMove.ReleaseMetadata =
3387 NewRetainReleaseRRI.ReleaseMetadata;
3388 ReleasesToMove.IsTailCallRelease =
3389 NewRetainReleaseRRI.IsTailCallRelease;
3390 FirstRelease = false;
3392 if (ReleasesToMove.ReleaseMetadata !=
3393 NewRetainReleaseRRI.ReleaseMetadata)
3394 ReleasesToMove.ReleaseMetadata = 0;
3395 if (ReleasesToMove.IsTailCallRelease !=
3396 NewRetainReleaseRRI.IsTailCallRelease)
3397 ReleasesToMove.IsTailCallRelease = false;
3400 // Collect the optimal insertion points.
3402 for (SmallPtrSet<Instruction *, 2>::const_iterator
3403 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3404 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3406 Instruction *RIP = *RI;
3407 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3408 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3410 NewReleases.push_back(NewRetainRelease);
3415 if (NewReleases.empty()) break;
3417 // Back the other way.
3418 for (SmallVectorImpl<Instruction *>::const_iterator
3419 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3420 Instruction *NewRelease = *NI;
3421 DenseMap<Value *, RRInfo>::const_iterator It =
3422 Releases.find(NewRelease);
3423 assert(It != Releases.end());
3424 const RRInfo &NewReleaseRRI = It->second;
3425 KnownSafeBU &= NewReleaseRRI.KnownSafe;
3426 for (SmallPtrSet<Instruction *, 2>::const_iterator
3427 LI = NewReleaseRRI.Calls.begin(),
3428 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3429 Instruction *NewReleaseRetain = *LI;
3430 MapVector<Value *, RRInfo>::const_iterator Jt =
3431 Retains.find(NewReleaseRetain);
3432 if (Jt == Retains.end())
3434 const RRInfo &NewReleaseRetainRRI = Jt->second;
3435 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3436 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3437 unsigned PathCount =
3438 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3439 OldDelta += PathCount;
3440 OldCount += PathCount;
3442 // Merge the IsRetainBlock values.
3444 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3445 FirstRetain = false;
3446 } else if (ReleasesToMove.IsRetainBlock !=
3447 NewReleaseRetainRRI.IsRetainBlock)
3448 // It's not possible to merge the sequences if one uses
3449 // objc_retain and the other uses objc_retainBlock.
3452 // Collect the optimal insertion points.
3454 for (SmallPtrSet<Instruction *, 2>::const_iterator
3455 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3456 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3458 Instruction *RIP = *RI;
3459 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3460 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3461 NewDelta += PathCount;
3462 NewCount += PathCount;
3465 NewRetains.push_back(NewReleaseRetain);
3469 NewReleases.clear();
3470 if (NewRetains.empty()) break;
3473 // If the pointer is known incremented or nested, we can safely delete the
3474 // pair regardless of what's between them.
3475 if (KnownSafeTD || KnownSafeBU) {
3476 RetainsToMove.ReverseInsertPts.clear();
3477 ReleasesToMove.ReverseInsertPts.clear();
3480 // Determine whether the new insertion points we computed preserve the
3481 // balance of retain and release calls through the program.
3482 // TODO: If the fully aggressive solution isn't valid, try to find a
3483 // less aggressive solution which is.
3488 // Determine whether the original call points are balanced in the retain and
3489 // release calls through the program. If not, conservatively don't touch
3491 // TODO: It's theoretically possible to do code motion in this case, as
3492 // long as the existing imbalances are maintained.
3496 // Ok, everything checks out and we're all set. Let's move some code!
3498 assert(OldCount != 0 && "Unreachable code?");
3499 AnyPairsCompletelyEliminated = NewCount == 0;
3500 NumRRs += OldCount - NewCount;
3501 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3502 Retains, Releases, DeadInsts, M);
3505 NewReleases.clear();
3507 RetainsToMove.clear();
3508 ReleasesToMove.clear();
3511 // Now that we're done moving everything, we can delete the newly dead
3512 // instructions, as we no longer need them as insert points.
3513 while (!DeadInsts.empty())
3514 EraseInstruction(DeadInsts.pop_back_val());
3516 return AnyPairsCompletelyEliminated;
3519 /// OptimizeWeakCalls - Weak pointer optimizations.
3520 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3521 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3522 // itself because it uses AliasAnalysis and we need to do provenance
3524 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3525 Instruction *Inst = &*I++;
3527 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
3530 InstructionClass Class = GetBasicInstructionClass(Inst);
3531 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3534 // Delete objc_loadWeak calls with no users.
3535 if (Class == IC_LoadWeak && Inst->use_empty()) {
3536 Inst->eraseFromParent();
3540 // TODO: For now, just look for an earlier available version of this value
3541 // within the same block. Theoretically, we could do memdep-style non-local
3542 // analysis too, but that would want caching. A better approach would be to
3543 // use the technique that EarlyCSE uses.
3544 inst_iterator Current = llvm::prior(I);
3545 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3546 for (BasicBlock::iterator B = CurrentBB->begin(),
3547 J = Current.getInstructionIterator();
3549 Instruction *EarlierInst = &*llvm::prior(J);
3550 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3551 switch (EarlierClass) {
3553 case IC_LoadWeakRetained: {
3554 // If this is loading from the same pointer, replace this load's value
3556 CallInst *Call = cast<CallInst>(Inst);
3557 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3558 Value *Arg = Call->getArgOperand(0);
3559 Value *EarlierArg = EarlierCall->getArgOperand(0);
3560 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3561 case AliasAnalysis::MustAlias:
3563 // If the load has a builtin retain, insert a plain retain for it.
3564 if (Class == IC_LoadWeakRetained) {
3566 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3570 // Zap the fully redundant load.
3571 Call->replaceAllUsesWith(EarlierCall);
3572 Call->eraseFromParent();
3574 case AliasAnalysis::MayAlias:
3575 case AliasAnalysis::PartialAlias:
3577 case AliasAnalysis::NoAlias:
3584 // If this is storing to the same pointer and has the same size etc.
3585 // replace this load's value with the stored value.
3586 CallInst *Call = cast<CallInst>(Inst);
3587 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3588 Value *Arg = Call->getArgOperand(0);
3589 Value *EarlierArg = EarlierCall->getArgOperand(0);
3590 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3591 case AliasAnalysis::MustAlias:
3593 // If the load has a builtin retain, insert a plain retain for it.
3594 if (Class == IC_LoadWeakRetained) {
3596 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3600 // Zap the fully redundant load.
3601 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3602 Call->eraseFromParent();
3604 case AliasAnalysis::MayAlias:
3605 case AliasAnalysis::PartialAlias:
3607 case AliasAnalysis::NoAlias:
3614 // TOOD: Grab the copied value.
3616 case IC_AutoreleasepoolPush:
3619 // Weak pointers are only modified through the weak entry points
3620 // (and arbitrary calls, which could call the weak entry points).
3623 // Anything else could modify the weak pointer.
3630 // Then, for each destroyWeak with an alloca operand, check to see if
3631 // the alloca and all its users can be zapped.
3632 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3633 Instruction *Inst = &*I++;
3634 InstructionClass Class = GetBasicInstructionClass(Inst);
3635 if (Class != IC_DestroyWeak)
3638 CallInst *Call = cast<CallInst>(Inst);
3639 Value *Arg = Call->getArgOperand(0);
3640 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3641 for (Value::use_iterator UI = Alloca->use_begin(),
3642 UE = Alloca->use_end(); UI != UE; ++UI) {
3643 const Instruction *UserInst = cast<Instruction>(*UI);
3644 switch (GetBasicInstructionClass(UserInst)) {
3647 case IC_DestroyWeak:
3654 for (Value::use_iterator UI = Alloca->use_begin(),
3655 UE = Alloca->use_end(); UI != UE; ) {
3656 CallInst *UserInst = cast<CallInst>(*UI++);
3657 switch (GetBasicInstructionClass(UserInst)) {
3660 // These functions return their second argument.
3661 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3663 case IC_DestroyWeak:
3667 llvm_unreachable("alloca really is used!");
3669 UserInst->eraseFromParent();
3671 Alloca->eraseFromParent();
3676 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
3680 /// OptimizeSequences - Identify program paths which execute sequences of
3681 /// retains and releases which can be eliminated.
3682 bool ObjCARCOpt::OptimizeSequences(Function &F) {
3683 /// Releases, Retains - These are used to store the results of the main flow
3684 /// analysis. These use Value* as the key instead of Instruction* so that the
3685 /// map stays valid when we get around to rewriting code and calls get
3686 /// replaced by arguments.
3687 DenseMap<Value *, RRInfo> Releases;
3688 MapVector<Value *, RRInfo> Retains;
3690 /// BBStates, This is used during the traversal of the function to track the
3691 /// states for each identified object at each block.
3692 DenseMap<const BasicBlock *, BBState> BBStates;
3694 // Analyze the CFG of the function, and all instructions.
3695 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3698 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3702 /// OptimizeReturns - Look for this pattern:
3704 /// %call = call i8* @something(...)
3705 /// %2 = call i8* @objc_retain(i8* %call)
3706 /// %3 = call i8* @objc_autorelease(i8* %2)
3709 /// And delete the retain and autorelease.
3711 /// Otherwise if it's just this:
3713 /// %3 = call i8* @objc_autorelease(i8* %2)
3716 /// convert the autorelease to autoreleaseRV.
3717 void ObjCARCOpt::OptimizeReturns(Function &F) {
3718 if (!F.getReturnType()->isPointerTy())
3721 SmallPtrSet<Instruction *, 4> DependingInstructions;
3722 SmallPtrSet<const BasicBlock *, 4> Visited;
3723 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3724 BasicBlock *BB = FI;
3725 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3727 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
3731 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3732 FindDependencies(NeedsPositiveRetainCount, Arg,
3733 BB, Ret, DependingInstructions, Visited, PA);
3734 if (DependingInstructions.size() != 1)
3738 CallInst *Autorelease =
3739 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3742 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3743 if (!IsAutorelease(AutoreleaseClass))
3745 if (GetObjCArg(Autorelease) != Arg)
3748 DependingInstructions.clear();
3751 // Check that there is nothing that can affect the reference
3752 // count between the autorelease and the retain.
3753 FindDependencies(CanChangeRetainCount, Arg,
3754 BB, Autorelease, DependingInstructions, Visited, PA);
3755 if (DependingInstructions.size() != 1)
3760 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3762 // Check that we found a retain with the same argument.
3764 !IsRetain(GetBasicInstructionClass(Retain)) ||
3765 GetObjCArg(Retain) != Arg)
3768 DependingInstructions.clear();
3771 // Convert the autorelease to an autoreleaseRV, since it's
3772 // returning the value.
3773 if (AutoreleaseClass == IC_Autorelease) {
3774 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
3775 "=> autoreleaseRV since it's returning a value.\n"
3776 " In: " << *Autorelease
3778 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3779 DEBUG(dbgs() << " Out: " << *Autorelease
3781 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
3782 AutoreleaseClass = IC_AutoreleaseRV;
3785 // Check that there is nothing that can affect the reference
3786 // count between the retain and the call.
3787 // Note that Retain need not be in BB.
3788 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3789 DependingInstructions, Visited, PA);
3790 if (DependingInstructions.size() != 1)
3795 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3797 // Check that the pointer is the return value of the call.
3798 if (!Call || Arg != Call)
3801 // Check that the call is a regular call.
3802 InstructionClass Class = GetBasicInstructionClass(Call);
3803 if (Class != IC_CallOrUser && Class != IC_Call)
3806 // If so, we can zap the retain and autorelease.
3809 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
3811 << *Autorelease << "\n");
3812 EraseInstruction(Retain);
3813 EraseInstruction(Autorelease);
3819 DependingInstructions.clear();
3823 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
3827 bool ObjCARCOpt::doInitialization(Module &M) {
3831 // If nothing in the Module uses ARC, don't do anything.
3832 Run = ModuleHasARC(M);
3836 // Identify the imprecise release metadata kind.
3837 ImpreciseReleaseMDKind =
3838 M.getContext().getMDKindID("clang.imprecise_release");
3839 CopyOnEscapeMDKind =
3840 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3841 NoObjCARCExceptionsMDKind =
3842 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3844 // Intuitively, objc_retain and others are nocapture, however in practice
3845 // they are not, because they return their argument value. And objc_release
3846 // calls finalizers which can have arbitrary side effects.
3848 // These are initialized lazily.
3850 AutoreleaseRVCallee = 0;
3853 RetainBlockCallee = 0;
3854 AutoreleaseCallee = 0;
3859 bool ObjCARCOpt::runOnFunction(Function &F) {
3863 // If nothing in the Module uses ARC, don't do anything.
3869 PA.setAA(&getAnalysis<AliasAnalysis>());
3871 // This pass performs several distinct transformations. As a compile-time aid
3872 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3873 // library functions aren't declared.
3875 // Preliminary optimizations. This also computs UsedInThisFunction.
3876 OptimizeIndividualCalls(F);
3878 // Optimizations for weak pointers.
3879 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3880 (1 << IC_LoadWeakRetained) |
3881 (1 << IC_StoreWeak) |
3882 (1 << IC_InitWeak) |
3883 (1 << IC_CopyWeak) |
3884 (1 << IC_MoveWeak) |
3885 (1 << IC_DestroyWeak)))
3886 OptimizeWeakCalls(F);
3888 // Optimizations for retain+release pairs.
3889 if (UsedInThisFunction & ((1 << IC_Retain) |
3890 (1 << IC_RetainRV) |
3891 (1 << IC_RetainBlock)))
3892 if (UsedInThisFunction & (1 << IC_Release))
3893 // Run OptimizeSequences until it either stops making changes or
3894 // no retain+release pair nesting is detected.
3895 while (OptimizeSequences(F)) {}
3897 // Optimizations if objc_autorelease is used.
3898 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3899 (1 << IC_AutoreleaseRV)))
3905 void ObjCARCOpt::releaseMemory() {
3909 //===----------------------------------------------------------------------===//
3911 //===----------------------------------------------------------------------===//
3913 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
3914 // dominated by single calls.
3916 #include "llvm/Analysis/Dominators.h"
3917 #include "llvm/IR/InlineAsm.h"
3918 #include "llvm/IR/Operator.h"
3920 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3923 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3924 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3925 class ObjCARCContract : public FunctionPass {
3929 ProvenanceAnalysis PA;
3931 /// Run - A flag indicating whether this optimization pass should run.
3934 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3935 /// functions, for use in creating calls to them. These are initialized
3936 /// lazily to avoid cluttering up the Module with unused declarations.
3937 Constant *StoreStrongCallee,
3938 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3940 /// RetainRVMarker - The inline asm string to insert between calls and
3941 /// RetainRV calls to make the optimization work on targets which need it.
3942 const MDString *RetainRVMarker;
3944 /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
3945 /// at the end of walking the function we have found no alloca
3946 /// instructions, these calls can be marked "tail".
3947 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
3949 Constant *getStoreStrongCallee(Module *M);
3950 Constant *getRetainAutoreleaseCallee(Module *M);
3951 Constant *getRetainAutoreleaseRVCallee(Module *M);
3953 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3954 InstructionClass Class,
3955 SmallPtrSet<Instruction *, 4>
3956 &DependingInstructions,
3957 SmallPtrSet<const BasicBlock *, 4>
3960 void ContractRelease(Instruction *Release,
3961 inst_iterator &Iter);
3963 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3964 virtual bool doInitialization(Module &M);
3965 virtual bool runOnFunction(Function &F);
3969 ObjCARCContract() : FunctionPass(ID) {
3970 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3975 char ObjCARCContract::ID = 0;
3976 INITIALIZE_PASS_BEGIN(ObjCARCContract,
3977 "objc-arc-contract", "ObjC ARC contraction", false, false)
3978 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3979 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3980 INITIALIZE_PASS_END(ObjCARCContract,
3981 "objc-arc-contract", "ObjC ARC contraction", false, false)
3983 Pass *llvm::createObjCARCContractPass() {
3984 return new ObjCARCContract();
3987 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3988 AU.addRequired<AliasAnalysis>();
3989 AU.addRequired<DominatorTree>();
3990 AU.setPreservesCFG();
3993 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3994 if (!StoreStrongCallee) {
3995 LLVMContext &C = M->getContext();
3996 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3997 Type *I8XX = PointerType::getUnqual(I8X);
3998 Type *Params[] = { I8XX, I8X };
4000 AttributeSet Attribute = AttributeSet()
4001 .addAttr(M->getContext(), AttributeSet::FunctionIndex,
4002 Attribute::get(C, Attribute::NoUnwind))
4003 .addAttr(M->getContext(), 1, Attribute::get(C, Attribute::NoCapture));
4006 M->getOrInsertFunction(
4008 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
4011 return StoreStrongCallee;
4014 Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
4015 if (!RetainAutoreleaseCallee) {
4016 LLVMContext &C = M->getContext();
4017 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4018 Type *Params[] = { I8X };
4019 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
4020 AttributeSet Attribute =
4021 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
4022 Attribute::get(C, Attribute::NoUnwind));
4023 RetainAutoreleaseCallee =
4024 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
4026 return RetainAutoreleaseCallee;
4029 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
4030 if (!RetainAutoreleaseRVCallee) {
4031 LLVMContext &C = M->getContext();
4032 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4033 Type *Params[] = { I8X };
4034 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
4035 AttributeSet Attribute =
4036 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
4037 Attribute::get(C, Attribute::NoUnwind));
4038 RetainAutoreleaseRVCallee =
4039 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
4042 return RetainAutoreleaseRVCallee;
4045 /// ContractAutorelease - Merge an autorelease with a retain into a fused call.
4047 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
4048 InstructionClass Class,
4049 SmallPtrSet<Instruction *, 4>
4050 &DependingInstructions,
4051 SmallPtrSet<const BasicBlock *, 4>
4053 const Value *Arg = GetObjCArg(Autorelease);
4055 // Check that there are no instructions between the retain and the autorelease
4056 // (such as an autorelease_pop) which may change the count.
4057 CallInst *Retain = 0;
4058 if (Class == IC_AutoreleaseRV)
4059 FindDependencies(RetainAutoreleaseRVDep, Arg,
4060 Autorelease->getParent(), Autorelease,
4061 DependingInstructions, Visited, PA);
4063 FindDependencies(RetainAutoreleaseDep, Arg,
4064 Autorelease->getParent(), Autorelease,
4065 DependingInstructions, Visited, PA);
4068 if (DependingInstructions.size() != 1) {
4069 DependingInstructions.clear();
4073 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
4074 DependingInstructions.clear();
4077 GetBasicInstructionClass(Retain) != IC_Retain ||
4078 GetObjCArg(Retain) != Arg)
4084 DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing "
4085 "retain/autorelease. Erasing: " << *Autorelease << "\n"
4087 << *Retain << "\n");
4089 if (Class == IC_AutoreleaseRV)
4090 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
4092 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
4094 DEBUG(dbgs() << " New Retain: "
4095 << *Retain << "\n");
4097 EraseInstruction(Autorelease);
4101 /// ContractRelease - Attempt to merge an objc_release with a store, load, and
4102 /// objc_retain to form an objc_storeStrong. This can be a little tricky because
4103 /// the instructions don't always appear in order, and there may be unrelated
4104 /// intervening instructions.
4105 void ObjCARCContract::ContractRelease(Instruction *Release,
4106 inst_iterator &Iter) {
4107 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
4108 if (!Load || !Load->isSimple()) return;
4110 // For now, require everything to be in one basic block.
4111 BasicBlock *BB = Release->getParent();
4112 if (Load->getParent() != BB) return;
4114 // Walk down to find the store and the release, which may be in either order.
4115 BasicBlock::iterator I = Load, End = BB->end();
4117 AliasAnalysis::Location Loc = AA->getLocation(Load);
4118 StoreInst *Store = 0;
4119 bool SawRelease = false;
4120 for (; !Store || !SawRelease; ++I) {
4124 Instruction *Inst = I;
4125 if (Inst == Release) {
4130 InstructionClass Class = GetBasicInstructionClass(Inst);
4132 // Unrelated retains are harmless.
4133 if (IsRetain(Class))
4137 // The store is the point where we're going to put the objc_storeStrong,
4138 // so make sure there are no uses after it.
4139 if (CanUse(Inst, Load, PA, Class))
4141 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
4142 // We are moving the load down to the store, so check for anything
4143 // else which writes to the memory between the load and the store.
4144 Store = dyn_cast<StoreInst>(Inst);
4145 if (!Store || !Store->isSimple()) return;
4146 if (Store->getPointerOperand() != Loc.Ptr) return;
4150 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
4152 // Walk up to find the retain.
4154 BasicBlock::iterator Begin = BB->begin();
4155 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
4157 Instruction *Retain = I;
4158 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
4159 if (GetObjCArg(Retain) != New) return;
4164 LLVMContext &C = Release->getContext();
4165 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4166 Type *I8XX = PointerType::getUnqual(I8X);
4168 Value *Args[] = { Load->getPointerOperand(), New };
4169 if (Args[0]->getType() != I8XX)
4170 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
4171 if (Args[1]->getType() != I8X)
4172 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
4173 CallInst *StoreStrong =
4174 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
4176 StoreStrong->setDoesNotThrow();
4177 StoreStrong->setDebugLoc(Store->getDebugLoc());
4179 // We can't set the tail flag yet, because we haven't yet determined
4180 // whether there are any escaping allocas. Remember this call, so that
4181 // we can set the tail flag once we know it's safe.
4182 StoreStrongCalls.insert(StoreStrong);
4184 if (&*Iter == Store) ++Iter;
4185 Store->eraseFromParent();
4186 Release->eraseFromParent();
4187 EraseInstruction(Retain);
4188 if (Load->use_empty())
4189 Load->eraseFromParent();
4192 bool ObjCARCContract::doInitialization(Module &M) {
4193 // If nothing in the Module uses ARC, don't do anything.
4194 Run = ModuleHasARC(M);
4198 // These are initialized lazily.
4199 StoreStrongCallee = 0;
4200 RetainAutoreleaseCallee = 0;
4201 RetainAutoreleaseRVCallee = 0;
4203 // Initialize RetainRVMarker.
4205 if (NamedMDNode *NMD =
4206 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4207 if (NMD->getNumOperands() == 1) {
4208 const MDNode *N = NMD->getOperand(0);
4209 if (N->getNumOperands() == 1)
4210 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4217 bool ObjCARCContract::runOnFunction(Function &F) {
4221 // If nothing in the Module uses ARC, don't do anything.
4226 AA = &getAnalysis<AliasAnalysis>();
4227 DT = &getAnalysis<DominatorTree>();
4229 PA.setAA(&getAnalysis<AliasAnalysis>());
4231 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4232 // keyword. Be conservative if the function has variadic arguments.
4233 // It seems that functions which "return twice" are also unsafe for the
4234 // "tail" argument, because they are setjmp, which could need to
4235 // return to an earlier stack state.
4236 bool TailOkForStoreStrongs = !F.isVarArg() &&
4237 !F.callsFunctionThatReturnsTwice();
4239 // For ObjC library calls which return their argument, replace uses of the
4240 // argument with uses of the call return value, if it dominates the use. This
4241 // reduces register pressure.
4242 SmallPtrSet<Instruction *, 4> DependingInstructions;
4243 SmallPtrSet<const BasicBlock *, 4> Visited;
4244 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4245 Instruction *Inst = &*I++;
4247 DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
4249 // Only these library routines return their argument. In particular,
4250 // objc_retainBlock does not necessarily return its argument.
4251 InstructionClass Class = GetBasicInstructionClass(Inst);
4254 case IC_FusedRetainAutorelease:
4255 case IC_FusedRetainAutoreleaseRV:
4257 case IC_Autorelease:
4258 case IC_AutoreleaseRV:
4259 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4263 // If we're compiling for a target which needs a special inline-asm
4264 // marker to do the retainAutoreleasedReturnValue optimization,
4266 if (!RetainRVMarker)
4268 BasicBlock::iterator BBI = Inst;
4269 BasicBlock *InstParent = Inst->getParent();
4271 // Step up to see if the call immediately precedes the RetainRV call.
4272 // If it's an invoke, we have to cross a block boundary. And we have
4273 // to carefully dodge no-op instructions.
4275 if (&*BBI == InstParent->begin()) {
4276 BasicBlock *Pred = InstParent->getSinglePredecessor();
4278 goto decline_rv_optimization;
4279 BBI = Pred->getTerminator();
4283 } while (isNoopInstruction(BBI));
4285 if (&*BBI == GetObjCArg(Inst)) {
4286 DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
4287 "retainAutoreleasedReturnValue optimization.\n");
4290 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4291 /*isVarArg=*/false),
4292 RetainRVMarker->getString(),
4293 /*Constraints=*/"", /*hasSideEffects=*/true);
4294 CallInst::Create(IA, "", Inst);
4296 decline_rv_optimization:
4300 // objc_initWeak(p, null) => *p = null
4301 CallInst *CI = cast<CallInst>(Inst);
4302 if (isNullOrUndef(CI->getArgOperand(1))) {
4304 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4306 new StoreInst(Null, CI->getArgOperand(0), CI);
4308 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
4309 << " New = " << *Null << "\n");
4311 CI->replaceAllUsesWith(Null);
4312 CI->eraseFromParent();
4317 ContractRelease(Inst, I);
4320 // Be conservative if the function has any alloca instructions.
4321 // Technically we only care about escaping alloca instructions,
4322 // but this is sufficient to handle some interesting cases.
4323 if (isa<AllocaInst>(Inst))
4324 TailOkForStoreStrongs = false;
4330 DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n");
4332 // Don't use GetObjCArg because we don't want to look through bitcasts
4333 // and such; to do the replacement, the argument must have type i8*.
4334 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4336 // If we're compiling bugpointed code, don't get in trouble.
4337 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4339 // Look through the uses of the pointer.
4340 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4342 Use &U = UI.getUse();
4343 unsigned OperandNo = UI.getOperandNo();
4344 ++UI; // Increment UI now, because we may unlink its element.
4346 // If the call's return value dominates a use of the call's argument
4347 // value, rewrite the use to use the return value. We check for
4348 // reachability here because an unreachable call is considered to
4349 // trivially dominate itself, which would lead us to rewriting its
4350 // argument in terms of its return value, which would lead to
4351 // infinite loops in GetObjCArg.
4352 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
4354 Instruction *Replacement = Inst;
4355 Type *UseTy = U.get()->getType();
4356 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
4357 // For PHI nodes, insert the bitcast in the predecessor block.
4358 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4359 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
4360 if (Replacement->getType() != UseTy)
4361 Replacement = new BitCastInst(Replacement, UseTy, "",
4363 // While we're here, rewrite all edges for this PHI, rather
4364 // than just one use at a time, to minimize the number of
4365 // bitcasts we emit.
4366 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4367 if (PHI->getIncomingBlock(i) == BB) {
4368 // Keep the UI iterator valid.
4369 if (&PHI->getOperandUse(
4370 PHINode::getOperandNumForIncomingValue(i)) ==
4373 PHI->setIncomingValue(i, Replacement);
4376 if (Replacement->getType() != UseTy)
4377 Replacement = new BitCastInst(Replacement, UseTy, "",
4378 cast<Instruction>(U.getUser()));
4384 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
4385 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4386 Arg = BI->getOperand(0);
4387 else if (isa<GEPOperator>(Arg) &&
4388 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4389 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4390 else if (isa<GlobalAlias>(Arg) &&
4391 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4392 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4398 // If this function has no escaping allocas or suspicious vararg usage,
4399 // objc_storeStrong calls can be marked with the "tail" keyword.
4400 if (TailOkForStoreStrongs)
4401 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
4402 E = StoreStrongCalls.end(); I != E; ++I)
4403 (*I)->setTailCall();
4404 StoreStrongCalls.clear();