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/Support/CommandLine.h"
33 #include "llvm/ADT/DenseMap.h"
36 // A handy option to enable/disable all optimizations in this file.
37 static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
39 //===----------------------------------------------------------------------===//
41 //===----------------------------------------------------------------------===//
44 /// MapVector - An associative container with fast insertion-order
45 /// (deterministic) iteration over its elements. Plus the special
47 template<class KeyT, class ValueT>
49 /// Map - Map keys to indices in Vector.
50 typedef DenseMap<KeyT, size_t> MapTy;
53 /// Vector - Keys and values.
54 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
58 typedef typename VectorTy::iterator iterator;
59 typedef typename VectorTy::const_iterator const_iterator;
60 iterator begin() { return Vector.begin(); }
61 iterator end() { return Vector.end(); }
62 const_iterator begin() const { return Vector.begin(); }
63 const_iterator end() const { return Vector.end(); }
67 assert(Vector.size() >= Map.size()); // May differ due to blotting.
68 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
70 assert(I->second < Vector.size());
71 assert(Vector[I->second].first == I->first);
73 for (typename VectorTy::const_iterator I = Vector.begin(),
74 E = Vector.end(); I != E; ++I)
76 (Map.count(I->first) &&
77 Map[I->first] == size_t(I - Vector.begin())));
81 ValueT &operator[](const KeyT &Arg) {
82 std::pair<typename MapTy::iterator, bool> Pair =
83 Map.insert(std::make_pair(Arg, size_t(0)));
85 size_t Num = Vector.size();
86 Pair.first->second = Num;
87 Vector.push_back(std::make_pair(Arg, ValueT()));
88 return Vector[Num].second;
90 return Vector[Pair.first->second].second;
93 std::pair<iterator, bool>
94 insert(const std::pair<KeyT, ValueT> &InsertPair) {
95 std::pair<typename MapTy::iterator, bool> Pair =
96 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
98 size_t Num = Vector.size();
99 Pair.first->second = Num;
100 Vector.push_back(InsertPair);
101 return std::make_pair(Vector.begin() + Num, true);
103 return std::make_pair(Vector.begin() + Pair.first->second, false);
106 const_iterator find(const KeyT &Key) const {
107 typename MapTy::const_iterator It = Map.find(Key);
108 if (It == Map.end()) return Vector.end();
109 return Vector.begin() + It->second;
112 /// blot - This is similar to erase, but instead of removing the element
113 /// from the vector, it just zeros out the key in the vector. This leaves
114 /// iterators intact, but clients must be prepared for zeroed-out keys when
116 void blot(const KeyT &Key) {
117 typename MapTy::iterator It = Map.find(Key);
118 if (It == Map.end()) return;
119 Vector[It->second].first = KeyT();
130 //===----------------------------------------------------------------------===//
132 //===----------------------------------------------------------------------===//
134 #include "llvm/Intrinsics.h"
135 #include "llvm/Module.h"
136 #include "llvm/Analysis/ValueTracking.h"
137 #include "llvm/Transforms/Utils/Local.h"
138 #include "llvm/Support/CallSite.h"
139 #include "llvm/ADT/StringSwitch.h"
142 /// InstructionClass - A simple classification for instructions.
143 enum InstructionClass {
144 IC_Retain, ///< objc_retain
145 IC_RetainRV, ///< objc_retainAutoreleasedReturnValue
146 IC_RetainBlock, ///< objc_retainBlock
147 IC_Release, ///< objc_release
148 IC_Autorelease, ///< objc_autorelease
149 IC_AutoreleaseRV, ///< objc_autoreleaseReturnValue
150 IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
151 IC_AutoreleasepoolPop, ///< objc_autoreleasePoolPop
152 IC_NoopCast, ///< objc_retainedObject, etc.
153 IC_FusedRetainAutorelease, ///< objc_retainAutorelease
154 IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
155 IC_LoadWeakRetained, ///< objc_loadWeakRetained (primitive)
156 IC_StoreWeak, ///< objc_storeWeak (primitive)
157 IC_InitWeak, ///< objc_initWeak (derived)
158 IC_LoadWeak, ///< objc_loadWeak (derived)
159 IC_MoveWeak, ///< objc_moveWeak (derived)
160 IC_CopyWeak, ///< objc_copyWeak (derived)
161 IC_DestroyWeak, ///< objc_destroyWeak (derived)
162 IC_StoreStrong, ///< objc_storeStrong (derived)
163 IC_CallOrUser, ///< could call objc_release and/or "use" pointers
164 IC_Call, ///< could call objc_release
165 IC_User, ///< could "use" a pointer
166 IC_None ///< anything else
170 /// IsPotentialUse - Test whether the given value is possible a
171 /// reference-counted pointer.
172 static bool IsPotentialUse(const Value *Op) {
173 // Pointers to static or stack storage are not reference-counted pointers.
174 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
176 // Special arguments are not reference-counted.
177 if (const Argument *Arg = dyn_cast<Argument>(Op))
178 if (Arg->hasByValAttr() ||
179 Arg->hasNestAttr() ||
180 Arg->hasStructRetAttr())
182 // Only consider values with pointer types.
183 // It seemes intuitive to exclude function pointer types as well, since
184 // functions are never reference-counted, however clang occasionally
185 // bitcasts reference-counted pointers to function-pointer type
187 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
190 // Conservatively assume anything else is a potential use.
194 /// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind
195 /// of construct CS is.
196 static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
197 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
199 if (IsPotentialUse(*I))
200 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
202 return CS.onlyReadsMemory() ? IC_None : IC_Call;
205 /// GetFunctionClass - Determine if F is one of the special known Functions.
206 /// If it isn't, return IC_CallOrUser.
207 static InstructionClass GetFunctionClass(const Function *F) {
208 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
212 return StringSwitch<InstructionClass>(F->getName())
213 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
214 .Default(IC_CallOrUser);
217 const Argument *A0 = AI++;
219 // Argument is a pointer.
220 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
221 Type *ETy = PTy->getElementType();
223 if (ETy->isIntegerTy(8))
224 return StringSwitch<InstructionClass>(F->getName())
225 .Case("objc_retain", IC_Retain)
226 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
227 .Case("objc_retainBlock", IC_RetainBlock)
228 .Case("objc_release", IC_Release)
229 .Case("objc_autorelease", IC_Autorelease)
230 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
231 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
232 .Case("objc_retainedObject", IC_NoopCast)
233 .Case("objc_unretainedObject", IC_NoopCast)
234 .Case("objc_unretainedPointer", IC_NoopCast)
235 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
236 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
237 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
238 .Default(IC_CallOrUser);
241 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
242 if (Pte->getElementType()->isIntegerTy(8))
243 return StringSwitch<InstructionClass>(F->getName())
244 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
245 .Case("objc_loadWeak", IC_LoadWeak)
246 .Case("objc_destroyWeak", IC_DestroyWeak)
247 .Default(IC_CallOrUser);
250 // Two arguments, first is i8**.
251 const Argument *A1 = AI++;
253 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
254 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
255 if (Pte->getElementType()->isIntegerTy(8))
256 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
257 Type *ETy1 = PTy1->getElementType();
258 // Second argument is i8*
259 if (ETy1->isIntegerTy(8))
260 return StringSwitch<InstructionClass>(F->getName())
261 .Case("objc_storeWeak", IC_StoreWeak)
262 .Case("objc_initWeak", IC_InitWeak)
263 .Case("objc_storeStrong", IC_StoreStrong)
264 .Default(IC_CallOrUser);
265 // Second argument is i8**.
266 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
267 if (Pte1->getElementType()->isIntegerTy(8))
268 return StringSwitch<InstructionClass>(F->getName())
269 .Case("objc_moveWeak", IC_MoveWeak)
270 .Case("objc_copyWeak", IC_CopyWeak)
271 .Default(IC_CallOrUser);
275 return IC_CallOrUser;
278 /// GetInstructionClass - Determine what kind of construct V is.
279 static InstructionClass GetInstructionClass(const Value *V) {
280 if (const Instruction *I = dyn_cast<Instruction>(V)) {
281 // Any instruction other than bitcast and gep with a pointer operand have a
282 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
283 // to a subsequent use, rather than using it themselves, in this sense.
284 // As a short cut, several other opcodes are known to have no pointer
285 // operands of interest. And ret is never followed by a release, so it's
286 // not interesting to examine.
287 switch (I->getOpcode()) {
288 case Instruction::Call: {
289 const CallInst *CI = cast<CallInst>(I);
290 // Check for calls to special functions.
291 if (const Function *F = CI->getCalledFunction()) {
292 InstructionClass Class = GetFunctionClass(F);
293 if (Class != IC_CallOrUser)
296 // None of the intrinsic functions do objc_release. For intrinsics, the
297 // only question is whether or not they may be users.
298 switch (F->getIntrinsicID()) {
299 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
300 case Intrinsic::stacksave: case Intrinsic::stackrestore:
301 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
302 case Intrinsic::objectsize: case Intrinsic::prefetch:
303 case Intrinsic::stackprotector:
304 case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
305 case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
306 case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
307 case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
308 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
309 case Intrinsic::invariant_start: case Intrinsic::invariant_end:
310 // Don't let dbg info affect our results.
311 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
312 // Short cut: Some intrinsics obviously don't use ObjC pointers.
318 return GetCallSiteClass(CI);
320 case Instruction::Invoke:
321 return GetCallSiteClass(cast<InvokeInst>(I));
322 case Instruction::BitCast:
323 case Instruction::GetElementPtr:
324 case Instruction::Select: case Instruction::PHI:
325 case Instruction::Ret: case Instruction::Br:
326 case Instruction::Switch: case Instruction::IndirectBr:
327 case Instruction::Alloca: case Instruction::VAArg:
328 case Instruction::Add: case Instruction::FAdd:
329 case Instruction::Sub: case Instruction::FSub:
330 case Instruction::Mul: case Instruction::FMul:
331 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
332 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
333 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
334 case Instruction::And: case Instruction::Or: case Instruction::Xor:
335 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
336 case Instruction::IntToPtr: case Instruction::FCmp:
337 case Instruction::FPTrunc: case Instruction::FPExt:
338 case Instruction::FPToUI: case Instruction::FPToSI:
339 case Instruction::UIToFP: case Instruction::SIToFP:
340 case Instruction::InsertElement: case Instruction::ExtractElement:
341 case Instruction::ShuffleVector:
342 case Instruction::ExtractValue:
344 case Instruction::ICmp:
345 // Comparing a pointer with null, or any other constant, isn't an
346 // interesting use, because we don't care what the pointer points to, or
347 // about the values of any other dynamic reference-counted pointers.
348 if (IsPotentialUse(I->getOperand(1)))
352 // For anything else, check all the operands.
353 // Note that this includes both operands of a Store: while the first
354 // operand isn't actually being dereferenced, it is being stored to
355 // memory where we can no longer track who might read it and dereference
356 // it, so we have to consider it potentially used.
357 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
359 if (IsPotentialUse(*OI))
364 // Otherwise, it's totally inert for ARC purposes.
368 /// GetBasicInstructionClass - Determine what kind of construct V is. This is
369 /// similar to GetInstructionClass except that it only detects objc runtine
370 /// calls. This allows it to be faster.
371 static InstructionClass GetBasicInstructionClass(const Value *V) {
372 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
373 if (const Function *F = CI->getCalledFunction())
374 return GetFunctionClass(F);
375 // Otherwise, be conservative.
376 return IC_CallOrUser;
379 // Otherwise, be conservative.
380 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
383 /// IsRetain - Test if the given class is objc_retain or
385 static bool IsRetain(InstructionClass Class) {
386 return Class == IC_Retain ||
387 Class == IC_RetainRV;
390 /// IsAutorelease - Test if the given class is objc_autorelease or
392 static bool IsAutorelease(InstructionClass Class) {
393 return Class == IC_Autorelease ||
394 Class == IC_AutoreleaseRV;
397 /// IsForwarding - Test if the given class represents instructions which return
398 /// their argument verbatim.
399 static bool IsForwarding(InstructionClass Class) {
400 // objc_retainBlock technically doesn't always return its argument
401 // verbatim, but it doesn't matter for our purposes here.
402 return Class == IC_Retain ||
403 Class == IC_RetainRV ||
404 Class == IC_Autorelease ||
405 Class == IC_AutoreleaseRV ||
406 Class == IC_RetainBlock ||
407 Class == IC_NoopCast;
410 /// IsNoopOnNull - Test if the given class represents instructions which do
411 /// nothing if passed a null pointer.
412 static bool IsNoopOnNull(InstructionClass Class) {
413 return Class == IC_Retain ||
414 Class == IC_RetainRV ||
415 Class == IC_Release ||
416 Class == IC_Autorelease ||
417 Class == IC_AutoreleaseRV ||
418 Class == IC_RetainBlock;
421 /// IsAlwaysTail - Test if the given class represents instructions which are
422 /// always safe to mark with the "tail" keyword.
423 static bool IsAlwaysTail(InstructionClass Class) {
424 // IC_RetainBlock may be given a stack argument.
425 return Class == IC_Retain ||
426 Class == IC_RetainRV ||
427 Class == IC_Autorelease ||
428 Class == IC_AutoreleaseRV;
431 /// IsNoThrow - Test if the given class represents instructions which are always
432 /// safe to mark with the nounwind attribute..
433 static bool IsNoThrow(InstructionClass Class) {
434 // objc_retainBlock is not nounwind because it calls user copy constructors
435 // which could theoretically throw.
436 return Class == IC_Retain ||
437 Class == IC_RetainRV ||
438 Class == IC_Release ||
439 Class == IC_Autorelease ||
440 Class == IC_AutoreleaseRV ||
441 Class == IC_AutoreleasepoolPush ||
442 Class == IC_AutoreleasepoolPop;
445 /// EraseInstruction - Erase the given instruction. Many ObjC calls return their
446 /// argument verbatim, so if it's such a call and the return value has users,
447 /// replace them with the argument value.
448 static void EraseInstruction(Instruction *CI) {
449 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
451 bool Unused = CI->use_empty();
454 // Replace the return value with the argument.
455 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
456 "Can't delete non-forwarding instruction with users!");
457 CI->replaceAllUsesWith(OldArg);
460 CI->eraseFromParent();
463 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
466 /// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
467 /// also knows how to look through objc_retain and objc_autorelease calls, which
468 /// we know to return their argument verbatim.
469 static const Value *GetUnderlyingObjCPtr(const Value *V) {
471 V = GetUnderlyingObject(V);
472 if (!IsForwarding(GetBasicInstructionClass(V)))
474 V = cast<CallInst>(V)->getArgOperand(0);
480 /// StripPointerCastsAndObjCCalls - This is a wrapper around
481 /// Value::stripPointerCasts which also knows how to look through objc_retain
482 /// and objc_autorelease calls, which we know to return their argument verbatim.
483 static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
485 V = V->stripPointerCasts();
486 if (!IsForwarding(GetBasicInstructionClass(V)))
488 V = cast<CallInst>(V)->getArgOperand(0);
493 /// StripPointerCastsAndObjCCalls - This is a wrapper around
494 /// Value::stripPointerCasts which also knows how to look through objc_retain
495 /// and objc_autorelease calls, which we know to return their argument verbatim.
496 static Value *StripPointerCastsAndObjCCalls(Value *V) {
498 V = V->stripPointerCasts();
499 if (!IsForwarding(GetBasicInstructionClass(V)))
501 V = cast<CallInst>(V)->getArgOperand(0);
506 /// GetObjCArg - Assuming the given instruction is one of the special calls such
507 /// as objc_retain or objc_release, return the argument value, stripped of no-op
508 /// casts and forwarding calls.
509 static Value *GetObjCArg(Value *Inst) {
510 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
513 /// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
514 /// isObjCIdentifiedObject, except that it uses special knowledge of
515 /// ObjC conventions...
516 static bool IsObjCIdentifiedObject(const Value *V) {
517 // Assume that call results and arguments have their own "provenance".
518 // Constants (including GlobalVariables) and Allocas are never
519 // reference-counted.
520 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
521 isa<Argument>(V) || isa<Constant>(V) ||
525 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
526 const Value *Pointer =
527 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
528 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
529 // A constant pointer can't be pointing to an object on the heap. It may
530 // be reference-counted, but it won't be deleted.
531 if (GV->isConstant())
533 StringRef Name = GV->getName();
534 // These special variables are known to hold values which are not
535 // reference-counted pointers.
536 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
537 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
538 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
539 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
540 Name.startswith("\01l_objc_msgSend_fixup_"))
548 /// FindSingleUseIdentifiedObject - This is similar to
549 /// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
550 /// with multiple uses.
551 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
552 if (Arg->hasOneUse()) {
553 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
554 return FindSingleUseIdentifiedObject(BC->getOperand(0));
555 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
556 if (GEP->hasAllZeroIndices())
557 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
558 if (IsForwarding(GetBasicInstructionClass(Arg)))
559 return FindSingleUseIdentifiedObject(
560 cast<CallInst>(Arg)->getArgOperand(0));
561 if (!IsObjCIdentifiedObject(Arg))
566 // If we found an identifiable object but it has multiple uses, but they are
567 // trivial uses, we can still consider this to be a single-use value.
568 if (IsObjCIdentifiedObject(Arg)) {
569 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
572 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
582 /// ModuleHasARC - Test if the given module looks interesting to run ARC
584 static bool ModuleHasARC(const Module &M) {
586 M.getNamedValue("objc_retain") ||
587 M.getNamedValue("objc_release") ||
588 M.getNamedValue("objc_autorelease") ||
589 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
590 M.getNamedValue("objc_retainBlock") ||
591 M.getNamedValue("objc_autoreleaseReturnValue") ||
592 M.getNamedValue("objc_autoreleasePoolPush") ||
593 M.getNamedValue("objc_loadWeakRetained") ||
594 M.getNamedValue("objc_loadWeak") ||
595 M.getNamedValue("objc_destroyWeak") ||
596 M.getNamedValue("objc_storeWeak") ||
597 M.getNamedValue("objc_initWeak") ||
598 M.getNamedValue("objc_moveWeak") ||
599 M.getNamedValue("objc_copyWeak") ||
600 M.getNamedValue("objc_retainedObject") ||
601 M.getNamedValue("objc_unretainedObject") ||
602 M.getNamedValue("objc_unretainedPointer");
605 /// DoesObjCBlockEscape - Test whether the given pointer, which is an
606 /// Objective C block pointer, does not "escape". This differs from regular
607 /// escape analysis in that a use as an argument to a call is not considered
609 static bool DoesObjCBlockEscape(const Value *BlockPtr) {
610 // Walk the def-use chains.
611 SmallVector<const Value *, 4> Worklist;
612 Worklist.push_back(BlockPtr);
614 const Value *V = Worklist.pop_back_val();
615 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
617 const User *UUser = *UI;
618 // Special - Use by a call (callee or argument) is not considered
620 switch (GetBasicInstructionClass(UUser)) {
625 case IC_AutoreleaseRV:
626 // These special functions make copies of their pointer arguments.
630 // Use by an instruction which copies the value is an escape if the
631 // result is an escape.
632 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
633 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
634 Worklist.push_back(UUser);
637 // Use by a load is not an escape.
638 if (isa<LoadInst>(UUser))
640 // Use by a store is not an escape if the use is the address.
641 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
642 if (V != SI->getValueOperand())
646 // Regular calls and other stuff are not considered escapes.
649 // Otherwise, conservatively assume an escape.
652 } while (!Worklist.empty());
658 //===----------------------------------------------------------------------===//
659 // ARC AliasAnalysis.
660 //===----------------------------------------------------------------------===//
662 #include "llvm/Pass.h"
663 #include "llvm/Analysis/AliasAnalysis.h"
664 #include "llvm/Analysis/Passes.h"
667 /// ObjCARCAliasAnalysis - This is a simple alias analysis
668 /// implementation that uses knowledge of ARC constructs to answer queries.
670 /// TODO: This class could be generalized to know about other ObjC-specific
671 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
672 /// even though their offsets are dynamic.
673 class ObjCARCAliasAnalysis : public ImmutablePass,
674 public AliasAnalysis {
676 static char ID; // Class identification, replacement for typeinfo
677 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
678 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
682 virtual void initializePass() {
683 InitializeAliasAnalysis(this);
686 /// getAdjustedAnalysisPointer - This method is used when a pass implements
687 /// an analysis interface through multiple inheritance. If needed, it
688 /// should override this to adjust the this pointer as needed for the
689 /// specified pass info.
690 virtual void *getAdjustedAnalysisPointer(const void *PI) {
691 if (PI == &AliasAnalysis::ID)
692 return static_cast<AliasAnalysis *>(this);
696 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
697 virtual AliasResult alias(const Location &LocA, const Location &LocB);
698 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
699 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
700 virtual ModRefBehavior getModRefBehavior(const Function *F);
701 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
702 const Location &Loc);
703 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
704 ImmutableCallSite CS2);
706 } // End of anonymous namespace
708 // Register this pass...
709 char ObjCARCAliasAnalysis::ID = 0;
710 INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
711 "ObjC-ARC-Based Alias Analysis", false, true, false)
713 ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
714 return new ObjCARCAliasAnalysis();
718 ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
719 AU.setPreservesAll();
720 AliasAnalysis::getAnalysisUsage(AU);
723 AliasAnalysis::AliasResult
724 ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
726 return AliasAnalysis::alias(LocA, LocB);
728 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
729 // precise alias query.
730 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
731 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
733 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
734 Location(SB, LocB.Size, LocB.TBAATag));
735 if (Result != MayAlias)
738 // If that failed, climb to the underlying object, including climbing through
739 // ObjC-specific no-ops, and try making an imprecise alias query.
740 const Value *UA = GetUnderlyingObjCPtr(SA);
741 const Value *UB = GetUnderlyingObjCPtr(SB);
742 if (UA != SA || UB != SB) {
743 Result = AliasAnalysis::alias(Location(UA), Location(UB));
744 // We can't use MustAlias or PartialAlias results here because
745 // GetUnderlyingObjCPtr may return an offsetted pointer value.
746 if (Result == NoAlias)
750 // If that failed, fail. We don't need to chain here, since that's covered
751 // by the earlier precise query.
756 ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
759 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
761 // First, strip off no-ops, including ObjC-specific no-ops, and try making
762 // a precise alias query.
763 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
764 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
768 // If that failed, climb to the underlying object, including climbing through
769 // ObjC-specific no-ops, and try making an imprecise alias query.
770 const Value *U = GetUnderlyingObjCPtr(S);
772 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
774 // If that failed, fail. We don't need to chain here, since that's covered
775 // by the earlier precise query.
779 AliasAnalysis::ModRefBehavior
780 ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
781 // We have nothing to do. Just chain to the next AliasAnalysis.
782 return AliasAnalysis::getModRefBehavior(CS);
785 AliasAnalysis::ModRefBehavior
786 ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
788 return AliasAnalysis::getModRefBehavior(F);
790 switch (GetFunctionClass(F)) {
792 return DoesNotAccessMemory;
797 return AliasAnalysis::getModRefBehavior(F);
800 AliasAnalysis::ModRefResult
801 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
803 return AliasAnalysis::getModRefInfo(CS, Loc);
805 switch (GetBasicInstructionClass(CS.getInstruction())) {
809 case IC_AutoreleaseRV:
811 case IC_AutoreleasepoolPush:
812 case IC_FusedRetainAutorelease:
813 case IC_FusedRetainAutoreleaseRV:
814 // These functions don't access any memory visible to the compiler.
815 // Note that this doesn't include objc_retainBlock, because it updates
816 // pointers when it copies block data.
822 return AliasAnalysis::getModRefInfo(CS, Loc);
825 AliasAnalysis::ModRefResult
826 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
827 ImmutableCallSite CS2) {
828 // TODO: Theoretically we could check for dependencies between objc_* calls
829 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
830 return AliasAnalysis::getModRefInfo(CS1, CS2);
833 //===----------------------------------------------------------------------===//
835 //===----------------------------------------------------------------------===//
837 #include "llvm/Support/InstIterator.h"
838 #include "llvm/Transforms/Scalar.h"
841 /// ObjCARCExpand - Early ARC transformations.
842 class ObjCARCExpand : public FunctionPass {
843 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
844 virtual bool doInitialization(Module &M);
845 virtual bool runOnFunction(Function &F);
847 /// Run - A flag indicating whether this optimization pass should run.
852 ObjCARCExpand() : FunctionPass(ID) {
853 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
858 char ObjCARCExpand::ID = 0;
859 INITIALIZE_PASS(ObjCARCExpand,
860 "objc-arc-expand", "ObjC ARC expansion", false, false)
862 Pass *llvm::createObjCARCExpandPass() {
863 return new ObjCARCExpand();
866 void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
867 AU.setPreservesCFG();
870 bool ObjCARCExpand::doInitialization(Module &M) {
871 Run = ModuleHasARC(M);
875 bool ObjCARCExpand::runOnFunction(Function &F) {
879 // If nothing in the Module uses ARC, don't do anything.
883 bool Changed = false;
885 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
886 Instruction *Inst = &*I;
888 switch (GetBasicInstructionClass(Inst)) {
892 case IC_AutoreleaseRV:
893 case IC_FusedRetainAutorelease:
894 case IC_FusedRetainAutoreleaseRV:
895 // These calls return their argument verbatim, as a low-level
896 // optimization. However, this makes high-level optimizations
897 // harder. Undo any uses of this optimization that the front-end
898 // emitted here. We'll redo them in the contract pass.
900 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
910 //===----------------------------------------------------------------------===//
911 // ARC autorelease pool elimination.
912 //===----------------------------------------------------------------------===//
914 #include "llvm/Constants.h"
915 #include "llvm/ADT/STLExtras.h"
918 /// ObjCARCAPElim - Autorelease pool elimination.
919 class ObjCARCAPElim : public ModulePass {
920 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
921 virtual bool runOnModule(Module &M);
923 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
924 static bool OptimizeBB(BasicBlock *BB);
928 ObjCARCAPElim() : ModulePass(ID) {
929 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
934 char ObjCARCAPElim::ID = 0;
935 INITIALIZE_PASS(ObjCARCAPElim,
937 "ObjC ARC autorelease pool elimination",
940 Pass *llvm::createObjCARCAPElimPass() {
941 return new ObjCARCAPElim();
944 void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
945 AU.setPreservesCFG();
948 /// MayAutorelease - Interprocedurally determine if calls made by the
949 /// given call site can possibly produce autoreleases.
950 bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
951 if (const Function *Callee = CS.getCalledFunction()) {
952 if (Callee->isDeclaration() || Callee->mayBeOverridden())
954 for (Function::const_iterator I = Callee->begin(), E = Callee->end();
956 const BasicBlock *BB = I;
957 for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
959 if (ImmutableCallSite JCS = ImmutableCallSite(J))
960 // This recursion depth limit is arbitrary. It's just great
961 // enough to cover known interesting testcases.
963 !JCS.onlyReadsMemory() &&
964 MayAutorelease(JCS, Depth + 1))
973 bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
974 bool Changed = false;
976 Instruction *Push = 0;
977 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
978 Instruction *Inst = I++;
979 switch (GetBasicInstructionClass(Inst)) {
980 case IC_AutoreleasepoolPush:
983 case IC_AutoreleasepoolPop:
984 // If this pop matches a push and nothing in between can autorelease,
986 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
988 Inst->eraseFromParent();
989 Push->eraseFromParent();
994 if (MayAutorelease(ImmutableCallSite(Inst)))
1005 bool ObjCARCAPElim::runOnModule(Module &M) {
1009 // If nothing in the Module uses ARC, don't do anything.
1010 if (!ModuleHasARC(M))
1013 // Find the llvm.global_ctors variable, as the first step in
1014 // identifying the global constructors. In theory, unnecessary autorelease
1015 // pools could occur anywhere, but in practice it's pretty rare. Global
1016 // ctors are a place where autorelease pools get inserted automatically,
1017 // so it's pretty common for them to be unnecessary, and it's pretty
1018 // profitable to eliminate them.
1019 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1023 assert(GV->hasDefinitiveInitializer() &&
1024 "llvm.global_ctors is uncooperative!");
1026 bool Changed = false;
1028 // Dig the constructor functions out of GV's initializer.
1029 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1030 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1033 // llvm.global_ctors is an array of pairs where the second members
1034 // are constructor functions.
1035 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1036 // If the user used a constructor function with the wrong signature and
1037 // it got bitcasted or whatever, look the other way.
1040 // Only look at function definitions.
1041 if (F->isDeclaration())
1043 // Only look at functions with one basic block.
1044 if (llvm::next(F->begin()) != F->end())
1046 // Ok, a single-block constructor function definition. Try to optimize it.
1047 Changed |= OptimizeBB(F->begin());
1053 //===----------------------------------------------------------------------===//
1054 // ARC optimization.
1055 //===----------------------------------------------------------------------===//
1057 // TODO: On code like this:
1060 // stuff_that_cannot_release()
1061 // objc_autorelease(%x)
1062 // stuff_that_cannot_release()
1064 // stuff_that_cannot_release()
1065 // objc_autorelease(%x)
1067 // The second retain and autorelease can be deleted.
1069 // TODO: It should be possible to delete
1070 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
1071 // pairs if nothing is actually autoreleased between them. Also, autorelease
1072 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1073 // after inlining) can be turned into plain release calls.
1075 // TODO: Critical-edge splitting. If the optimial insertion point is
1076 // a critical edge, the current algorithm has to fail, because it doesn't
1077 // know how to split edges. It should be possible to make the optimizer
1078 // think in terms of edges, rather than blocks, and then split critical
1081 // TODO: OptimizeSequences could generalized to be Interprocedural.
1083 // TODO: Recognize that a bunch of other objc runtime calls have
1084 // non-escaping arguments and non-releasing arguments, and may be
1085 // non-autoreleasing.
1087 // TODO: Sink autorelease calls as far as possible. Unfortunately we
1088 // usually can't sink them past other calls, which would be the main
1089 // case where it would be useful.
1091 // TODO: The pointer returned from objc_loadWeakRetained is retained.
1093 // TODO: Delete release+retain pairs (rare).
1095 #include "llvm/LLVMContext.h"
1096 #include "llvm/Support/CFG.h"
1097 #include "llvm/ADT/Statistic.h"
1098 #include "llvm/ADT/SmallPtrSet.h"
1100 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1101 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1102 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1103 STATISTIC(NumRets, "Number of return value forwarding "
1104 "retain+autoreleaes eliminated");
1105 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1106 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1109 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1110 /// uses many of the same techniques, except it uses special ObjC-specific
1111 /// reasoning about pointer relationships.
1112 class ProvenanceAnalysis {
1115 typedef std::pair<const Value *, const Value *> ValuePairTy;
1116 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1117 CachedResultsTy CachedResults;
1119 bool relatedCheck(const Value *A, const Value *B);
1120 bool relatedSelect(const SelectInst *A, const Value *B);
1121 bool relatedPHI(const PHINode *A, const Value *B);
1123 // Do not implement.
1124 void operator=(const ProvenanceAnalysis &);
1125 ProvenanceAnalysis(const ProvenanceAnalysis &);
1128 ProvenanceAnalysis() {}
1130 void setAA(AliasAnalysis *aa) { AA = aa; }
1132 AliasAnalysis *getAA() const { return AA; }
1134 bool related(const Value *A, const Value *B);
1137 CachedResults.clear();
1142 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1143 // If the values are Selects with the same condition, we can do a more precise
1144 // check: just check for relations between the values on corresponding arms.
1145 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
1146 if (A->getCondition() == SB->getCondition())
1147 return related(A->getTrueValue(), SB->getTrueValue()) ||
1148 related(A->getFalseValue(), SB->getFalseValue());
1150 // Check both arms of the Select node individually.
1151 return related(A->getTrueValue(), B) ||
1152 related(A->getFalseValue(), B);
1155 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1156 // If the values are PHIs in the same block, we can do a more precise as well
1157 // as efficient check: just check for relations between the values on
1158 // corresponding edges.
1159 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1160 if (PNB->getParent() == A->getParent()) {
1161 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1162 if (related(A->getIncomingValue(i),
1163 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1168 // Check each unique source of the PHI node against B.
1169 SmallPtrSet<const Value *, 4> UniqueSrc;
1170 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1171 const Value *PV1 = A->getIncomingValue(i);
1172 if (UniqueSrc.insert(PV1) && related(PV1, B))
1176 // All of the arms checked out.
1180 /// isStoredObjCPointer - Test if the value of P, or any value covered by its
1181 /// provenance, is ever stored within the function (not counting callees).
1182 static bool isStoredObjCPointer(const Value *P) {
1183 SmallPtrSet<const Value *, 8> Visited;
1184 SmallVector<const Value *, 8> Worklist;
1185 Worklist.push_back(P);
1188 P = Worklist.pop_back_val();
1189 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1191 const User *Ur = *UI;
1192 if (isa<StoreInst>(Ur)) {
1193 if (UI.getOperandNo() == 0)
1194 // The pointer is stored.
1196 // The pointed is stored through.
1199 if (isa<CallInst>(Ur))
1200 // The pointer is passed as an argument, ignore this.
1202 if (isa<PtrToIntInst>(P))
1203 // Assume the worst.
1205 if (Visited.insert(Ur))
1206 Worklist.push_back(Ur);
1208 } while (!Worklist.empty());
1210 // Everything checked out.
1214 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1215 // Skip past provenance pass-throughs.
1216 A = GetUnderlyingObjCPtr(A);
1217 B = GetUnderlyingObjCPtr(B);
1223 // Ask regular AliasAnalysis, for a first approximation.
1224 switch (AA->alias(A, B)) {
1225 case AliasAnalysis::NoAlias:
1227 case AliasAnalysis::MustAlias:
1228 case AliasAnalysis::PartialAlias:
1230 case AliasAnalysis::MayAlias:
1234 bool AIsIdentified = IsObjCIdentifiedObject(A);
1235 bool BIsIdentified = IsObjCIdentifiedObject(B);
1237 // An ObjC-Identified object can't alias a load if it is never locally stored.
1238 if (AIsIdentified) {
1239 // Check for an obvious escape.
1240 if (isa<LoadInst>(B))
1241 return isStoredObjCPointer(A);
1242 if (BIsIdentified) {
1243 // Check for an obvious escape.
1244 if (isa<LoadInst>(A))
1245 return isStoredObjCPointer(B);
1246 // Both pointers are identified and escapes aren't an evident problem.
1249 } else if (BIsIdentified) {
1250 // Check for an obvious escape.
1251 if (isa<LoadInst>(A))
1252 return isStoredObjCPointer(B);
1255 // Special handling for PHI and Select.
1256 if (const PHINode *PN = dyn_cast<PHINode>(A))
1257 return relatedPHI(PN, B);
1258 if (const PHINode *PN = dyn_cast<PHINode>(B))
1259 return relatedPHI(PN, A);
1260 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1261 return relatedSelect(S, B);
1262 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1263 return relatedSelect(S, A);
1269 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1270 // Begin by inserting a conservative value into the map. If the insertion
1271 // fails, we have the answer already. If it succeeds, leave it there until we
1272 // compute the real answer to guard against recursive queries.
1273 if (A > B) std::swap(A, B);
1274 std::pair<CachedResultsTy::iterator, bool> Pair =
1275 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1277 return Pair.first->second;
1279 bool Result = relatedCheck(A, B);
1280 CachedResults[ValuePairTy(A, B)] = Result;
1285 // Sequence - A sequence of states that a pointer may go through in which an
1286 // objc_retain and objc_release are actually needed.
1289 S_Retain, ///< objc_retain(x)
1290 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1291 S_Use, ///< any use of x
1292 S_Stop, ///< like S_Release, but code motion is stopped
1293 S_Release, ///< objc_release(x)
1294 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1298 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1302 if (A == S_None || B == S_None)
1305 if (A > B) std::swap(A, B);
1307 // Choose the side which is further along in the sequence.
1308 if ((A == S_Retain || A == S_CanRelease) &&
1309 (B == S_CanRelease || B == S_Use))
1312 // Choose the side which is further along in the sequence.
1313 if ((A == S_Use || A == S_CanRelease) &&
1314 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
1316 // If both sides are releases, choose the more conservative one.
1317 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1319 if (A == S_Release && B == S_MovableRelease)
1327 /// RRInfo - Unidirectional information about either a
1328 /// retain-decrement-use-release sequence or release-use-decrement-retain
1329 /// reverese sequence.
1331 /// KnownSafe - After an objc_retain, the reference count of the referenced
1332 /// object is known to be positive. Similarly, before an objc_release, the
1333 /// reference count of the referenced object is known to be positive. If
1334 /// there are retain-release pairs in code regions where the retain count
1335 /// is known to be positive, they can be eliminated, regardless of any side
1336 /// effects between them.
1338 /// Also, a retain+release pair nested within another retain+release
1339 /// pair all on the known same pointer value can be eliminated, regardless
1340 /// of any intervening side effects.
1342 /// KnownSafe is true when either of these conditions is satisfied.
1345 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1346 /// opposed to objc_retain calls).
1349 /// IsTailCallRelease - True of the objc_release calls are all marked
1350 /// with the "tail" keyword.
1351 bool IsTailCallRelease;
1353 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1354 /// a clang.imprecise_release tag, this is the metadata tag.
1355 MDNode *ReleaseMetadata;
1357 /// Calls - For a top-down sequence, the set of objc_retains or
1358 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1359 SmallPtrSet<Instruction *, 2> Calls;
1361 /// ReverseInsertPts - The set of optimal insert positions for
1362 /// moving calls in the opposite sequence.
1363 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1366 KnownSafe(false), IsRetainBlock(false),
1367 IsTailCallRelease(false),
1368 ReleaseMetadata(0) {}
1374 void RRInfo::clear() {
1376 IsRetainBlock = false;
1377 IsTailCallRelease = false;
1378 ReleaseMetadata = 0;
1380 ReverseInsertPts.clear();
1384 /// PtrState - This class summarizes several per-pointer runtime properties
1385 /// which are propogated through the flow graph.
1387 /// KnownPositiveRefCount - True if the reference count is known to
1389 bool KnownPositiveRefCount;
1391 /// Partial - True of we've seen an opportunity for partial RR elimination,
1392 /// such as pushing calls into a CFG triangle or into one side of a
1396 /// Seq - The current position in the sequence.
1400 /// RRI - Unidirectional information about the current sequence.
1401 /// TODO: Encapsulate this better.
1404 PtrState() : KnownPositiveRefCount(false), Partial(false),
1407 void SetKnownPositiveRefCount() {
1408 KnownPositiveRefCount = true;
1411 void ClearRefCount() {
1412 KnownPositiveRefCount = false;
1415 bool IsKnownIncremented() const {
1416 return KnownPositiveRefCount;
1419 void SetSeq(Sequence NewSeq) {
1423 Sequence GetSeq() const {
1427 void ClearSequenceProgress() {
1428 ResetSequenceProgress(S_None);
1431 void ResetSequenceProgress(Sequence NewSeq) {
1437 void Merge(const PtrState &Other, bool TopDown);
1442 PtrState::Merge(const PtrState &Other, bool TopDown) {
1443 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1444 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
1446 // We can't merge a plain objc_retain with an objc_retainBlock.
1447 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1450 // If we're not in a sequence (anymore), drop all associated state.
1451 if (Seq == S_None) {
1454 } else if (Partial || Other.Partial) {
1455 // If we're doing a merge on a path that's previously seen a partial
1456 // merge, conservatively drop the sequence, to avoid doing partial
1457 // RR elimination. If the branch predicates for the two merge differ,
1458 // mixing them is unsafe.
1459 ClearSequenceProgress();
1461 // Conservatively merge the ReleaseMetadata information.
1462 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1463 RRI.ReleaseMetadata = 0;
1465 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
1466 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1467 Other.RRI.IsTailCallRelease;
1468 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1470 // Merge the insert point sets. If there are any differences,
1471 // that makes this a partial merge.
1472 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
1473 for (SmallPtrSet<Instruction *, 2>::const_iterator
1474 I = Other.RRI.ReverseInsertPts.begin(),
1475 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1476 Partial |= RRI.ReverseInsertPts.insert(*I);
1481 /// BBState - Per-BasicBlock state.
1483 /// TopDownPathCount - The number of unique control paths from the entry
1484 /// which can reach this block.
1485 unsigned TopDownPathCount;
1487 /// BottomUpPathCount - The number of unique control paths to exits
1488 /// from this block.
1489 unsigned BottomUpPathCount;
1491 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1492 typedef MapVector<const Value *, PtrState> MapTy;
1494 /// PerPtrTopDown - The top-down traversal uses this to record information
1495 /// known about a pointer at the bottom of each block.
1496 MapTy PerPtrTopDown;
1498 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1499 /// known about a pointer at the top of each block.
1500 MapTy PerPtrBottomUp;
1502 /// Preds, Succs - Effective successors and predecessors of the current
1503 /// block (this ignores ignorable edges and ignored backedges).
1504 SmallVector<BasicBlock *, 2> Preds;
1505 SmallVector<BasicBlock *, 2> Succs;
1508 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1510 typedef MapTy::iterator ptr_iterator;
1511 typedef MapTy::const_iterator ptr_const_iterator;
1513 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1514 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1515 ptr_const_iterator top_down_ptr_begin() const {
1516 return PerPtrTopDown.begin();
1518 ptr_const_iterator top_down_ptr_end() const {
1519 return PerPtrTopDown.end();
1522 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1523 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1524 ptr_const_iterator bottom_up_ptr_begin() const {
1525 return PerPtrBottomUp.begin();
1527 ptr_const_iterator bottom_up_ptr_end() const {
1528 return PerPtrBottomUp.end();
1531 /// SetAsEntry - Mark this block as being an entry block, which has one
1532 /// path from the entry by definition.
1533 void SetAsEntry() { TopDownPathCount = 1; }
1535 /// SetAsExit - Mark this block as being an exit block, which has one
1536 /// path to an exit by definition.
1537 void SetAsExit() { BottomUpPathCount = 1; }
1539 PtrState &getPtrTopDownState(const Value *Arg) {
1540 return PerPtrTopDown[Arg];
1543 PtrState &getPtrBottomUpState(const Value *Arg) {
1544 return PerPtrBottomUp[Arg];
1547 void clearBottomUpPointers() {
1548 PerPtrBottomUp.clear();
1551 void clearTopDownPointers() {
1552 PerPtrTopDown.clear();
1555 void InitFromPred(const BBState &Other);
1556 void InitFromSucc(const BBState &Other);
1557 void MergePred(const BBState &Other);
1558 void MergeSucc(const BBState &Other);
1560 /// GetAllPathCount - Return the number of possible unique paths from an
1561 /// entry to an exit which pass through this block. This is only valid
1562 /// after both the top-down and bottom-up traversals are complete.
1563 unsigned GetAllPathCount() const {
1564 assert(TopDownPathCount != 0);
1565 assert(BottomUpPathCount != 0);
1566 return TopDownPathCount * BottomUpPathCount;
1569 // Specialized CFG utilities.
1570 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
1571 edge_iterator pred_begin() { return Preds.begin(); }
1572 edge_iterator pred_end() { return Preds.end(); }
1573 edge_iterator succ_begin() { return Succs.begin(); }
1574 edge_iterator succ_end() { return Succs.end(); }
1576 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1577 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1579 bool isExit() const { return Succs.empty(); }
1583 void BBState::InitFromPred(const BBState &Other) {
1584 PerPtrTopDown = Other.PerPtrTopDown;
1585 TopDownPathCount = Other.TopDownPathCount;
1588 void BBState::InitFromSucc(const BBState &Other) {
1589 PerPtrBottomUp = Other.PerPtrBottomUp;
1590 BottomUpPathCount = Other.BottomUpPathCount;
1593 /// MergePred - The top-down traversal uses this to merge information about
1594 /// predecessors to form the initial state for a new block.
1595 void BBState::MergePred(const BBState &Other) {
1596 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1597 // loop backedge. Loop backedges are special.
1598 TopDownPathCount += Other.TopDownPathCount;
1600 // For each entry in the other set, if our set has an entry with the same key,
1601 // merge the entries. Otherwise, copy the entry and merge it with an empty
1603 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1604 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1605 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1606 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1610 // For each entry in our set, if the other set doesn't have an entry with the
1611 // same key, force it to merge with an empty entry.
1612 for (ptr_iterator MI = top_down_ptr_begin(),
1613 ME = top_down_ptr_end(); MI != ME; ++MI)
1614 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1615 MI->second.Merge(PtrState(), /*TopDown=*/true);
1618 /// MergeSucc - The bottom-up traversal uses this to merge information about
1619 /// successors to form the initial state for a new block.
1620 void BBState::MergeSucc(const BBState &Other) {
1621 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1622 // loop backedge. Loop backedges are special.
1623 BottomUpPathCount += Other.BottomUpPathCount;
1625 // For each entry in the other set, if our set has an entry with the
1626 // same key, merge the entries. Otherwise, copy the entry and merge
1627 // it with an empty entry.
1628 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1629 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1630 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1631 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1635 // For each entry in our set, if the other set doesn't have an entry
1636 // with the same key, force it to merge with an empty entry.
1637 for (ptr_iterator MI = bottom_up_ptr_begin(),
1638 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1639 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1640 MI->second.Merge(PtrState(), /*TopDown=*/false);
1644 /// ObjCARCOpt - The main ARC optimization pass.
1645 class ObjCARCOpt : public FunctionPass {
1647 ProvenanceAnalysis PA;
1649 /// Run - A flag indicating whether this optimization pass should run.
1652 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1653 /// functions, for use in creating calls to them. These are initialized
1654 /// lazily to avoid cluttering up the Module with unused declarations.
1655 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
1656 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
1658 /// UsedInThisFunciton - Flags which determine whether each of the
1659 /// interesting runtine functions is in fact used in the current function.
1660 unsigned UsedInThisFunction;
1662 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1664 unsigned ImpreciseReleaseMDKind;
1666 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
1668 unsigned CopyOnEscapeMDKind;
1670 /// NoObjCARCExceptionsMDKind - The Metadata Kind for
1671 /// clang.arc.no_objc_arc_exceptions metadata.
1672 unsigned NoObjCARCExceptionsMDKind;
1674 Constant *getRetainRVCallee(Module *M);
1675 Constant *getAutoreleaseRVCallee(Module *M);
1676 Constant *getReleaseCallee(Module *M);
1677 Constant *getRetainCallee(Module *M);
1678 Constant *getRetainBlockCallee(Module *M);
1679 Constant *getAutoreleaseCallee(Module *M);
1681 bool IsRetainBlockOptimizable(const Instruction *Inst);
1683 void OptimizeRetainCall(Function &F, Instruction *Retain);
1684 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1685 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1686 void OptimizeIndividualCalls(Function &F);
1688 void CheckForCFGHazards(const BasicBlock *BB,
1689 DenseMap<const BasicBlock *, BBState> &BBStates,
1690 BBState &MyStates) const;
1691 bool VisitInstructionBottomUp(Instruction *Inst,
1693 MapVector<Value *, RRInfo> &Retains,
1695 bool VisitBottomUp(BasicBlock *BB,
1696 DenseMap<const BasicBlock *, BBState> &BBStates,
1697 MapVector<Value *, RRInfo> &Retains);
1698 bool VisitInstructionTopDown(Instruction *Inst,
1699 DenseMap<Value *, RRInfo> &Releases,
1701 bool VisitTopDown(BasicBlock *BB,
1702 DenseMap<const BasicBlock *, BBState> &BBStates,
1703 DenseMap<Value *, RRInfo> &Releases);
1704 bool Visit(Function &F,
1705 DenseMap<const BasicBlock *, BBState> &BBStates,
1706 MapVector<Value *, RRInfo> &Retains,
1707 DenseMap<Value *, RRInfo> &Releases);
1709 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1710 MapVector<Value *, RRInfo> &Retains,
1711 DenseMap<Value *, RRInfo> &Releases,
1712 SmallVectorImpl<Instruction *> &DeadInsts,
1715 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1716 MapVector<Value *, RRInfo> &Retains,
1717 DenseMap<Value *, RRInfo> &Releases,
1720 void OptimizeWeakCalls(Function &F);
1722 bool OptimizeSequences(Function &F);
1724 void OptimizeReturns(Function &F);
1726 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1727 virtual bool doInitialization(Module &M);
1728 virtual bool runOnFunction(Function &F);
1729 virtual void releaseMemory();
1733 ObjCARCOpt() : FunctionPass(ID) {
1734 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1739 char ObjCARCOpt::ID = 0;
1740 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1741 "objc-arc", "ObjC ARC optimization", false, false)
1742 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1743 INITIALIZE_PASS_END(ObjCARCOpt,
1744 "objc-arc", "ObjC ARC optimization", false, false)
1746 Pass *llvm::createObjCARCOptPass() {
1747 return new ObjCARCOpt();
1750 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1751 AU.addRequired<ObjCARCAliasAnalysis>();
1752 AU.addRequired<AliasAnalysis>();
1753 // ARC optimization doesn't currently split critical edges.
1754 AU.setPreservesCFG();
1757 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1758 // Without the magic metadata tag, we have to assume this might be an
1759 // objc_retainBlock call inserted to convert a block pointer to an id,
1760 // in which case it really is needed.
1761 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1764 // If the pointer "escapes" (not including being used in a call),
1765 // the copy may be needed.
1766 if (DoesObjCBlockEscape(Inst))
1769 // Otherwise, it's not needed.
1773 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1774 if (!RetainRVCallee) {
1775 LLVMContext &C = M->getContext();
1776 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1777 Type *Params[] = { I8X };
1778 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1779 AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
1781 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1784 return RetainRVCallee;
1787 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1788 if (!AutoreleaseRVCallee) {
1789 LLVMContext &C = M->getContext();
1790 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1791 Type *Params[] = { I8X };
1792 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1793 AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
1794 AutoreleaseRVCallee =
1795 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1798 return AutoreleaseRVCallee;
1801 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1802 if (!ReleaseCallee) {
1803 LLVMContext &C = M->getContext();
1804 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1805 AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
1807 M->getOrInsertFunction(
1809 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1812 return ReleaseCallee;
1815 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1816 if (!RetainCallee) {
1817 LLVMContext &C = M->getContext();
1818 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1819 AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
1821 M->getOrInsertFunction(
1823 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1826 return RetainCallee;
1829 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1830 if (!RetainBlockCallee) {
1831 LLVMContext &C = M->getContext();
1832 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1833 // objc_retainBlock is not nounwind because it calls user copy constructors
1834 // which could theoretically throw.
1836 M->getOrInsertFunction(
1838 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1841 return RetainBlockCallee;
1844 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1845 if (!AutoreleaseCallee) {
1846 LLVMContext &C = M->getContext();
1847 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1848 AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
1850 M->getOrInsertFunction(
1852 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1855 return AutoreleaseCallee;
1858 /// IsPotentialUse - Test whether the given value is possible a
1859 /// reference-counted pointer, including tests which utilize AliasAnalysis.
1860 static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
1861 // First make the rudimentary check.
1862 if (!IsPotentialUse(Op))
1865 // Objects in constant memory are not reference-counted.
1866 if (AA.pointsToConstantMemory(Op))
1869 // Pointers in constant memory are not pointing to reference-counted objects.
1870 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1871 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1874 // Otherwise assume the worst.
1878 /// CanAlterRefCount - Test whether the given instruction can result in a
1879 /// reference count modification (positive or negative) for the pointer's
1882 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1883 ProvenanceAnalysis &PA, InstructionClass Class) {
1885 case IC_Autorelease:
1886 case IC_AutoreleaseRV:
1888 // These operations never directly modify a reference count.
1893 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1894 assert(CS && "Only calls can alter reference counts!");
1896 // See if AliasAnalysis can help us with the call.
1897 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1898 if (AliasAnalysis::onlyReadsMemory(MRB))
1900 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1901 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1903 const Value *Op = *I;
1904 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
1910 // Assume the worst.
1914 /// CanUse - Test whether the given instruction can "use" the given pointer's
1915 /// object in a way that requires the reference count to be positive.
1917 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1918 InstructionClass Class) {
1919 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1920 if (Class == IC_Call)
1923 // Consider various instructions which may have pointer arguments which are
1925 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1926 // Comparing a pointer with null, or any other constant, isn't really a use,
1927 // because we don't care what the pointer points to, or about the values
1928 // of any other dynamic reference-counted pointers.
1929 if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
1931 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1932 // For calls, just check the arguments (and not the callee operand).
1933 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1934 OE = CS.arg_end(); OI != OE; ++OI) {
1935 const Value *Op = *OI;
1936 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
1940 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1941 // Special-case stores, because we don't care about the stored value, just
1942 // the store address.
1943 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1944 // If we can't tell what the underlying object was, assume there is a
1946 return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
1949 // Check each operand for a match.
1950 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1952 const Value *Op = *OI;
1953 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
1959 /// CanInterruptRV - Test whether the given instruction can autorelease
1960 /// any pointer or cause an autoreleasepool pop.
1962 CanInterruptRV(InstructionClass Class) {
1964 case IC_AutoreleasepoolPop:
1967 case IC_Autorelease:
1968 case IC_AutoreleaseRV:
1969 case IC_FusedRetainAutorelease:
1970 case IC_FusedRetainAutoreleaseRV:
1978 /// DependenceKind - There are several kinds of dependence-like concepts in
1980 enum DependenceKind {
1981 NeedsPositiveRetainCount,
1982 AutoreleasePoolBoundary,
1983 CanChangeRetainCount,
1984 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1985 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1986 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1990 /// Depends - Test if there can be dependencies on Inst through Arg. This
1991 /// function only tests dependencies relevant for removing pairs of calls.
1993 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1994 ProvenanceAnalysis &PA) {
1995 // If we've reached the definition of Arg, stop.
2000 case NeedsPositiveRetainCount: {
2001 InstructionClass Class = GetInstructionClass(Inst);
2003 case IC_AutoreleasepoolPop:
2004 case IC_AutoreleasepoolPush:
2008 return CanUse(Inst, Arg, PA, Class);
2012 case AutoreleasePoolBoundary: {
2013 InstructionClass Class = GetInstructionClass(Inst);
2015 case IC_AutoreleasepoolPop:
2016 case IC_AutoreleasepoolPush:
2017 // These mark the end and begin of an autorelease pool scope.
2020 // Nothing else does this.
2025 case CanChangeRetainCount: {
2026 InstructionClass Class = GetInstructionClass(Inst);
2028 case IC_AutoreleasepoolPop:
2029 // Conservatively assume this can decrement any count.
2031 case IC_AutoreleasepoolPush:
2035 return CanAlterRefCount(Inst, Arg, PA, Class);
2039 case RetainAutoreleaseDep:
2040 switch (GetBasicInstructionClass(Inst)) {
2041 case IC_AutoreleasepoolPop:
2042 case IC_AutoreleasepoolPush:
2043 // Don't merge an objc_autorelease with an objc_retain inside a different
2044 // autoreleasepool scope.
2048 // Check for a retain of the same pointer for merging.
2049 return GetObjCArg(Inst) == Arg;
2051 // Nothing else matters for objc_retainAutorelease formation.
2055 case RetainAutoreleaseRVDep: {
2056 InstructionClass Class = GetBasicInstructionClass(Inst);
2060 // Check for a retain of the same pointer for merging.
2061 return GetObjCArg(Inst) == Arg;
2063 // Anything that can autorelease interrupts
2064 // retainAutoreleaseReturnValue formation.
2065 return CanInterruptRV(Class);
2070 return CanInterruptRV(GetBasicInstructionClass(Inst));
2073 llvm_unreachable("Invalid dependence flavor");
2076 /// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2077 /// find local and non-local dependencies on Arg.
2078 /// TODO: Cache results?
2080 FindDependencies(DependenceKind Flavor,
2082 BasicBlock *StartBB, Instruction *StartInst,
2083 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2084 SmallPtrSet<const BasicBlock *, 4> &Visited,
2085 ProvenanceAnalysis &PA) {
2086 BasicBlock::iterator StartPos = StartInst;
2088 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2089 Worklist.push_back(std::make_pair(StartBB, StartPos));
2091 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2092 Worklist.pop_back_val();
2093 BasicBlock *LocalStartBB = Pair.first;
2094 BasicBlock::iterator LocalStartPos = Pair.second;
2095 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2097 if (LocalStartPos == StartBBBegin) {
2098 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2100 // If we've reached the function entry, produce a null dependence.
2101 DependingInstructions.insert(0);
2103 // Add the predecessors to the worklist.
2105 BasicBlock *PredBB = *PI;
2106 if (Visited.insert(PredBB))
2107 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2108 } while (++PI != PE);
2112 Instruction *Inst = --LocalStartPos;
2113 if (Depends(Flavor, Inst, Arg, PA)) {
2114 DependingInstructions.insert(Inst);
2118 } while (!Worklist.empty());
2120 // Determine whether the original StartBB post-dominates all of the blocks we
2121 // visited. If not, insert a sentinal indicating that most optimizations are
2123 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2124 E = Visited.end(); I != E; ++I) {
2125 const BasicBlock *BB = *I;
2128 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2129 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2130 const BasicBlock *Succ = *SI;
2131 if (Succ != StartBB && !Visited.count(Succ)) {
2132 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2139 static bool isNullOrUndef(const Value *V) {
2140 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2143 static bool isNoopInstruction(const Instruction *I) {
2144 return isa<BitCastInst>(I) ||
2145 (isa<GetElementPtrInst>(I) &&
2146 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2149 /// OptimizeRetainCall - Turn objc_retain into
2150 /// objc_retainAutoreleasedReturnValue if the operand is a return value.
2152 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
2153 ImmutableCallSite CS(GetObjCArg(Retain));
2154 const Instruction *Call = CS.getInstruction();
2156 if (Call->getParent() != Retain->getParent()) return;
2158 // Check that the call is next to the retain.
2159 BasicBlock::const_iterator I = Call;
2161 while (isNoopInstruction(I)) ++I;
2165 // Turn it to an objc_retainAutoreleasedReturnValue..
2168 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2171 /// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
2172 /// objc_retain if the operand is not a return value. Or, if it can be paired
2173 /// with an objc_autoreleaseReturnValue, delete the pair and return true.
2175 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
2176 // Check for the argument being from an immediately preceding call or invoke.
2177 const Value *Arg = GetObjCArg(RetainRV);
2178 ImmutableCallSite CS(Arg);
2179 if (const Instruction *Call = CS.getInstruction()) {
2180 if (Call->getParent() == RetainRV->getParent()) {
2181 BasicBlock::const_iterator I = Call;
2183 while (isNoopInstruction(I)) ++I;
2184 if (&*I == RetainRV)
2186 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
2187 BasicBlock *RetainRVParent = RetainRV->getParent();
2188 if (II->getNormalDest() == RetainRVParent) {
2189 BasicBlock::const_iterator I = RetainRVParent->begin();
2190 while (isNoopInstruction(I)) ++I;
2191 if (&*I == RetainRV)
2197 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2198 // pointer. In this case, we can delete the pair.
2199 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2201 do --I; while (I != Begin && isNoopInstruction(I));
2202 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2203 GetObjCArg(I) == Arg) {
2206 EraseInstruction(I);
2207 EraseInstruction(RetainRV);
2212 // Turn it to a plain objc_retain.
2215 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2219 /// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2220 /// objc_autorelease if the result is not used as a return value.
2222 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
2223 // Check for a return of the pointer value.
2224 const Value *Ptr = GetObjCArg(AutoreleaseRV);
2225 SmallVector<const Value *, 2> Users;
2226 Users.push_back(Ptr);
2228 Ptr = Users.pop_back_val();
2229 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2231 const User *I = *UI;
2232 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2234 if (isa<BitCastInst>(I))
2237 } while (!Users.empty());
2241 cast<CallInst>(AutoreleaseRV)->
2242 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2245 /// OptimizeIndividualCalls - Visit each call, one at a time, and make
2246 /// simplifications without doing any additional analysis.
2247 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2248 // Reset all the flags in preparation for recomputing them.
2249 UsedInThisFunction = 0;
2251 // Visit all objc_* calls in F.
2252 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2253 Instruction *Inst = &*I++;
2254 InstructionClass Class = GetBasicInstructionClass(Inst);
2259 // Delete no-op casts. These function calls have special semantics, but
2260 // the semantics are entirely implemented via lowering in the front-end,
2261 // so by the time they reach the optimizer, they are just no-op calls
2262 // which return their argument.
2264 // There are gray areas here, as the ability to cast reference-counted
2265 // pointers to raw void* and back allows code to break ARC assumptions,
2266 // however these are currently considered to be unimportant.
2270 EraseInstruction(Inst);
2273 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2276 case IC_LoadWeakRetained:
2278 case IC_DestroyWeak: {
2279 CallInst *CI = cast<CallInst>(Inst);
2280 if (isNullOrUndef(CI->getArgOperand(0))) {
2282 Type *Ty = CI->getArgOperand(0)->getType();
2283 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2284 Constant::getNullValue(Ty),
2286 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2287 CI->eraseFromParent();
2294 CallInst *CI = cast<CallInst>(Inst);
2295 if (isNullOrUndef(CI->getArgOperand(0)) ||
2296 isNullOrUndef(CI->getArgOperand(1))) {
2298 Type *Ty = CI->getArgOperand(0)->getType();
2299 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2300 Constant::getNullValue(Ty),
2302 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2303 CI->eraseFromParent();
2309 OptimizeRetainCall(F, Inst);
2312 if (OptimizeRetainRVCall(F, Inst))
2315 case IC_AutoreleaseRV:
2316 OptimizeAutoreleaseRVCall(F, Inst);
2320 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2321 if (IsAutorelease(Class) && Inst->use_empty()) {
2322 CallInst *Call = cast<CallInst>(Inst);
2323 const Value *Arg = Call->getArgOperand(0);
2324 Arg = FindSingleUseIdentifiedObject(Arg);
2329 // Create the declaration lazily.
2330 LLVMContext &C = Inst->getContext();
2332 CallInst::Create(getReleaseCallee(F.getParent()),
2333 Call->getArgOperand(0), "", Call);
2334 NewCall->setMetadata(ImpreciseReleaseMDKind,
2335 MDNode::get(C, ArrayRef<Value *>()));
2336 EraseInstruction(Call);
2342 // For functions which can never be passed stack arguments, add
2344 if (IsAlwaysTail(Class)) {
2346 cast<CallInst>(Inst)->setTailCall();
2349 // Set nounwind as needed.
2350 if (IsNoThrow(Class)) {
2352 cast<CallInst>(Inst)->setDoesNotThrow();
2355 if (!IsNoopOnNull(Class)) {
2356 UsedInThisFunction |= 1 << Class;
2360 const Value *Arg = GetObjCArg(Inst);
2362 // ARC calls with null are no-ops. Delete them.
2363 if (isNullOrUndef(Arg)) {
2366 EraseInstruction(Inst);
2370 // Keep track of which of retain, release, autorelease, and retain_block
2371 // are actually present in this function.
2372 UsedInThisFunction |= 1 << Class;
2374 // If Arg is a PHI, and one or more incoming values to the
2375 // PHI are null, and the call is control-equivalent to the PHI, and there
2376 // are no relevant side effects between the PHI and the call, the call
2377 // could be pushed up to just those paths with non-null incoming values.
2378 // For now, don't bother splitting critical edges for this.
2379 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2380 Worklist.push_back(std::make_pair(Inst, Arg));
2382 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2386 const PHINode *PN = dyn_cast<PHINode>(Arg);
2389 // Determine if the PHI has any null operands, or any incoming
2391 bool HasNull = false;
2392 bool HasCriticalEdges = false;
2393 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2395 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2396 if (isNullOrUndef(Incoming))
2398 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2399 .getNumSuccessors() != 1) {
2400 HasCriticalEdges = true;
2404 // If we have null operands and no critical edges, optimize.
2405 if (!HasCriticalEdges && HasNull) {
2406 SmallPtrSet<Instruction *, 4> DependingInstructions;
2407 SmallPtrSet<const BasicBlock *, 4> Visited;
2409 // Check that there is nothing that cares about the reference
2410 // count between the call and the phi.
2413 case IC_RetainBlock:
2414 // These can always be moved up.
2417 // These can't be moved across things that care about the retain
2419 FindDependencies(NeedsPositiveRetainCount, Arg,
2420 Inst->getParent(), Inst,
2421 DependingInstructions, Visited, PA);
2423 case IC_Autorelease:
2424 // These can't be moved across autorelease pool scope boundaries.
2425 FindDependencies(AutoreleasePoolBoundary, Arg,
2426 Inst->getParent(), Inst,
2427 DependingInstructions, Visited, PA);
2430 case IC_AutoreleaseRV:
2431 // Don't move these; the RV optimization depends on the autoreleaseRV
2432 // being tail called, and the retainRV being immediately after a call
2433 // (which might still happen if we get lucky with codegen layout, but
2434 // it's not worth taking the chance).
2437 llvm_unreachable("Invalid dependence flavor");
2440 if (DependingInstructions.size() == 1 &&
2441 *DependingInstructions.begin() == PN) {
2444 // Clone the call into each predecessor that has a non-null value.
2445 CallInst *CInst = cast<CallInst>(Inst);
2446 Type *ParamTy = CInst->getArgOperand(0)->getType();
2447 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2449 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2450 if (!isNullOrUndef(Incoming)) {
2451 CallInst *Clone = cast<CallInst>(CInst->clone());
2452 Value *Op = PN->getIncomingValue(i);
2453 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2454 if (Op->getType() != ParamTy)
2455 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2456 Clone->setArgOperand(0, Op);
2457 Clone->insertBefore(InsertPos);
2458 Worklist.push_back(std::make_pair(Clone, Incoming));
2461 // Erase the original call.
2462 EraseInstruction(CInst);
2466 } while (!Worklist.empty());
2470 /// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2471 /// control flow, or other CFG structures where moving code across the edge
2472 /// would result in it being executed more.
2474 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2475 DenseMap<const BasicBlock *, BBState> &BBStates,
2476 BBState &MyStates) const {
2477 // If any top-down local-use or possible-dec has a succ which is earlier in
2478 // the sequence, forget it.
2479 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
2480 E = MyStates.top_down_ptr_end(); I != E; ++I)
2481 switch (I->second.GetSeq()) {
2484 const Value *Arg = I->first;
2485 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2486 bool SomeSuccHasSame = false;
2487 bool AllSuccsHaveSame = true;
2488 PtrState &S = I->second;
2489 succ_const_iterator SI(TI), SE(TI, false);
2491 // If the terminator is an invoke marked with the
2492 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2493 // ignored, for ARC purposes.
2494 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2497 for (; SI != SE; ++SI) {
2498 Sequence SuccSSeq = S_None;
2499 bool SuccSRRIKnownSafe = false;
2500 // If VisitBottomUp has pointer information for this successor, take
2501 // what we know about it.
2502 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2504 assert(BBI != BBStates.end());
2505 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2506 SuccSSeq = SuccS.GetSeq();
2507 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2510 case S_CanRelease: {
2511 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2512 S.ClearSequenceProgress();
2518 SomeSuccHasSame = true;
2522 case S_MovableRelease:
2523 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2524 AllSuccsHaveSame = false;
2527 llvm_unreachable("bottom-up pointer in retain state!");
2530 // If the state at the other end of any of the successor edges
2531 // matches the current state, require all edges to match. This
2532 // guards against loops in the middle of a sequence.
2533 if (SomeSuccHasSame && !AllSuccsHaveSame)
2534 S.ClearSequenceProgress();
2537 case S_CanRelease: {
2538 const Value *Arg = I->first;
2539 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2540 bool SomeSuccHasSame = false;
2541 bool AllSuccsHaveSame = true;
2542 PtrState &S = I->second;
2543 succ_const_iterator SI(TI), SE(TI, false);
2545 // If the terminator is an invoke marked with the
2546 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2547 // ignored, for ARC purposes.
2548 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2551 for (; SI != SE; ++SI) {
2552 Sequence SuccSSeq = S_None;
2553 bool SuccSRRIKnownSafe = false;
2554 // If VisitBottomUp has pointer information for this successor, take
2555 // what we know about it.
2556 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2558 assert(BBI != BBStates.end());
2559 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2560 SuccSSeq = SuccS.GetSeq();
2561 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2564 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2565 S.ClearSequenceProgress();
2571 SomeSuccHasSame = true;
2575 case S_MovableRelease:
2577 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2578 AllSuccsHaveSame = false;
2581 llvm_unreachable("bottom-up pointer in retain state!");
2584 // If the state at the other end of any of the successor edges
2585 // matches the current state, require all edges to match. This
2586 // guards against loops in the middle of a sequence.
2587 if (SomeSuccHasSame && !AllSuccsHaveSame)
2588 S.ClearSequenceProgress();
2595 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
2597 MapVector<Value *, RRInfo> &Retains,
2598 BBState &MyStates) {
2599 bool NestingDetected = false;
2600 InstructionClass Class = GetInstructionClass(Inst);
2601 const Value *Arg = 0;
2605 Arg = GetObjCArg(Inst);
2607 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2609 // If we see two releases in a row on the same pointer. If so, make
2610 // a note, and we'll cicle back to revisit it after we've
2611 // hopefully eliminated the second release, which may allow us to
2612 // eliminate the first release too.
2613 // Theoretically we could implement removal of nested retain+release
2614 // pairs by making PtrState hold a stack of states, but this is
2615 // simple and avoids adding overhead for the non-nested case.
2616 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2617 NestingDetected = true;
2619 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2620 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
2621 S.RRI.ReleaseMetadata = ReleaseMetadata;
2622 S.RRI.KnownSafe = S.IsKnownIncremented();
2623 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2624 S.RRI.Calls.insert(Inst);
2626 S.SetKnownPositiveRefCount();
2629 case IC_RetainBlock:
2630 // An objc_retainBlock call with just a use may need to be kept,
2631 // because it may be copying a block from the stack to the heap.
2632 if (!IsRetainBlockOptimizable(Inst))
2637 Arg = GetObjCArg(Inst);
2639 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2640 S.SetKnownPositiveRefCount();
2642 switch (S.GetSeq()) {
2645 case S_MovableRelease:
2647 S.RRI.ReverseInsertPts.clear();
2650 // Don't do retain+release tracking for IC_RetainRV, because it's
2651 // better to let it remain as the first instruction after a call.
2652 if (Class != IC_RetainRV) {
2653 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2654 Retains[Inst] = S.RRI;
2656 S.ClearSequenceProgress();
2661 llvm_unreachable("bottom-up pointer in retain state!");
2663 return NestingDetected;
2665 case IC_AutoreleasepoolPop:
2666 // Conservatively, clear MyStates for all known pointers.
2667 MyStates.clearBottomUpPointers();
2668 return NestingDetected;
2669 case IC_AutoreleasepoolPush:
2671 // These are irrelevant.
2672 return NestingDetected;
2677 // Consider any other possible effects of this instruction on each
2678 // pointer being tracked.
2679 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2680 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2681 const Value *Ptr = MI->first;
2683 continue; // Handled above.
2684 PtrState &S = MI->second;
2685 Sequence Seq = S.GetSeq();
2687 // Check for possible releases.
2688 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2692 S.SetSeq(S_CanRelease);
2696 case S_MovableRelease:
2701 llvm_unreachable("bottom-up pointer in retain state!");
2705 // Check for possible direct uses.
2708 case S_MovableRelease:
2709 if (CanUse(Inst, Ptr, PA, Class)) {
2710 assert(S.RRI.ReverseInsertPts.empty());
2711 // If this is an invoke instruction, we're scanning it as part of
2712 // one of its successor blocks, since we can't insert code after it
2713 // in its own block, and we don't want to split critical edges.
2714 if (isa<InvokeInst>(Inst))
2715 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2717 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2719 } else if (Seq == S_Release &&
2720 (Class == IC_User || Class == IC_CallOrUser)) {
2721 // Non-movable releases depend on any possible objc pointer use.
2723 assert(S.RRI.ReverseInsertPts.empty());
2724 // As above; handle invoke specially.
2725 if (isa<InvokeInst>(Inst))
2726 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2728 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2732 if (CanUse(Inst, Ptr, PA, Class))
2740 llvm_unreachable("bottom-up pointer in retain state!");
2744 return NestingDetected;
2748 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2749 DenseMap<const BasicBlock *, BBState> &BBStates,
2750 MapVector<Value *, RRInfo> &Retains) {
2751 bool NestingDetected = false;
2752 BBState &MyStates = BBStates[BB];
2754 // Merge the states from each successor to compute the initial state
2755 // for the current block.
2756 BBState::edge_iterator SI(MyStates.succ_begin()),
2757 SE(MyStates.succ_end());
2759 const BasicBlock *Succ = *SI;
2760 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2761 assert(I != BBStates.end());
2762 MyStates.InitFromSucc(I->second);
2764 for (; SI != SE; ++SI) {
2766 I = BBStates.find(Succ);
2767 assert(I != BBStates.end());
2768 MyStates.MergeSucc(I->second);
2772 // Visit all the instructions, bottom-up.
2773 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2774 Instruction *Inst = llvm::prior(I);
2776 // Invoke instructions are visited as part of their successors (below).
2777 if (isa<InvokeInst>(Inst))
2780 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2783 // If there's a predecessor with an invoke, visit the invoke as if it were
2784 // part of this block, since we can't insert code after an invoke in its own
2785 // block, and we don't want to split critical edges.
2786 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2787 PE(MyStates.pred_end()); PI != PE; ++PI) {
2788 BasicBlock *Pred = *PI;
2789 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2790 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
2793 return NestingDetected;
2797 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2798 DenseMap<Value *, RRInfo> &Releases,
2799 BBState &MyStates) {
2800 bool NestingDetected = false;
2801 InstructionClass Class = GetInstructionClass(Inst);
2802 const Value *Arg = 0;
2805 case IC_RetainBlock:
2806 // An objc_retainBlock call with just a use may need to be kept,
2807 // because it may be copying a block from the stack to the heap.
2808 if (!IsRetainBlockOptimizable(Inst))
2813 Arg = GetObjCArg(Inst);
2815 PtrState &S = MyStates.getPtrTopDownState(Arg);
2817 // Don't do retain+release tracking for IC_RetainRV, because it's
2818 // better to let it remain as the first instruction after a call.
2819 if (Class != IC_RetainRV) {
2820 // If we see two retains in a row on the same pointer. If so, make
2821 // a note, and we'll cicle back to revisit it after we've
2822 // hopefully eliminated the second retain, which may allow us to
2823 // eliminate the first retain too.
2824 // Theoretically we could implement removal of nested retain+release
2825 // pairs by making PtrState hold a stack of states, but this is
2826 // simple and avoids adding overhead for the non-nested case.
2827 if (S.GetSeq() == S_Retain)
2828 NestingDetected = true;
2830 S.ResetSequenceProgress(S_Retain);
2831 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2832 S.RRI.KnownSafe = S.IsKnownIncremented();
2833 S.RRI.Calls.insert(Inst);
2836 S.SetKnownPositiveRefCount();
2838 // A retain can be a potential use; procede to the generic checking
2843 Arg = GetObjCArg(Inst);
2845 PtrState &S = MyStates.getPtrTopDownState(Arg);
2848 switch (S.GetSeq()) {
2851 S.RRI.ReverseInsertPts.clear();
2854 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2855 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2856 Releases[Inst] = S.RRI;
2857 S.ClearSequenceProgress();
2863 case S_MovableRelease:
2864 llvm_unreachable("top-down pointer in release state!");
2868 case IC_AutoreleasepoolPop:
2869 // Conservatively, clear MyStates for all known pointers.
2870 MyStates.clearTopDownPointers();
2871 return NestingDetected;
2872 case IC_AutoreleasepoolPush:
2874 // These are irrelevant.
2875 return NestingDetected;
2880 // Consider any other possible effects of this instruction on each
2881 // pointer being tracked.
2882 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2883 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2884 const Value *Ptr = MI->first;
2886 continue; // Handled above.
2887 PtrState &S = MI->second;
2888 Sequence Seq = S.GetSeq();
2890 // Check for possible releases.
2891 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2895 S.SetSeq(S_CanRelease);
2896 assert(S.RRI.ReverseInsertPts.empty());
2897 S.RRI.ReverseInsertPts.insert(Inst);
2899 // One call can't cause a transition from S_Retain to S_CanRelease
2900 // and S_CanRelease to S_Use. If we've made the first transition,
2909 case S_MovableRelease:
2910 llvm_unreachable("top-down pointer in release state!");
2914 // Check for possible direct uses.
2917 if (CanUse(Inst, Ptr, PA, Class))
2926 case S_MovableRelease:
2927 llvm_unreachable("top-down pointer in release state!");
2931 return NestingDetected;
2935 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2936 DenseMap<const BasicBlock *, BBState> &BBStates,
2937 DenseMap<Value *, RRInfo> &Releases) {
2938 bool NestingDetected = false;
2939 BBState &MyStates = BBStates[BB];
2941 // Merge the states from each predecessor to compute the initial state
2942 // for the current block.
2943 BBState::edge_iterator PI(MyStates.pred_begin()),
2944 PE(MyStates.pred_end());
2946 const BasicBlock *Pred = *PI;
2947 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2948 assert(I != BBStates.end());
2949 MyStates.InitFromPred(I->second);
2951 for (; PI != PE; ++PI) {
2953 I = BBStates.find(Pred);
2954 assert(I != BBStates.end());
2955 MyStates.MergePred(I->second);
2959 // Visit all the instructions, top-down.
2960 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2961 Instruction *Inst = I;
2962 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
2965 CheckForCFGHazards(BB, BBStates, MyStates);
2966 return NestingDetected;
2970 ComputePostOrders(Function &F,
2971 SmallVectorImpl<BasicBlock *> &PostOrder,
2972 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2973 unsigned NoObjCARCExceptionsMDKind,
2974 DenseMap<const BasicBlock *, BBState> &BBStates) {
2975 /// Visited - The visited set, for doing DFS walks.
2976 SmallPtrSet<BasicBlock *, 16> Visited;
2978 // Do DFS, computing the PostOrder.
2979 SmallPtrSet<BasicBlock *, 16> OnStack;
2980 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2982 // Functions always have exactly one entry block, and we don't have
2983 // any other block that we treat like an entry block.
2984 BasicBlock *EntryBB = &F.getEntryBlock();
2985 BBState &MyStates = BBStates[EntryBB];
2986 MyStates.SetAsEntry();
2987 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
2988 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
2989 Visited.insert(EntryBB);
2990 OnStack.insert(EntryBB);
2993 BasicBlock *CurrBB = SuccStack.back().first;
2994 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
2995 succ_iterator SE(TI, false);
2997 // If the terminator is an invoke marked with the
2998 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2999 // ignored, for ARC purposes.
3000 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
3003 while (SuccStack.back().second != SE) {
3004 BasicBlock *SuccBB = *SuccStack.back().second++;
3005 if (Visited.insert(SuccBB)) {
3006 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3007 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
3008 BBStates[CurrBB].addSucc(SuccBB);
3009 BBState &SuccStates = BBStates[SuccBB];
3010 SuccStates.addPred(CurrBB);
3011 OnStack.insert(SuccBB);
3015 if (!OnStack.count(SuccBB)) {
3016 BBStates[CurrBB].addSucc(SuccBB);
3017 BBStates[SuccBB].addPred(CurrBB);
3020 OnStack.erase(CurrBB);
3021 PostOrder.push_back(CurrBB);
3022 SuccStack.pop_back();
3023 } while (!SuccStack.empty());
3027 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
3028 // Functions may have many exits, and there also blocks which we treat
3029 // as exits due to ignored edges.
3030 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3031 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3032 BasicBlock *ExitBB = I;
3033 BBState &MyStates = BBStates[ExitBB];
3034 if (!MyStates.isExit())
3037 MyStates.SetAsExit();
3039 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
3040 Visited.insert(ExitBB);
3041 while (!PredStack.empty()) {
3042 reverse_dfs_next_succ:
3043 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3044 while (PredStack.back().second != PE) {
3045 BasicBlock *BB = *PredStack.back().second++;
3046 if (Visited.insert(BB)) {
3047 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
3048 goto reverse_dfs_next_succ;
3051 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3056 // Visit - Visit the function both top-down and bottom-up.
3058 ObjCARCOpt::Visit(Function &F,
3059 DenseMap<const BasicBlock *, BBState> &BBStates,
3060 MapVector<Value *, RRInfo> &Retains,
3061 DenseMap<Value *, RRInfo> &Releases) {
3063 // Use reverse-postorder traversals, because we magically know that loops
3064 // will be well behaved, i.e. they won't repeatedly call retain on a single
3065 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3066 // class here because we want the reverse-CFG postorder to consider each
3067 // function exit point, and we want to ignore selected cycle edges.
3068 SmallVector<BasicBlock *, 16> PostOrder;
3069 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
3070 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3071 NoObjCARCExceptionsMDKind,
3074 // Use reverse-postorder on the reverse CFG for bottom-up.
3075 bool BottomUpNestingDetected = false;
3076 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3077 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3079 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
3081 // Use reverse-postorder for top-down.
3082 bool TopDownNestingDetected = false;
3083 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3084 PostOrder.rbegin(), E = PostOrder.rend();
3086 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
3088 return TopDownNestingDetected && BottomUpNestingDetected;
3091 /// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
3092 void ObjCARCOpt::MoveCalls(Value *Arg,
3093 RRInfo &RetainsToMove,
3094 RRInfo &ReleasesToMove,
3095 MapVector<Value *, RRInfo> &Retains,
3096 DenseMap<Value *, RRInfo> &Releases,
3097 SmallVectorImpl<Instruction *> &DeadInsts,
3099 Type *ArgTy = Arg->getType();
3100 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
3102 // Insert the new retain and release calls.
3103 for (SmallPtrSet<Instruction *, 2>::const_iterator
3104 PI = ReleasesToMove.ReverseInsertPts.begin(),
3105 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3106 Instruction *InsertPt = *PI;
3107 Value *MyArg = ArgTy == ParamTy ? Arg :
3108 new BitCastInst(Arg, ParamTy, "", InsertPt);
3110 CallInst::Create(RetainsToMove.IsRetainBlock ?
3111 getRetainBlockCallee(M) : getRetainCallee(M),
3112 MyArg, "", InsertPt);
3113 Call->setDoesNotThrow();
3114 if (RetainsToMove.IsRetainBlock)
3115 Call->setMetadata(CopyOnEscapeMDKind,
3116 MDNode::get(M->getContext(), ArrayRef<Value *>()));
3118 Call->setTailCall();
3120 for (SmallPtrSet<Instruction *, 2>::const_iterator
3121 PI = RetainsToMove.ReverseInsertPts.begin(),
3122 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3123 Instruction *InsertPt = *PI;
3124 Value *MyArg = ArgTy == ParamTy ? Arg :
3125 new BitCastInst(Arg, ParamTy, "", InsertPt);
3126 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3128 // Attach a clang.imprecise_release metadata tag, if appropriate.
3129 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3130 Call->setMetadata(ImpreciseReleaseMDKind, M);
3131 Call->setDoesNotThrow();
3132 if (ReleasesToMove.IsTailCallRelease)
3133 Call->setTailCall();
3136 // Delete the original retain and release calls.
3137 for (SmallPtrSet<Instruction *, 2>::const_iterator
3138 AI = RetainsToMove.Calls.begin(),
3139 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3140 Instruction *OrigRetain = *AI;
3141 Retains.blot(OrigRetain);
3142 DeadInsts.push_back(OrigRetain);
3144 for (SmallPtrSet<Instruction *, 2>::const_iterator
3145 AI = ReleasesToMove.Calls.begin(),
3146 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3147 Instruction *OrigRelease = *AI;
3148 Releases.erase(OrigRelease);
3149 DeadInsts.push_back(OrigRelease);
3153 /// PerformCodePlacement - Identify pairings between the retains and releases,
3154 /// and delete and/or move them.
3156 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3158 MapVector<Value *, RRInfo> &Retains,
3159 DenseMap<Value *, RRInfo> &Releases,
3161 bool AnyPairsCompletelyEliminated = false;
3162 RRInfo RetainsToMove;
3163 RRInfo ReleasesToMove;
3164 SmallVector<Instruction *, 4> NewRetains;
3165 SmallVector<Instruction *, 4> NewReleases;
3166 SmallVector<Instruction *, 8> DeadInsts;
3168 // Visit each retain.
3169 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
3170 E = Retains.end(); I != E; ++I) {
3171 Value *V = I->first;
3172 if (!V) continue; // blotted
3174 Instruction *Retain = cast<Instruction>(V);
3175 Value *Arg = GetObjCArg(Retain);
3177 // If the object being released is in static or stack storage, we know it's
3178 // not being managed by ObjC reference counting, so we can delete pairs
3179 // regardless of what possible decrements or uses lie between them.
3180 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
3182 // A constant pointer can't be pointing to an object on the heap. It may
3183 // be reference-counted, but it won't be deleted.
3184 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3185 if (const GlobalVariable *GV =
3186 dyn_cast<GlobalVariable>(
3187 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3188 if (GV->isConstant())
3191 // If a pair happens in a region where it is known that the reference count
3192 // is already incremented, we can similarly ignore possible decrements.
3193 bool KnownSafeTD = true, KnownSafeBU = true;
3195 // Connect the dots between the top-down-collected RetainsToMove and
3196 // bottom-up-collected ReleasesToMove to form sets of related calls.
3197 // This is an iterative process so that we connect multiple releases
3198 // to multiple retains if needed.
3199 unsigned OldDelta = 0;
3200 unsigned NewDelta = 0;
3201 unsigned OldCount = 0;
3202 unsigned NewCount = 0;
3203 bool FirstRelease = true;
3204 bool FirstRetain = true;
3205 NewRetains.push_back(Retain);
3207 for (SmallVectorImpl<Instruction *>::const_iterator
3208 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3209 Instruction *NewRetain = *NI;
3210 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3211 assert(It != Retains.end());
3212 const RRInfo &NewRetainRRI = It->second;
3213 KnownSafeTD &= NewRetainRRI.KnownSafe;
3214 for (SmallPtrSet<Instruction *, 2>::const_iterator
3215 LI = NewRetainRRI.Calls.begin(),
3216 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3217 Instruction *NewRetainRelease = *LI;
3218 DenseMap<Value *, RRInfo>::const_iterator Jt =
3219 Releases.find(NewRetainRelease);
3220 if (Jt == Releases.end())
3222 const RRInfo &NewRetainReleaseRRI = Jt->second;
3223 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3224 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3226 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3228 // Merge the ReleaseMetadata and IsTailCallRelease values.
3230 ReleasesToMove.ReleaseMetadata =
3231 NewRetainReleaseRRI.ReleaseMetadata;
3232 ReleasesToMove.IsTailCallRelease =
3233 NewRetainReleaseRRI.IsTailCallRelease;
3234 FirstRelease = false;
3236 if (ReleasesToMove.ReleaseMetadata !=
3237 NewRetainReleaseRRI.ReleaseMetadata)
3238 ReleasesToMove.ReleaseMetadata = 0;
3239 if (ReleasesToMove.IsTailCallRelease !=
3240 NewRetainReleaseRRI.IsTailCallRelease)
3241 ReleasesToMove.IsTailCallRelease = false;
3244 // Collect the optimal insertion points.
3246 for (SmallPtrSet<Instruction *, 2>::const_iterator
3247 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3248 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3250 Instruction *RIP = *RI;
3251 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3252 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3254 NewReleases.push_back(NewRetainRelease);
3259 if (NewReleases.empty()) break;
3261 // Back the other way.
3262 for (SmallVectorImpl<Instruction *>::const_iterator
3263 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3264 Instruction *NewRelease = *NI;
3265 DenseMap<Value *, RRInfo>::const_iterator It =
3266 Releases.find(NewRelease);
3267 assert(It != Releases.end());
3268 const RRInfo &NewReleaseRRI = It->second;
3269 KnownSafeBU &= NewReleaseRRI.KnownSafe;
3270 for (SmallPtrSet<Instruction *, 2>::const_iterator
3271 LI = NewReleaseRRI.Calls.begin(),
3272 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3273 Instruction *NewReleaseRetain = *LI;
3274 MapVector<Value *, RRInfo>::const_iterator Jt =
3275 Retains.find(NewReleaseRetain);
3276 if (Jt == Retains.end())
3278 const RRInfo &NewReleaseRetainRRI = Jt->second;
3279 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3280 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3281 unsigned PathCount =
3282 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3283 OldDelta += PathCount;
3284 OldCount += PathCount;
3286 // Merge the IsRetainBlock values.
3288 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3289 FirstRetain = false;
3290 } else if (ReleasesToMove.IsRetainBlock !=
3291 NewReleaseRetainRRI.IsRetainBlock)
3292 // It's not possible to merge the sequences if one uses
3293 // objc_retain and the other uses objc_retainBlock.
3296 // Collect the optimal insertion points.
3298 for (SmallPtrSet<Instruction *, 2>::const_iterator
3299 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3300 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3302 Instruction *RIP = *RI;
3303 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3304 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3305 NewDelta += PathCount;
3306 NewCount += PathCount;
3309 NewRetains.push_back(NewReleaseRetain);
3313 NewReleases.clear();
3314 if (NewRetains.empty()) break;
3317 // If the pointer is known incremented or nested, we can safely delete the
3318 // pair regardless of what's between them.
3319 if (KnownSafeTD || KnownSafeBU) {
3320 RetainsToMove.ReverseInsertPts.clear();
3321 ReleasesToMove.ReverseInsertPts.clear();
3324 // Determine whether the new insertion points we computed preserve the
3325 // balance of retain and release calls through the program.
3326 // TODO: If the fully aggressive solution isn't valid, try to find a
3327 // less aggressive solution which is.
3332 // Determine whether the original call points are balanced in the retain and
3333 // release calls through the program. If not, conservatively don't touch
3335 // TODO: It's theoretically possible to do code motion in this case, as
3336 // long as the existing imbalances are maintained.
3340 // Ok, everything checks out and we're all set. Let's move some code!
3342 assert(OldCount != 0 && "Unreachable code?");
3343 AnyPairsCompletelyEliminated = NewCount == 0;
3344 NumRRs += OldCount - NewCount;
3345 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3346 Retains, Releases, DeadInsts, M);
3349 NewReleases.clear();
3351 RetainsToMove.clear();
3352 ReleasesToMove.clear();
3355 // Now that we're done moving everything, we can delete the newly dead
3356 // instructions, as we no longer need them as insert points.
3357 while (!DeadInsts.empty())
3358 EraseInstruction(DeadInsts.pop_back_val());
3360 return AnyPairsCompletelyEliminated;
3363 /// OptimizeWeakCalls - Weak pointer optimizations.
3364 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3365 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3366 // itself because it uses AliasAnalysis and we need to do provenance
3368 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3369 Instruction *Inst = &*I++;
3370 InstructionClass Class = GetBasicInstructionClass(Inst);
3371 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3374 // Delete objc_loadWeak calls with no users.
3375 if (Class == IC_LoadWeak && Inst->use_empty()) {
3376 Inst->eraseFromParent();
3380 // TODO: For now, just look for an earlier available version of this value
3381 // within the same block. Theoretically, we could do memdep-style non-local
3382 // analysis too, but that would want caching. A better approach would be to
3383 // use the technique that EarlyCSE uses.
3384 inst_iterator Current = llvm::prior(I);
3385 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3386 for (BasicBlock::iterator B = CurrentBB->begin(),
3387 J = Current.getInstructionIterator();
3389 Instruction *EarlierInst = &*llvm::prior(J);
3390 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3391 switch (EarlierClass) {
3393 case IC_LoadWeakRetained: {
3394 // If this is loading from the same pointer, replace this load's value
3396 CallInst *Call = cast<CallInst>(Inst);
3397 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3398 Value *Arg = Call->getArgOperand(0);
3399 Value *EarlierArg = EarlierCall->getArgOperand(0);
3400 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3401 case AliasAnalysis::MustAlias:
3403 // If the load has a builtin retain, insert a plain retain for it.
3404 if (Class == IC_LoadWeakRetained) {
3406 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3410 // Zap the fully redundant load.
3411 Call->replaceAllUsesWith(EarlierCall);
3412 Call->eraseFromParent();
3414 case AliasAnalysis::MayAlias:
3415 case AliasAnalysis::PartialAlias:
3417 case AliasAnalysis::NoAlias:
3424 // If this is storing to the same pointer and has the same size etc.
3425 // replace this load's value with the stored value.
3426 CallInst *Call = cast<CallInst>(Inst);
3427 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3428 Value *Arg = Call->getArgOperand(0);
3429 Value *EarlierArg = EarlierCall->getArgOperand(0);
3430 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3431 case AliasAnalysis::MustAlias:
3433 // If the load has a builtin retain, insert a plain retain for it.
3434 if (Class == IC_LoadWeakRetained) {
3436 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3440 // Zap the fully redundant load.
3441 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3442 Call->eraseFromParent();
3444 case AliasAnalysis::MayAlias:
3445 case AliasAnalysis::PartialAlias:
3447 case AliasAnalysis::NoAlias:
3454 // TOOD: Grab the copied value.
3456 case IC_AutoreleasepoolPush:
3459 // Weak pointers are only modified through the weak entry points
3460 // (and arbitrary calls, which could call the weak entry points).
3463 // Anything else could modify the weak pointer.
3470 // Then, for each destroyWeak with an alloca operand, check to see if
3471 // the alloca and all its users can be zapped.
3472 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3473 Instruction *Inst = &*I++;
3474 InstructionClass Class = GetBasicInstructionClass(Inst);
3475 if (Class != IC_DestroyWeak)
3478 CallInst *Call = cast<CallInst>(Inst);
3479 Value *Arg = Call->getArgOperand(0);
3480 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3481 for (Value::use_iterator UI = Alloca->use_begin(),
3482 UE = Alloca->use_end(); UI != UE; ++UI) {
3483 const Instruction *UserInst = cast<Instruction>(*UI);
3484 switch (GetBasicInstructionClass(UserInst)) {
3487 case IC_DestroyWeak:
3494 for (Value::use_iterator UI = Alloca->use_begin(),
3495 UE = Alloca->use_end(); UI != UE; ) {
3496 CallInst *UserInst = cast<CallInst>(*UI++);
3497 switch (GetBasicInstructionClass(UserInst)) {
3500 // These functions return their second argument.
3501 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3503 case IC_DestroyWeak:
3507 llvm_unreachable("alloca really is used!");
3509 UserInst->eraseFromParent();
3511 Alloca->eraseFromParent();
3517 /// OptimizeSequences - Identify program paths which execute sequences of
3518 /// retains and releases which can be eliminated.
3519 bool ObjCARCOpt::OptimizeSequences(Function &F) {
3520 /// Releases, Retains - These are used to store the results of the main flow
3521 /// analysis. These use Value* as the key instead of Instruction* so that the
3522 /// map stays valid when we get around to rewriting code and calls get
3523 /// replaced by arguments.
3524 DenseMap<Value *, RRInfo> Releases;
3525 MapVector<Value *, RRInfo> Retains;
3527 /// BBStates, This is used during the traversal of the function to track the
3528 /// states for each identified object at each block.
3529 DenseMap<const BasicBlock *, BBState> BBStates;
3531 // Analyze the CFG of the function, and all instructions.
3532 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3535 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3539 /// OptimizeReturns - Look for this pattern:
3541 /// %call = call i8* @something(...)
3542 /// %2 = call i8* @objc_retain(i8* %call)
3543 /// %3 = call i8* @objc_autorelease(i8* %2)
3546 /// And delete the retain and autorelease.
3548 /// Otherwise if it's just this:
3550 /// %3 = call i8* @objc_autorelease(i8* %2)
3553 /// convert the autorelease to autoreleaseRV.
3554 void ObjCARCOpt::OptimizeReturns(Function &F) {
3555 if (!F.getReturnType()->isPointerTy())
3558 SmallPtrSet<Instruction *, 4> DependingInstructions;
3559 SmallPtrSet<const BasicBlock *, 4> Visited;
3560 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3561 BasicBlock *BB = FI;
3562 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3565 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3566 FindDependencies(NeedsPositiveRetainCount, Arg,
3567 BB, Ret, DependingInstructions, Visited, PA);
3568 if (DependingInstructions.size() != 1)
3572 CallInst *Autorelease =
3573 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3576 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3577 if (!IsAutorelease(AutoreleaseClass))
3579 if (GetObjCArg(Autorelease) != Arg)
3582 DependingInstructions.clear();
3585 // Check that there is nothing that can affect the reference
3586 // count between the autorelease and the retain.
3587 FindDependencies(CanChangeRetainCount, Arg,
3588 BB, Autorelease, DependingInstructions, Visited, PA);
3589 if (DependingInstructions.size() != 1)
3594 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3596 // Check that we found a retain with the same argument.
3598 !IsRetain(GetBasicInstructionClass(Retain)) ||
3599 GetObjCArg(Retain) != Arg)
3602 DependingInstructions.clear();
3605 // Convert the autorelease to an autoreleaseRV, since it's
3606 // returning the value.
3607 if (AutoreleaseClass == IC_Autorelease) {
3608 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3609 AutoreleaseClass = IC_AutoreleaseRV;
3612 // Check that there is nothing that can affect the reference
3613 // count between the retain and the call.
3614 // Note that Retain need not be in BB.
3615 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3616 DependingInstructions, Visited, PA);
3617 if (DependingInstructions.size() != 1)
3622 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3624 // Check that the pointer is the return value of the call.
3625 if (!Call || Arg != Call)
3628 // Check that the call is a regular call.
3629 InstructionClass Class = GetBasicInstructionClass(Call);
3630 if (Class != IC_CallOrUser && Class != IC_Call)
3633 // If so, we can zap the retain and autorelease.
3636 EraseInstruction(Retain);
3637 EraseInstruction(Autorelease);
3643 DependingInstructions.clear();
3648 bool ObjCARCOpt::doInitialization(Module &M) {
3652 // If nothing in the Module uses ARC, don't do anything.
3653 Run = ModuleHasARC(M);
3657 // Identify the imprecise release metadata kind.
3658 ImpreciseReleaseMDKind =
3659 M.getContext().getMDKindID("clang.imprecise_release");
3660 CopyOnEscapeMDKind =
3661 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3662 NoObjCARCExceptionsMDKind =
3663 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3665 // Intuitively, objc_retain and others are nocapture, however in practice
3666 // they are not, because they return their argument value. And objc_release
3667 // calls finalizers which can have arbitrary side effects.
3669 // These are initialized lazily.
3671 AutoreleaseRVCallee = 0;
3674 RetainBlockCallee = 0;
3675 AutoreleaseCallee = 0;
3680 bool ObjCARCOpt::runOnFunction(Function &F) {
3684 // If nothing in the Module uses ARC, don't do anything.
3690 PA.setAA(&getAnalysis<AliasAnalysis>());
3692 // This pass performs several distinct transformations. As a compile-time aid
3693 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3694 // library functions aren't declared.
3696 // Preliminary optimizations. This also computs UsedInThisFunction.
3697 OptimizeIndividualCalls(F);
3699 // Optimizations for weak pointers.
3700 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3701 (1 << IC_LoadWeakRetained) |
3702 (1 << IC_StoreWeak) |
3703 (1 << IC_InitWeak) |
3704 (1 << IC_CopyWeak) |
3705 (1 << IC_MoveWeak) |
3706 (1 << IC_DestroyWeak)))
3707 OptimizeWeakCalls(F);
3709 // Optimizations for retain+release pairs.
3710 if (UsedInThisFunction & ((1 << IC_Retain) |
3711 (1 << IC_RetainRV) |
3712 (1 << IC_RetainBlock)))
3713 if (UsedInThisFunction & (1 << IC_Release))
3714 // Run OptimizeSequences until it either stops making changes or
3715 // no retain+release pair nesting is detected.
3716 while (OptimizeSequences(F)) {}
3718 // Optimizations if objc_autorelease is used.
3719 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3720 (1 << IC_AutoreleaseRV)))
3726 void ObjCARCOpt::releaseMemory() {
3730 //===----------------------------------------------------------------------===//
3732 //===----------------------------------------------------------------------===//
3734 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
3735 // dominated by single calls.
3737 #include "llvm/Operator.h"
3738 #include "llvm/InlineAsm.h"
3739 #include "llvm/Analysis/Dominators.h"
3741 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3744 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3745 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3746 class ObjCARCContract : public FunctionPass {
3750 ProvenanceAnalysis PA;
3752 /// Run - A flag indicating whether this optimization pass should run.
3755 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3756 /// functions, for use in creating calls to them. These are initialized
3757 /// lazily to avoid cluttering up the Module with unused declarations.
3758 Constant *StoreStrongCallee,
3759 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3761 /// RetainRVMarker - The inline asm string to insert between calls and
3762 /// RetainRV calls to make the optimization work on targets which need it.
3763 const MDString *RetainRVMarker;
3765 /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
3766 /// at the end of walking the function we have found no alloca
3767 /// instructions, these calls can be marked "tail".
3768 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
3770 Constant *getStoreStrongCallee(Module *M);
3771 Constant *getRetainAutoreleaseCallee(Module *M);
3772 Constant *getRetainAutoreleaseRVCallee(Module *M);
3774 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3775 InstructionClass Class,
3776 SmallPtrSet<Instruction *, 4>
3777 &DependingInstructions,
3778 SmallPtrSet<const BasicBlock *, 4>
3781 void ContractRelease(Instruction *Release,
3782 inst_iterator &Iter);
3784 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3785 virtual bool doInitialization(Module &M);
3786 virtual bool runOnFunction(Function &F);
3790 ObjCARCContract() : FunctionPass(ID) {
3791 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3796 char ObjCARCContract::ID = 0;
3797 INITIALIZE_PASS_BEGIN(ObjCARCContract,
3798 "objc-arc-contract", "ObjC ARC contraction", false, false)
3799 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3800 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3801 INITIALIZE_PASS_END(ObjCARCContract,
3802 "objc-arc-contract", "ObjC ARC contraction", false, false)
3804 Pass *llvm::createObjCARCContractPass() {
3805 return new ObjCARCContract();
3808 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3809 AU.addRequired<AliasAnalysis>();
3810 AU.addRequired<DominatorTree>();
3811 AU.setPreservesCFG();
3814 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3815 if (!StoreStrongCallee) {
3816 LLVMContext &C = M->getContext();
3817 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3818 Type *I8XX = PointerType::getUnqual(I8X);
3819 Type *Params[] = { I8XX, I8X };
3821 AttrListPtr Attributes = AttrListPtr()
3822 .addAttr(~0u, Attribute::NoUnwind)
3823 .addAttr(1, Attribute::NoCapture);
3826 M->getOrInsertFunction(
3828 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3831 return StoreStrongCallee;
3834 Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3835 if (!RetainAutoreleaseCallee) {
3836 LLVMContext &C = M->getContext();
3837 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3838 Type *Params[] = { I8X };
3839 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
3840 AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
3841 RetainAutoreleaseCallee =
3842 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3844 return RetainAutoreleaseCallee;
3847 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3848 if (!RetainAutoreleaseRVCallee) {
3849 LLVMContext &C = M->getContext();
3850 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3851 Type *Params[] = { I8X };
3852 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
3853 AttrListPtr Attributes = AttrListPtr().addAttr(~0u, Attribute::NoUnwind);
3854 RetainAutoreleaseRVCallee =
3855 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3858 return RetainAutoreleaseRVCallee;
3861 /// ContractAutorelease - Merge an autorelease with a retain into a fused call.
3863 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3864 InstructionClass Class,
3865 SmallPtrSet<Instruction *, 4>
3866 &DependingInstructions,
3867 SmallPtrSet<const BasicBlock *, 4>
3869 const Value *Arg = GetObjCArg(Autorelease);
3871 // Check that there are no instructions between the retain and the autorelease
3872 // (such as an autorelease_pop) which may change the count.
3873 CallInst *Retain = 0;
3874 if (Class == IC_AutoreleaseRV)
3875 FindDependencies(RetainAutoreleaseRVDep, Arg,
3876 Autorelease->getParent(), Autorelease,
3877 DependingInstructions, Visited, PA);
3879 FindDependencies(RetainAutoreleaseDep, Arg,
3880 Autorelease->getParent(), Autorelease,
3881 DependingInstructions, Visited, PA);
3884 if (DependingInstructions.size() != 1) {
3885 DependingInstructions.clear();
3889 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3890 DependingInstructions.clear();
3893 GetBasicInstructionClass(Retain) != IC_Retain ||
3894 GetObjCArg(Retain) != Arg)
3900 if (Class == IC_AutoreleaseRV)
3901 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3903 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3905 EraseInstruction(Autorelease);
3909 /// ContractRelease - Attempt to merge an objc_release with a store, load, and
3910 /// objc_retain to form an objc_storeStrong. This can be a little tricky because
3911 /// the instructions don't always appear in order, and there may be unrelated
3912 /// intervening instructions.
3913 void ObjCARCContract::ContractRelease(Instruction *Release,
3914 inst_iterator &Iter) {
3915 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
3916 if (!Load || !Load->isSimple()) return;
3918 // For now, require everything to be in one basic block.
3919 BasicBlock *BB = Release->getParent();
3920 if (Load->getParent() != BB) return;
3922 // Walk down to find the store and the release, which may be in either order.
3923 BasicBlock::iterator I = Load, End = BB->end();
3925 AliasAnalysis::Location Loc = AA->getLocation(Load);
3926 StoreInst *Store = 0;
3927 bool SawRelease = false;
3928 for (; !Store || !SawRelease; ++I) {
3932 Instruction *Inst = I;
3933 if (Inst == Release) {
3938 InstructionClass Class = GetBasicInstructionClass(Inst);
3940 // Unrelated retains are harmless.
3941 if (IsRetain(Class))
3945 // The store is the point where we're going to put the objc_storeStrong,
3946 // so make sure there are no uses after it.
3947 if (CanUse(Inst, Load, PA, Class))
3949 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
3950 // We are moving the load down to the store, so check for anything
3951 // else which writes to the memory between the load and the store.
3952 Store = dyn_cast<StoreInst>(Inst);
3953 if (!Store || !Store->isSimple()) return;
3954 if (Store->getPointerOperand() != Loc.Ptr) return;
3958 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3960 // Walk up to find the retain.
3962 BasicBlock::iterator Begin = BB->begin();
3963 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3965 Instruction *Retain = I;
3966 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3967 if (GetObjCArg(Retain) != New) return;
3972 LLVMContext &C = Release->getContext();
3973 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3974 Type *I8XX = PointerType::getUnqual(I8X);
3976 Value *Args[] = { Load->getPointerOperand(), New };
3977 if (Args[0]->getType() != I8XX)
3978 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3979 if (Args[1]->getType() != I8X)
3980 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3981 CallInst *StoreStrong =
3982 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
3984 StoreStrong->setDoesNotThrow();
3985 StoreStrong->setDebugLoc(Store->getDebugLoc());
3987 // We can't set the tail flag yet, because we haven't yet determined
3988 // whether there are any escaping allocas. Remember this call, so that
3989 // we can set the tail flag once we know it's safe.
3990 StoreStrongCalls.insert(StoreStrong);
3992 if (&*Iter == Store) ++Iter;
3993 Store->eraseFromParent();
3994 Release->eraseFromParent();
3995 EraseInstruction(Retain);
3996 if (Load->use_empty())
3997 Load->eraseFromParent();
4000 bool ObjCARCContract::doInitialization(Module &M) {
4001 // If nothing in the Module uses ARC, don't do anything.
4002 Run = ModuleHasARC(M);
4006 // These are initialized lazily.
4007 StoreStrongCallee = 0;
4008 RetainAutoreleaseCallee = 0;
4009 RetainAutoreleaseRVCallee = 0;
4011 // Initialize RetainRVMarker.
4013 if (NamedMDNode *NMD =
4014 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4015 if (NMD->getNumOperands() == 1) {
4016 const MDNode *N = NMD->getOperand(0);
4017 if (N->getNumOperands() == 1)
4018 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4025 bool ObjCARCContract::runOnFunction(Function &F) {
4029 // If nothing in the Module uses ARC, don't do anything.
4034 AA = &getAnalysis<AliasAnalysis>();
4035 DT = &getAnalysis<DominatorTree>();
4037 PA.setAA(&getAnalysis<AliasAnalysis>());
4039 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4040 // keyword. Be conservative if the function has variadic arguments.
4041 // It seems that functions which "return twice" are also unsafe for the
4042 // "tail" argument, because they are setjmp, which could need to
4043 // return to an earlier stack state.
4044 bool TailOkForStoreStrongs = !F.isVarArg() &&
4045 !F.callsFunctionThatReturnsTwice();
4047 // For ObjC library calls which return their argument, replace uses of the
4048 // argument with uses of the call return value, if it dominates the use. This
4049 // reduces register pressure.
4050 SmallPtrSet<Instruction *, 4> DependingInstructions;
4051 SmallPtrSet<const BasicBlock *, 4> Visited;
4052 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4053 Instruction *Inst = &*I++;
4055 // Only these library routines return their argument. In particular,
4056 // objc_retainBlock does not necessarily return its argument.
4057 InstructionClass Class = GetBasicInstructionClass(Inst);
4060 case IC_FusedRetainAutorelease:
4061 case IC_FusedRetainAutoreleaseRV:
4063 case IC_Autorelease:
4064 case IC_AutoreleaseRV:
4065 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4069 // If we're compiling for a target which needs a special inline-asm
4070 // marker to do the retainAutoreleasedReturnValue optimization,
4072 if (!RetainRVMarker)
4074 BasicBlock::iterator BBI = Inst;
4075 BasicBlock *InstParent = Inst->getParent();
4077 // Step up to see if the call immediately precedes the RetainRV call.
4078 // If it's an invoke, we have to cross a block boundary. And we have
4079 // to carefully dodge no-op instructions.
4081 if (&*BBI == InstParent->begin()) {
4082 BasicBlock *Pred = InstParent->getSinglePredecessor();
4084 goto decline_rv_optimization;
4085 BBI = Pred->getTerminator();
4089 } while (isNoopInstruction(BBI));
4091 if (&*BBI == GetObjCArg(Inst)) {
4094 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4095 /*isVarArg=*/false),
4096 RetainRVMarker->getString(),
4097 /*Constraints=*/"", /*hasSideEffects=*/true);
4098 CallInst::Create(IA, "", Inst);
4100 decline_rv_optimization:
4104 // objc_initWeak(p, null) => *p = null
4105 CallInst *CI = cast<CallInst>(Inst);
4106 if (isNullOrUndef(CI->getArgOperand(1))) {
4108 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4110 new StoreInst(Null, CI->getArgOperand(0), CI);
4111 CI->replaceAllUsesWith(Null);
4112 CI->eraseFromParent();
4117 ContractRelease(Inst, I);
4120 // Be conservative if the function has any alloca instructions.
4121 // Technically we only care about escaping alloca instructions,
4122 // but this is sufficient to handle some interesting cases.
4123 if (isa<AllocaInst>(Inst))
4124 TailOkForStoreStrongs = false;
4130 // Don't use GetObjCArg because we don't want to look through bitcasts
4131 // and such; to do the replacement, the argument must have type i8*.
4132 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4134 // If we're compiling bugpointed code, don't get in trouble.
4135 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4137 // Look through the uses of the pointer.
4138 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4140 Use &U = UI.getUse();
4141 unsigned OperandNo = UI.getOperandNo();
4142 ++UI; // Increment UI now, because we may unlink its element.
4144 // If the call's return value dominates a use of the call's argument
4145 // value, rewrite the use to use the return value. We check for
4146 // reachability here because an unreachable call is considered to
4147 // trivially dominate itself, which would lead us to rewriting its
4148 // argument in terms of its return value, which would lead to
4149 // infinite loops in GetObjCArg.
4150 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
4152 Instruction *Replacement = Inst;
4153 Type *UseTy = U.get()->getType();
4154 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
4155 // For PHI nodes, insert the bitcast in the predecessor block.
4156 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4157 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
4158 if (Replacement->getType() != UseTy)
4159 Replacement = new BitCastInst(Replacement, UseTy, "",
4161 // While we're here, rewrite all edges for this PHI, rather
4162 // than just one use at a time, to minimize the number of
4163 // bitcasts we emit.
4164 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4165 if (PHI->getIncomingBlock(i) == BB) {
4166 // Keep the UI iterator valid.
4167 if (&PHI->getOperandUse(
4168 PHINode::getOperandNumForIncomingValue(i)) ==
4171 PHI->setIncomingValue(i, Replacement);
4174 if (Replacement->getType() != UseTy)
4175 Replacement = new BitCastInst(Replacement, UseTy, "",
4176 cast<Instruction>(U.getUser()));
4182 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
4183 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4184 Arg = BI->getOperand(0);
4185 else if (isa<GEPOperator>(Arg) &&
4186 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4187 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4188 else if (isa<GlobalAlias>(Arg) &&
4189 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4190 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4196 // If this function has no escaping allocas or suspicious vararg usage,
4197 // objc_storeStrong calls can be marked with the "tail" keyword.
4198 if (TailOkForStoreStrongs)
4199 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
4200 E = StoreStrongCalls.end(); I != E; ++I)
4201 (*I)->setTailCall();
4202 StoreStrongCalls.clear();