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 knowedge 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/Function.h"
33 #include "llvm/Intrinsics.h"
34 #include "llvm/GlobalVariable.h"
35 #include "llvm/DerivedTypes.h"
36 #include "llvm/Module.h"
37 #include "llvm/Analysis/ValueTracking.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 #include "llvm/Support/CallSite.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/ADT/StringSwitch.h"
42 #include "llvm/ADT/DenseMap.h"
43 #include "llvm/ADT/STLExtras.h"
46 // A handy option to enable/disable all optimizations in this file.
47 static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
49 //===----------------------------------------------------------------------===//
51 //===----------------------------------------------------------------------===//
54 /// MapVector - An associative container with fast insertion-order
55 /// (deterministic) iteration over its elements. Plus the special
57 template<class KeyT, class ValueT>
59 /// Map - Map keys to indices in Vector.
60 typedef DenseMap<KeyT, size_t> MapTy;
63 /// Vector - Keys and values.
64 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
68 typedef typename VectorTy::iterator iterator;
69 typedef typename VectorTy::const_iterator const_iterator;
70 iterator begin() { return Vector.begin(); }
71 iterator end() { return Vector.end(); }
72 const_iterator begin() const { return Vector.begin(); }
73 const_iterator end() const { return Vector.end(); }
77 assert(Vector.size() >= Map.size()); // May differ due to blotting.
78 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
80 assert(I->second < Vector.size());
81 assert(Vector[I->second].first == I->first);
83 for (typename VectorTy::const_iterator I = Vector.begin(),
84 E = Vector.end(); I != E; ++I)
86 (Map.count(I->first) &&
87 Map[I->first] == size_t(I - Vector.begin())));
91 ValueT &operator[](const KeyT &Arg) {
92 std::pair<typename MapTy::iterator, bool> Pair =
93 Map.insert(std::make_pair(Arg, size_t(0)));
95 size_t Num = Vector.size();
96 Pair.first->second = Num;
97 Vector.push_back(std::make_pair(Arg, ValueT()));
98 return Vector[Num].second;
100 return Vector[Pair.first->second].second;
103 std::pair<iterator, bool>
104 insert(const std::pair<KeyT, ValueT> &InsertPair) {
105 std::pair<typename MapTy::iterator, bool> Pair =
106 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
108 size_t Num = Vector.size();
109 Pair.first->second = Num;
110 Vector.push_back(InsertPair);
111 return std::make_pair(Vector.begin() + Num, true);
113 return std::make_pair(Vector.begin() + Pair.first->second, false);
116 const_iterator find(const KeyT &Key) const {
117 typename MapTy::const_iterator It = Map.find(Key);
118 if (It == Map.end()) return Vector.end();
119 return Vector.begin() + It->second;
122 /// blot - This is similar to erase, but instead of removing the element
123 /// from the vector, it just zeros out the key in the vector. This leaves
124 /// iterators intact, but clients must be prepared for zeroed-out keys when
126 void blot(const KeyT &Key) {
127 typename MapTy::iterator It = Map.find(Key);
128 if (It == Map.end()) return;
129 Vector[It->second].first = KeyT();
140 //===----------------------------------------------------------------------===//
142 //===----------------------------------------------------------------------===//
145 /// InstructionClass - A simple classification for instructions.
146 enum InstructionClass {
147 IC_Retain, ///< objc_retain
148 IC_RetainRV, ///< objc_retainAutoreleasedReturnValue
149 IC_RetainBlock, ///< objc_retainBlock
150 IC_Release, ///< objc_release
151 IC_Autorelease, ///< objc_autorelease
152 IC_AutoreleaseRV, ///< objc_autoreleaseReturnValue
153 IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
154 IC_AutoreleasepoolPop, ///< objc_autoreleasePoolPop
155 IC_NoopCast, ///< objc_retainedObject, etc.
156 IC_FusedRetainAutorelease, ///< objc_retainAutorelease
157 IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
158 IC_LoadWeakRetained, ///< objc_loadWeakRetained (primitive)
159 IC_StoreWeak, ///< objc_storeWeak (primitive)
160 IC_InitWeak, ///< objc_initWeak (derived)
161 IC_LoadWeak, ///< objc_loadWeak (derived)
162 IC_MoveWeak, ///< objc_moveWeak (derived)
163 IC_CopyWeak, ///< objc_copyWeak (derived)
164 IC_DestroyWeak, ///< objc_destroyWeak (derived)
165 IC_StoreStrong, ///< objc_storeStrong (derived)
166 IC_CallOrUser, ///< could call objc_release and/or "use" pointers
167 IC_Call, ///< could call objc_release
168 IC_User, ///< could "use" a pointer
169 IC_None ///< anything else
173 /// IsPotentialUse - Test whether the given value is possible a
174 /// reference-counted pointer.
175 static bool IsPotentialUse(const Value *Op) {
176 // Pointers to static or stack storage are not reference-counted pointers.
177 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
179 // Special arguments are not reference-counted.
180 if (const Argument *Arg = dyn_cast<Argument>(Op))
181 if (Arg->hasByValAttr() ||
182 Arg->hasNestAttr() ||
183 Arg->hasStructRetAttr())
185 // Only consider values with pointer types.
186 // It seemes intuitive to exclude function pointer types as well, since
187 // functions are never reference-counted, however clang occasionally
188 // bitcasts reference-counted pointers to function-pointer type
190 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
193 // Conservatively assume anything else is a potential use.
197 /// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind
198 /// of construct CS is.
199 static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
200 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
202 if (IsPotentialUse(*I))
203 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
205 return CS.onlyReadsMemory() ? IC_None : IC_Call;
208 /// GetFunctionClass - Determine if F is one of the special known Functions.
209 /// If it isn't, return IC_CallOrUser.
210 static InstructionClass GetFunctionClass(const Function *F) {
211 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
215 return StringSwitch<InstructionClass>(F->getName())
216 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
217 .Default(IC_CallOrUser);
220 const Argument *A0 = AI++;
222 // Argument is a pointer.
223 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
224 Type *ETy = PTy->getElementType();
226 if (ETy->isIntegerTy(8))
227 return StringSwitch<InstructionClass>(F->getName())
228 .Case("objc_retain", IC_Retain)
229 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
230 .Case("objc_retainBlock", IC_RetainBlock)
231 .Case("objc_release", IC_Release)
232 .Case("objc_autorelease", IC_Autorelease)
233 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
234 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
235 .Case("objc_retainedObject", IC_NoopCast)
236 .Case("objc_unretainedObject", IC_NoopCast)
237 .Case("objc_unretainedPointer", IC_NoopCast)
238 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
239 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
240 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
241 .Default(IC_CallOrUser);
244 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
245 if (Pte->getElementType()->isIntegerTy(8))
246 return StringSwitch<InstructionClass>(F->getName())
247 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
248 .Case("objc_loadWeak", IC_LoadWeak)
249 .Case("objc_destroyWeak", IC_DestroyWeak)
250 .Default(IC_CallOrUser);
253 // Two arguments, first is i8**.
254 const Argument *A1 = AI++;
256 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
257 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
258 if (Pte->getElementType()->isIntegerTy(8))
259 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
260 Type *ETy1 = PTy1->getElementType();
261 // Second argument is i8*
262 if (ETy1->isIntegerTy(8))
263 return StringSwitch<InstructionClass>(F->getName())
264 .Case("objc_storeWeak", IC_StoreWeak)
265 .Case("objc_initWeak", IC_InitWeak)
266 .Case("objc_storeStrong", IC_StoreStrong)
267 .Default(IC_CallOrUser);
268 // Second argument is i8**.
269 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
270 if (Pte1->getElementType()->isIntegerTy(8))
271 return StringSwitch<InstructionClass>(F->getName())
272 .Case("objc_moveWeak", IC_MoveWeak)
273 .Case("objc_copyWeak", IC_CopyWeak)
274 .Default(IC_CallOrUser);
278 return IC_CallOrUser;
281 /// GetInstructionClass - Determine what kind of construct V is.
282 static InstructionClass GetInstructionClass(const Value *V) {
283 if (const Instruction *I = dyn_cast<Instruction>(V)) {
284 // Any instruction other than bitcast and gep with a pointer operand have a
285 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
286 // to a subsequent use, rather than using it themselves, in this sense.
287 // As a short cut, several other opcodes are known to have no pointer
288 // operands of interest. And ret is never followed by a release, so it's
289 // not interesting to examine.
290 switch (I->getOpcode()) {
291 case Instruction::Call: {
292 const CallInst *CI = cast<CallInst>(I);
293 // Check for calls to special functions.
294 if (const Function *F = CI->getCalledFunction()) {
295 InstructionClass Class = GetFunctionClass(F);
296 if (Class != IC_CallOrUser)
299 // None of the intrinsic functions do objc_release. For intrinsics, the
300 // only question is whether or not they may be users.
301 switch (F->getIntrinsicID()) {
303 case Intrinsic::bswap: case Intrinsic::ctpop:
304 case Intrinsic::ctlz: case Intrinsic::cttz:
305 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
306 case Intrinsic::stacksave: case Intrinsic::stackrestore:
307 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
308 // Don't let dbg info affect our results.
309 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
310 // Short cut: Some intrinsics obviously don't use ObjC pointers.
313 for (Function::const_arg_iterator AI = F->arg_begin(),
314 AE = F->arg_end(); AI != AE; ++AI)
315 if (IsPotentialUse(AI))
320 return GetCallSiteClass(CI);
322 case Instruction::Invoke:
323 return GetCallSiteClass(cast<InvokeInst>(I));
324 case Instruction::BitCast:
325 case Instruction::GetElementPtr:
326 case Instruction::Select: case Instruction::PHI:
327 case Instruction::Ret: case Instruction::Br:
328 case Instruction::Switch: case Instruction::IndirectBr:
329 case Instruction::Alloca: case Instruction::VAArg:
330 case Instruction::Add: case Instruction::FAdd:
331 case Instruction::Sub: case Instruction::FSub:
332 case Instruction::Mul: case Instruction::FMul:
333 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
334 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
335 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
336 case Instruction::And: case Instruction::Or: case Instruction::Xor:
337 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
338 case Instruction::IntToPtr: case Instruction::FCmp:
339 case Instruction::FPTrunc: case Instruction::FPExt:
340 case Instruction::FPToUI: case Instruction::FPToSI:
341 case Instruction::UIToFP: case Instruction::SIToFP:
342 case Instruction::InsertElement: case Instruction::ExtractElement:
343 case Instruction::ShuffleVector:
344 case Instruction::ExtractValue:
346 case Instruction::ICmp:
347 // Comparing a pointer with null, or any other constant, isn't an
348 // interesting use, because we don't care what the pointer points to, or
349 // about the values of any other dynamic reference-counted pointers.
350 if (IsPotentialUse(I->getOperand(1)))
354 // For anything else, check all the operands.
355 // Note that this includes both operands of a Store: while the first
356 // operand isn't actually being dereferenced, it is being stored to
357 // memory where we can no longer track who might read it and dereference
358 // it, so we have to consider it potentially used.
359 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
361 if (IsPotentialUse(*OI))
366 // Otherwise, it's totally inert for ARC purposes.
370 /// GetBasicInstructionClass - Determine what kind of construct V is. This is
371 /// similar to GetInstructionClass except that it only detects objc runtine
372 /// calls. This allows it to be faster.
373 static InstructionClass GetBasicInstructionClass(const Value *V) {
374 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
375 if (const Function *F = CI->getCalledFunction())
376 return GetFunctionClass(F);
377 // Otherwise, be conservative.
378 return IC_CallOrUser;
381 // Otherwise, be conservative.
382 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
385 /// IsRetain - Test if the the given class is objc_retain or
387 static bool IsRetain(InstructionClass Class) {
388 return Class == IC_Retain ||
389 Class == IC_RetainRV;
392 /// IsAutorelease - Test if the the given class is objc_autorelease or
394 static bool IsAutorelease(InstructionClass Class) {
395 return Class == IC_Autorelease ||
396 Class == IC_AutoreleaseRV;
399 /// IsForwarding - Test if the given class represents instructions which return
400 /// their argument verbatim.
401 static bool IsForwarding(InstructionClass Class) {
402 // objc_retainBlock technically doesn't always return its argument
403 // verbatim, but it doesn't matter for our purposes here.
404 return Class == IC_Retain ||
405 Class == IC_RetainRV ||
406 Class == IC_Autorelease ||
407 Class == IC_AutoreleaseRV ||
408 Class == IC_RetainBlock ||
409 Class == IC_NoopCast;
412 /// IsNoopOnNull - Test if the given class represents instructions which do
413 /// nothing if passed a null pointer.
414 static bool IsNoopOnNull(InstructionClass Class) {
415 return Class == IC_Retain ||
416 Class == IC_RetainRV ||
417 Class == IC_Release ||
418 Class == IC_Autorelease ||
419 Class == IC_AutoreleaseRV ||
420 Class == IC_RetainBlock;
423 /// IsAlwaysTail - Test if the given class represents instructions which are
424 /// always safe to mark with the "tail" keyword.
425 static bool IsAlwaysTail(InstructionClass Class) {
426 // IC_RetainBlock may be given a stack argument.
427 return Class == IC_Retain ||
428 Class == IC_RetainRV ||
429 Class == IC_Autorelease ||
430 Class == IC_AutoreleaseRV;
433 /// IsNoThrow - Test if the given class represents instructions which are always
434 /// safe to mark with the nounwind attribute..
435 static bool IsNoThrow(InstructionClass Class) {
436 // objc_retainBlock is not nounwind because it calls user copy constructors
437 // which could theoretically throw.
438 return Class == IC_Retain ||
439 Class == IC_RetainRV ||
440 Class == IC_Release ||
441 Class == IC_Autorelease ||
442 Class == IC_AutoreleaseRV ||
443 Class == IC_AutoreleasepoolPush ||
444 Class == IC_AutoreleasepoolPop;
447 /// EraseInstruction - Erase the given instruction. Many ObjC calls return their
448 /// argument verbatim, so if it's such a call and the return value has users,
449 /// replace them with the argument value.
450 static void EraseInstruction(Instruction *CI) {
451 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
453 bool Unused = CI->use_empty();
456 // Replace the return value with the argument.
457 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
458 "Can't delete non-forwarding instruction with users!");
459 CI->replaceAllUsesWith(OldArg);
462 CI->eraseFromParent();
465 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
468 /// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
469 /// also knows how to look through objc_retain and objc_autorelease calls, which
470 /// we know to return their argument verbatim.
471 static const Value *GetUnderlyingObjCPtr(const Value *V) {
473 V = GetUnderlyingObject(V);
474 if (!IsForwarding(GetBasicInstructionClass(V)))
476 V = cast<CallInst>(V)->getArgOperand(0);
482 /// StripPointerCastsAndObjCCalls - This is a wrapper around
483 /// Value::stripPointerCasts which also knows how to look through objc_retain
484 /// and objc_autorelease calls, which we know to return their argument verbatim.
485 static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
487 V = V->stripPointerCasts();
488 if (!IsForwarding(GetBasicInstructionClass(V)))
490 V = cast<CallInst>(V)->getArgOperand(0);
495 /// StripPointerCastsAndObjCCalls - This is a wrapper around
496 /// Value::stripPointerCasts which also knows how to look through objc_retain
497 /// and objc_autorelease calls, which we know to return their argument verbatim.
498 static Value *StripPointerCastsAndObjCCalls(Value *V) {
500 V = V->stripPointerCasts();
501 if (!IsForwarding(GetBasicInstructionClass(V)))
503 V = cast<CallInst>(V)->getArgOperand(0);
508 /// GetObjCArg - Assuming the given instruction is one of the special calls such
509 /// as objc_retain or objc_release, return the argument value, stripped of no-op
510 /// casts and forwarding calls.
511 static Value *GetObjCArg(Value *Inst) {
512 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
515 /// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
516 /// isObjCIdentifiedObject, except that it uses special knowledge of
517 /// ObjC conventions...
518 static bool IsObjCIdentifiedObject(const Value *V) {
519 // Assume that call results and arguments have their own "provenance".
520 // Constants (including GlobalVariables) and Allocas are never
521 // reference-counted.
522 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
523 isa<Argument>(V) || isa<Constant>(V) ||
527 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
528 const Value *Pointer =
529 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
530 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
531 // A constant pointer can't be pointing to an object on the heap. It may
532 // be reference-counted, but it won't be deleted.
533 if (GV->isConstant())
535 StringRef Name = GV->getName();
536 // These special variables are known to hold values which are not
537 // reference-counted pointers.
538 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
539 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
540 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
541 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
542 Name.startswith("\01l_objc_msgSend_fixup_"))
550 /// FindSingleUseIdentifiedObject - This is similar to
551 /// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
552 /// with multiple uses.
553 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
554 if (Arg->hasOneUse()) {
555 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
556 return FindSingleUseIdentifiedObject(BC->getOperand(0));
557 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
558 if (GEP->hasAllZeroIndices())
559 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
560 if (IsForwarding(GetBasicInstructionClass(Arg)))
561 return FindSingleUseIdentifiedObject(
562 cast<CallInst>(Arg)->getArgOperand(0));
563 if (!IsObjCIdentifiedObject(Arg))
568 // If we found an identifiable object but it has multiple uses, but they
569 // are trivial uses, we can still consider this to be a single-use
571 if (IsObjCIdentifiedObject(Arg)) {
572 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
575 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
585 /// ModuleHasARC - Test if the given module looks interesting to run ARC
587 static bool ModuleHasARC(const Module &M) {
589 M.getNamedValue("objc_retain") ||
590 M.getNamedValue("objc_release") ||
591 M.getNamedValue("objc_autorelease") ||
592 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
593 M.getNamedValue("objc_retainBlock") ||
594 M.getNamedValue("objc_autoreleaseReturnValue") ||
595 M.getNamedValue("objc_autoreleasePoolPush") ||
596 M.getNamedValue("objc_loadWeakRetained") ||
597 M.getNamedValue("objc_loadWeak") ||
598 M.getNamedValue("objc_destroyWeak") ||
599 M.getNamedValue("objc_storeWeak") ||
600 M.getNamedValue("objc_initWeak") ||
601 M.getNamedValue("objc_moveWeak") ||
602 M.getNamedValue("objc_copyWeak") ||
603 M.getNamedValue("objc_retainedObject") ||
604 M.getNamedValue("objc_unretainedObject") ||
605 M.getNamedValue("objc_unretainedPointer");
608 /// DoesObjCBlockEscape - Test whether the given pointer, which is an
609 /// Objective C block pointer, does not "escape". This differs from regular
610 /// escape analysis in that a use as an argument to a call is not considered
612 static bool DoesObjCBlockEscape(const Value *BlockPtr) {
613 // Walk the def-use chains.
614 SmallVector<const Value *, 4> Worklist;
615 Worklist.push_back(BlockPtr);
617 const Value *V = Worklist.pop_back_val();
618 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
620 const User *UUser = *UI;
621 // Special - Use by a call (callee or argument) is not considered
623 switch (GetBasicInstructionClass(UUser)) {
628 case IC_AutoreleaseRV:
629 // These special functions make copies of their pointer arguments.
633 // Use by an instruction which copies the value is an escape if the
634 // result is an escape.
635 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
636 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
637 Worklist.push_back(UUser);
640 // Use by a load is not an escape.
641 if (isa<LoadInst>(UUser))
643 // Use by a store is not an escape if the use is the address.
644 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
645 if (V != SI->getValueOperand())
649 // Regular calls and other stuff are not considered escapes.
652 // Otherwise, conservatively assume an escape.
655 } while (!Worklist.empty());
661 //===----------------------------------------------------------------------===//
662 // ARC AliasAnalysis.
663 //===----------------------------------------------------------------------===//
665 #include "llvm/Pass.h"
666 #include "llvm/Analysis/AliasAnalysis.h"
667 #include "llvm/Analysis/Passes.h"
670 /// ObjCARCAliasAnalysis - This is a simple alias analysis
671 /// implementation that uses knowledge of ARC constructs to answer queries.
673 /// TODO: This class could be generalized to know about other ObjC-specific
674 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
675 /// even though their offsets are dynamic.
676 class ObjCARCAliasAnalysis : public ImmutablePass,
677 public AliasAnalysis {
679 static char ID; // Class identification, replacement for typeinfo
680 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
681 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
685 virtual void initializePass() {
686 InitializeAliasAnalysis(this);
689 /// getAdjustedAnalysisPointer - This method is used when a pass implements
690 /// an analysis interface through multiple inheritance. If needed, it
691 /// should override this to adjust the this pointer as needed for the
692 /// specified pass info.
693 virtual void *getAdjustedAnalysisPointer(const void *PI) {
694 if (PI == &AliasAnalysis::ID)
695 return static_cast<AliasAnalysis *>(this);
699 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
700 virtual AliasResult alias(const Location &LocA, const Location &LocB);
701 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
702 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
703 virtual ModRefBehavior getModRefBehavior(const Function *F);
704 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
705 const Location &Loc);
706 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
707 ImmutableCallSite CS2);
709 } // End of anonymous namespace
711 // Register this pass...
712 char ObjCARCAliasAnalysis::ID = 0;
713 INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
714 "ObjC-ARC-Based Alias Analysis", false, true, false)
716 ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
717 return new ObjCARCAliasAnalysis();
721 ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
722 AU.setPreservesAll();
723 AliasAnalysis::getAnalysisUsage(AU);
726 AliasAnalysis::AliasResult
727 ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
729 return AliasAnalysis::alias(LocA, LocB);
731 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
732 // precise alias query.
733 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
734 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
736 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
737 Location(SB, LocB.Size, LocB.TBAATag));
738 if (Result != MayAlias)
741 // If that failed, climb to the underlying object, including climbing through
742 // ObjC-specific no-ops, and try making an imprecise alias query.
743 const Value *UA = GetUnderlyingObjCPtr(SA);
744 const Value *UB = GetUnderlyingObjCPtr(SB);
745 if (UA != SA || UB != SB) {
746 Result = AliasAnalysis::alias(Location(UA), Location(UB));
747 // We can't use MustAlias or PartialAlias results here because
748 // GetUnderlyingObjCPtr may return an offsetted pointer value.
749 if (Result == NoAlias)
753 // If that failed, fail. We don't need to chain here, since that's covered
754 // by the earlier precise query.
759 ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
762 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
764 // First, strip off no-ops, including ObjC-specific no-ops, and try making
765 // a precise alias query.
766 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
767 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
771 // If that failed, climb to the underlying object, including climbing through
772 // ObjC-specific no-ops, and try making an imprecise alias query.
773 const Value *U = GetUnderlyingObjCPtr(S);
775 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
777 // If that failed, fail. We don't need to chain here, since that's covered
778 // by the earlier precise query.
782 AliasAnalysis::ModRefBehavior
783 ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
784 // We have nothing to do. Just chain to the next AliasAnalysis.
785 return AliasAnalysis::getModRefBehavior(CS);
788 AliasAnalysis::ModRefBehavior
789 ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
791 return AliasAnalysis::getModRefBehavior(F);
793 switch (GetFunctionClass(F)) {
795 return DoesNotAccessMemory;
800 return AliasAnalysis::getModRefBehavior(F);
803 AliasAnalysis::ModRefResult
804 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
806 return AliasAnalysis::getModRefInfo(CS, Loc);
808 switch (GetBasicInstructionClass(CS.getInstruction())) {
812 case IC_AutoreleaseRV:
814 case IC_AutoreleasepoolPush:
815 case IC_FusedRetainAutorelease:
816 case IC_FusedRetainAutoreleaseRV:
817 // These functions don't access any memory visible to the compiler.
818 // Note that this doesn't include objc_retainBlock, becuase it updates
819 // pointers when it copies block data.
825 return AliasAnalysis::getModRefInfo(CS, Loc);
828 AliasAnalysis::ModRefResult
829 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
830 ImmutableCallSite CS2) {
831 // TODO: Theoretically we could check for dependencies between objc_* calls
832 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
833 return AliasAnalysis::getModRefInfo(CS1, CS2);
836 //===----------------------------------------------------------------------===//
838 //===----------------------------------------------------------------------===//
840 #include "llvm/Support/InstIterator.h"
841 #include "llvm/Transforms/Scalar.h"
844 /// ObjCARCExpand - Early ARC transformations.
845 class ObjCARCExpand : public FunctionPass {
846 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
847 virtual bool doInitialization(Module &M);
848 virtual bool runOnFunction(Function &F);
850 /// Run - A flag indicating whether this optimization pass should run.
855 ObjCARCExpand() : FunctionPass(ID) {
856 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
861 char ObjCARCExpand::ID = 0;
862 INITIALIZE_PASS(ObjCARCExpand,
863 "objc-arc-expand", "ObjC ARC expansion", false, false)
865 Pass *llvm::createObjCARCExpandPass() {
866 return new ObjCARCExpand();
869 void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
870 AU.setPreservesCFG();
873 bool ObjCARCExpand::doInitialization(Module &M) {
874 Run = ModuleHasARC(M);
878 bool ObjCARCExpand::runOnFunction(Function &F) {
882 // If nothing in the Module uses ARC, don't do anything.
886 bool Changed = false;
888 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
889 Instruction *Inst = &*I;
891 switch (GetBasicInstructionClass(Inst)) {
895 case IC_AutoreleaseRV:
896 case IC_FusedRetainAutorelease:
897 case IC_FusedRetainAutoreleaseRV:
898 // These calls return their argument verbatim, as a low-level
899 // optimization. However, this makes high-level optimizations
900 // harder. Undo any uses of this optimization that the front-end
901 // emitted here. We'll redo them in the contract pass.
903 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
913 //===----------------------------------------------------------------------===//
914 // ARC autorelease pool elimination.
915 //===----------------------------------------------------------------------===//
917 #include "llvm/Constants.h"
920 /// ObjCARCAPElim - Autorelease pool elimination.
921 class ObjCARCAPElim : public ModulePass {
922 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
923 virtual bool runOnModule(Module &M);
925 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
926 static bool OptimizeBB(BasicBlock *BB);
930 ObjCARCAPElim() : ModulePass(ID) {
931 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
936 char ObjCARCAPElim::ID = 0;
937 INITIALIZE_PASS(ObjCARCAPElim,
939 "ObjC ARC autorelease pool elimination",
942 Pass *llvm::createObjCARCAPElimPass() {
943 return new ObjCARCAPElim();
946 void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
947 AU.setPreservesCFG();
950 /// MayAutorelease - Interprocedurally determine if calls made by the
951 /// given call site can possibly produce autoreleases.
952 bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
953 if (const Function *Callee = CS.getCalledFunction()) {
954 if (Callee->isDeclaration() || Callee->mayBeOverridden())
956 for (Function::const_iterator I = Callee->begin(), E = Callee->end();
958 const BasicBlock *BB = I;
959 for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
961 if (ImmutableCallSite JCS = ImmutableCallSite(J))
962 // This recursion depth limit is arbitrary. It's just great
963 // enough to cover known interesting testcases.
965 !JCS.onlyReadsMemory() &&
966 MayAutorelease(JCS, Depth + 1))
975 bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
976 bool Changed = false;
978 Instruction *Push = 0;
979 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
980 Instruction *Inst = I++;
981 switch (GetBasicInstructionClass(Inst)) {
982 case IC_AutoreleasepoolPush:
985 case IC_AutoreleasepoolPop:
986 // If this pop matches a push and nothing in between can autorelease,
988 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
990 Inst->eraseFromParent();
991 Push->eraseFromParent();
996 if (MayAutorelease(ImmutableCallSite(Inst)))
1007 bool ObjCARCAPElim::runOnModule(Module &M) {
1011 // If nothing in the Module uses ARC, don't do anything.
1012 if (!ModuleHasARC(M))
1015 // Find the llvm.global_ctors variable, as the first step in
1016 // identifying the global constructors. In theory, unnecessary autorelease
1017 // pools could occur anywhere, but in practice it's pretty rare. Global
1018 // ctors are a place where autorelease pools get inserted automatically,
1019 // so it's pretty common for them to be unnecessary, and it's pretty
1020 // profitable to eliminate them.
1021 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1025 assert(GV->hasDefinitiveInitializer() &&
1026 "llvm.global_ctors is uncooperative!");
1028 bool Changed = false;
1030 // Dig the constructor functions out of GV's initializer.
1031 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1032 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1035 // llvm.global_ctors is an array of pairs where the second members
1036 // are constructor functions.
1037 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1038 // If the user used a constructor function with the wrong signature and
1039 // it got bitcasted or whatever, look the other way.
1042 // Only look at function definitions.
1043 if (F->isDeclaration())
1045 // Only look at functions with one basic block.
1046 if (llvm::next(F->begin()) != F->end())
1048 // Ok, a single-block constructor function definition. Try to optimize it.
1049 Changed |= OptimizeBB(F->begin());
1055 //===----------------------------------------------------------------------===//
1056 // ARC optimization.
1057 //===----------------------------------------------------------------------===//
1059 // TODO: On code like this:
1062 // stuff_that_cannot_release()
1063 // objc_autorelease(%x)
1064 // stuff_that_cannot_release()
1066 // stuff_that_cannot_release()
1067 // objc_autorelease(%x)
1069 // The second retain and autorelease can be deleted.
1071 // TODO: It should be possible to delete
1072 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
1073 // pairs if nothing is actually autoreleased between them. Also, autorelease
1074 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1075 // after inlining) can be turned into plain release calls.
1077 // TODO: Critical-edge splitting. If the optimial insertion point is
1078 // a critical edge, the current algorithm has to fail, because it doesn't
1079 // know how to split edges. It should be possible to make the optimizer
1080 // think in terms of edges, rather than blocks, and then split critical
1083 // TODO: OptimizeSequences could generalized to be Interprocedural.
1085 // TODO: Recognize that a bunch of other objc runtime calls have
1086 // non-escaping arguments and non-releasing arguments, and may be
1087 // non-autoreleasing.
1089 // TODO: Sink autorelease calls as far as possible. Unfortunately we
1090 // usually can't sink them past other calls, which would be the main
1091 // case where it would be useful.
1093 // TODO: The pointer returned from objc_loadWeakRetained is retained.
1095 // TODO: Delete release+retain pairs (rare).
1097 #include "llvm/GlobalAlias.h"
1098 #include "llvm/LLVMContext.h"
1099 #include "llvm/Support/ErrorHandling.h"
1100 #include "llvm/Support/CFG.h"
1101 #include "llvm/ADT/Statistic.h"
1102 #include "llvm/ADT/SmallPtrSet.h"
1103 #include "llvm/ADT/DenseSet.h"
1105 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1106 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1107 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1108 STATISTIC(NumRets, "Number of return value forwarding "
1109 "retain+autoreleaes eliminated");
1110 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1111 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1114 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1115 /// uses many of the same techniques, except it uses special ObjC-specific
1116 /// reasoning about pointer relationships.
1117 class ProvenanceAnalysis {
1120 typedef std::pair<const Value *, const Value *> ValuePairTy;
1121 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1122 CachedResultsTy CachedResults;
1124 bool relatedCheck(const Value *A, const Value *B);
1125 bool relatedSelect(const SelectInst *A, const Value *B);
1126 bool relatedPHI(const PHINode *A, const Value *B);
1128 // Do not implement.
1129 void operator=(const ProvenanceAnalysis &);
1130 ProvenanceAnalysis(const ProvenanceAnalysis &);
1133 ProvenanceAnalysis() {}
1135 void setAA(AliasAnalysis *aa) { AA = aa; }
1137 AliasAnalysis *getAA() const { return AA; }
1139 bool related(const Value *A, const Value *B);
1142 CachedResults.clear();
1147 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1148 // If the values are Selects with the same condition, we can do a more precise
1149 // check: just check for relations between the values on corresponding arms.
1150 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
1151 if (A->getCondition() == SB->getCondition())
1152 return related(A->getTrueValue(), SB->getTrueValue()) ||
1153 related(A->getFalseValue(), SB->getFalseValue());
1155 // Check both arms of the Select node individually.
1156 return related(A->getTrueValue(), B) ||
1157 related(A->getFalseValue(), B);
1160 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1161 // If the values are PHIs in the same block, we can do a more precise as well
1162 // as efficient check: just check for relations between the values on
1163 // corresponding edges.
1164 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1165 if (PNB->getParent() == A->getParent()) {
1166 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1167 if (related(A->getIncomingValue(i),
1168 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1173 // Check each unique source of the PHI node against B.
1174 SmallPtrSet<const Value *, 4> UniqueSrc;
1175 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1176 const Value *PV1 = A->getIncomingValue(i);
1177 if (UniqueSrc.insert(PV1) && related(PV1, B))
1181 // All of the arms checked out.
1185 /// isStoredObjCPointer - Test if the value of P, or any value covered by its
1186 /// provenance, is ever stored within the function (not counting callees).
1187 static bool isStoredObjCPointer(const Value *P) {
1188 SmallPtrSet<const Value *, 8> Visited;
1189 SmallVector<const Value *, 8> Worklist;
1190 Worklist.push_back(P);
1193 P = Worklist.pop_back_val();
1194 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1196 const User *Ur = *UI;
1197 if (isa<StoreInst>(Ur)) {
1198 if (UI.getOperandNo() == 0)
1199 // The pointer is stored.
1201 // The pointed is stored through.
1204 if (isa<CallInst>(Ur))
1205 // The pointer is passed as an argument, ignore this.
1207 if (isa<PtrToIntInst>(P))
1208 // Assume the worst.
1210 if (Visited.insert(Ur))
1211 Worklist.push_back(Ur);
1213 } while (!Worklist.empty());
1215 // Everything checked out.
1219 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1220 // Skip past provenance pass-throughs.
1221 A = GetUnderlyingObjCPtr(A);
1222 B = GetUnderlyingObjCPtr(B);
1228 // Ask regular AliasAnalysis, for a first approximation.
1229 switch (AA->alias(A, B)) {
1230 case AliasAnalysis::NoAlias:
1232 case AliasAnalysis::MustAlias:
1233 case AliasAnalysis::PartialAlias:
1235 case AliasAnalysis::MayAlias:
1239 bool AIsIdentified = IsObjCIdentifiedObject(A);
1240 bool BIsIdentified = IsObjCIdentifiedObject(B);
1242 // An ObjC-Identified object can't alias a load if it is never locally stored.
1243 if (AIsIdentified) {
1244 if (BIsIdentified) {
1245 // If both pointers have provenance, they can be directly compared.
1249 if (isa<LoadInst>(B))
1250 return isStoredObjCPointer(A);
1253 if (BIsIdentified && isa<LoadInst>(A))
1254 return isStoredObjCPointer(B);
1257 // Special handling for PHI and Select.
1258 if (const PHINode *PN = dyn_cast<PHINode>(A))
1259 return relatedPHI(PN, B);
1260 if (const PHINode *PN = dyn_cast<PHINode>(B))
1261 return relatedPHI(PN, A);
1262 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1263 return relatedSelect(S, B);
1264 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1265 return relatedSelect(S, A);
1271 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1272 // Begin by inserting a conservative value into the map. If the insertion
1273 // fails, we have the answer already. If it succeeds, leave it there until we
1274 // compute the real answer to guard against recursive queries.
1275 if (A > B) std::swap(A, B);
1276 std::pair<CachedResultsTy::iterator, bool> Pair =
1277 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1279 return Pair.first->second;
1281 bool Result = relatedCheck(A, B);
1282 CachedResults[ValuePairTy(A, B)] = Result;
1287 // Sequence - A sequence of states that a pointer may go through in which an
1288 // objc_retain and objc_release are actually needed.
1291 S_Retain, ///< objc_retain(x)
1292 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1293 S_Use, ///< any use of x
1294 S_Stop, ///< like S_Release, but code motion is stopped
1295 S_Release, ///< objc_release(x)
1296 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1300 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1304 if (A == S_None || B == S_None)
1307 if (A > B) std::swap(A, B);
1309 // Choose the side which is further along in the sequence.
1310 if ((A == S_Retain || A == S_CanRelease) &&
1311 (B == S_CanRelease || B == S_Use))
1314 // Choose the side which is further along in the sequence.
1315 if ((A == S_Use || A == S_CanRelease) &&
1316 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
1318 // If both sides are releases, choose the more conservative one.
1319 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1321 if (A == S_Release && B == S_MovableRelease)
1329 /// RRInfo - Unidirectional information about either a
1330 /// retain-decrement-use-release sequence or release-use-decrement-retain
1331 /// reverese sequence.
1333 /// KnownSafe - After an objc_retain, the reference count of the referenced
1334 /// object is known to be positive. Similarly, before an objc_release, the
1335 /// reference count of the referenced object is known to be positive. If
1336 /// there are retain-release pairs in code regions where the retain count
1337 /// is known to be positive, they can be eliminated, regardless of any side
1338 /// effects between them.
1340 /// Also, a retain+release pair nested within another retain+release
1341 /// pair all on the known same pointer value can be eliminated, regardless
1342 /// of any intervening side effects.
1344 /// KnownSafe is true when either of these conditions is satisfied.
1347 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1348 /// opposed to objc_retain calls).
1351 /// IsTailCallRelease - True of the objc_release calls are all marked
1352 /// with the "tail" keyword.
1353 bool IsTailCallRelease;
1355 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1356 /// a clang.imprecise_release tag, this is the metadata tag.
1357 MDNode *ReleaseMetadata;
1359 /// Calls - For a top-down sequence, the set of objc_retains or
1360 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1361 SmallPtrSet<Instruction *, 2> Calls;
1363 /// ReverseInsertPts - The set of optimal insert positions for
1364 /// moving calls in the opposite sequence.
1365 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1368 KnownSafe(false), IsRetainBlock(false),
1369 IsTailCallRelease(false),
1370 ReleaseMetadata(0) {}
1376 void RRInfo::clear() {
1378 IsRetainBlock = false;
1379 IsTailCallRelease = false;
1380 ReleaseMetadata = 0;
1382 ReverseInsertPts.clear();
1386 /// PtrState - This class summarizes several per-pointer runtime properties
1387 /// which are propogated through the flow graph.
1389 /// KnownPositiveRefCount - True if the reference count is known to
1391 bool KnownPositiveRefCount;
1393 /// Partial - True of we've seen an opportunity for partial RR elimination,
1394 /// such as pushing calls into a CFG triangle or into one side of a
1398 /// NestCount - The known minimum level of retain+release nesting.
1401 /// Seq - The current position in the sequence.
1405 /// RRI - Unidirectional information about the current sequence.
1406 /// TODO: Encapsulate this better.
1409 PtrState() : KnownPositiveRefCount(false), Partial(false),
1410 NestCount(0), Seq(S_None) {}
1412 void SetKnownPositiveRefCount() {
1413 KnownPositiveRefCount = true;
1416 void ClearRefCount() {
1417 KnownPositiveRefCount = false;
1420 bool IsKnownIncremented() const {
1421 return KnownPositiveRefCount;
1424 void IncrementNestCount() {
1425 if (NestCount != UINT_MAX) ++NestCount;
1428 void DecrementNestCount() {
1429 if (NestCount != 0) --NestCount;
1432 bool IsKnownNested() const {
1433 return NestCount > 0;
1436 void SetSeq(Sequence NewSeq) {
1440 Sequence GetSeq() const {
1444 void ClearSequenceProgress() {
1445 ResetSequenceProgress(S_None);
1448 void ResetSequenceProgress(Sequence NewSeq) {
1454 void Merge(const PtrState &Other, bool TopDown);
1459 PtrState::Merge(const PtrState &Other, bool TopDown) {
1460 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1461 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
1462 NestCount = std::min(NestCount, Other.NestCount);
1464 // We can't merge a plain objc_retain with an objc_retainBlock.
1465 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1468 // If we're not in a sequence (anymore), drop all associated state.
1469 if (Seq == S_None) {
1472 } else if (Partial || Other.Partial) {
1473 // If we're doing a merge on a path that's previously seen a partial
1474 // merge, conservatively drop the sequence, to avoid doing partial
1475 // RR elimination. If the branch predicates for the two merge differ,
1476 // mixing them is unsafe.
1477 ClearSequenceProgress();
1479 // Conservatively merge the ReleaseMetadata information.
1480 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1481 RRI.ReleaseMetadata = 0;
1483 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
1484 RRI.IsTailCallRelease = RRI.IsTailCallRelease && Other.RRI.IsTailCallRelease;
1485 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1487 // Merge the insert point sets. If there are any differences,
1488 // that makes this a partial merge.
1489 Partial = RRI.ReverseInsertPts.size() !=
1490 Other.RRI.ReverseInsertPts.size();
1491 for (SmallPtrSet<Instruction *, 2>::const_iterator
1492 I = Other.RRI.ReverseInsertPts.begin(),
1493 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1494 Partial |= RRI.ReverseInsertPts.insert(*I);
1499 /// BBState - Per-BasicBlock state.
1501 /// TopDownPathCount - The number of unique control paths from the entry
1502 /// which can reach this block.
1503 unsigned TopDownPathCount;
1505 /// BottomUpPathCount - The number of unique control paths to exits
1506 /// from this block.
1507 unsigned BottomUpPathCount;
1509 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1510 typedef MapVector<const Value *, PtrState> MapTy;
1512 /// PerPtrTopDown - The top-down traversal uses this to record information
1513 /// known about a pointer at the bottom of each block.
1514 MapTy PerPtrTopDown;
1516 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1517 /// known about a pointer at the top of each block.
1518 MapTy PerPtrBottomUp;
1520 /// Preds, Succs - Effective successors and predecessors of the current
1521 /// block (this ignores ignorable edges and ignored backedges).
1522 SmallVector<BasicBlock *, 2> Preds;
1523 SmallVector<BasicBlock *, 2> Succs;
1526 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1528 typedef MapTy::iterator ptr_iterator;
1529 typedef MapTy::const_iterator ptr_const_iterator;
1531 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1532 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1533 ptr_const_iterator top_down_ptr_begin() const {
1534 return PerPtrTopDown.begin();
1536 ptr_const_iterator top_down_ptr_end() const {
1537 return PerPtrTopDown.end();
1540 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1541 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1542 ptr_const_iterator bottom_up_ptr_begin() const {
1543 return PerPtrBottomUp.begin();
1545 ptr_const_iterator bottom_up_ptr_end() const {
1546 return PerPtrBottomUp.end();
1549 /// SetAsEntry - Mark this block as being an entry block, which has one
1550 /// path from the entry by definition.
1551 void SetAsEntry() { TopDownPathCount = 1; }
1553 /// SetAsExit - Mark this block as being an exit block, which has one
1554 /// path to an exit by definition.
1555 void SetAsExit() { BottomUpPathCount = 1; }
1557 PtrState &getPtrTopDownState(const Value *Arg) {
1558 return PerPtrTopDown[Arg];
1561 PtrState &getPtrBottomUpState(const Value *Arg) {
1562 return PerPtrBottomUp[Arg];
1565 void clearBottomUpPointers() {
1566 PerPtrBottomUp.clear();
1569 void clearTopDownPointers() {
1570 PerPtrTopDown.clear();
1573 void InitFromPred(const BBState &Other);
1574 void InitFromSucc(const BBState &Other);
1575 void MergePred(const BBState &Other);
1576 void MergeSucc(const BBState &Other);
1578 /// GetAllPathCount - Return the number of possible unique paths from an
1579 /// entry to an exit which pass through this block. This is only valid
1580 /// after both the top-down and bottom-up traversals are complete.
1581 unsigned GetAllPathCount() const {
1582 assert(TopDownPathCount != 0);
1583 assert(BottomUpPathCount != 0);
1584 return TopDownPathCount * BottomUpPathCount;
1587 // Specialized CFG utilities.
1588 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
1589 edge_iterator pred_begin() { return Preds.begin(); }
1590 edge_iterator pred_end() { return Preds.end(); }
1591 edge_iterator succ_begin() { return Succs.begin(); }
1592 edge_iterator succ_end() { return Succs.end(); }
1594 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1595 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1597 bool isExit() const { return Succs.empty(); }
1601 void BBState::InitFromPred(const BBState &Other) {
1602 PerPtrTopDown = Other.PerPtrTopDown;
1603 TopDownPathCount = Other.TopDownPathCount;
1606 void BBState::InitFromSucc(const BBState &Other) {
1607 PerPtrBottomUp = Other.PerPtrBottomUp;
1608 BottomUpPathCount = Other.BottomUpPathCount;
1611 /// MergePred - The top-down traversal uses this to merge information about
1612 /// predecessors to form the initial state for a new block.
1613 void BBState::MergePred(const BBState &Other) {
1614 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1615 // loop backedge. Loop backedges are special.
1616 TopDownPathCount += Other.TopDownPathCount;
1618 // For each entry in the other set, if our set has an entry with the same key,
1619 // merge the entries. Otherwise, copy the entry and merge it with an empty
1621 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1622 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1623 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1624 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1628 // For each entry in our set, if the other set doesn't have an entry with the
1629 // same key, force it to merge with an empty entry.
1630 for (ptr_iterator MI = top_down_ptr_begin(),
1631 ME = top_down_ptr_end(); MI != ME; ++MI)
1632 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1633 MI->second.Merge(PtrState(), /*TopDown=*/true);
1636 /// MergeSucc - The bottom-up traversal uses this to merge information about
1637 /// successors to form the initial state for a new block.
1638 void BBState::MergeSucc(const BBState &Other) {
1639 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1640 // loop backedge. Loop backedges are special.
1641 BottomUpPathCount += Other.BottomUpPathCount;
1643 // For each entry in the other set, if our set has an entry with the
1644 // same key, merge the entries. Otherwise, copy the entry and merge
1645 // it with an empty entry.
1646 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1647 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1648 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1649 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1653 // For each entry in our set, if the other set doesn't have an entry
1654 // with the same key, force it to merge with an empty entry.
1655 for (ptr_iterator MI = bottom_up_ptr_begin(),
1656 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1657 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1658 MI->second.Merge(PtrState(), /*TopDown=*/false);
1662 /// ObjCARCOpt - The main ARC optimization pass.
1663 class ObjCARCOpt : public FunctionPass {
1665 ProvenanceAnalysis PA;
1667 /// Run - A flag indicating whether this optimization pass should run.
1670 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1671 /// functions, for use in creating calls to them. These are initialized
1672 /// lazily to avoid cluttering up the Module with unused declarations.
1673 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
1674 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
1676 /// UsedInThisFunciton - Flags which determine whether each of the
1677 /// interesting runtine functions is in fact used in the current function.
1678 unsigned UsedInThisFunction;
1680 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1682 unsigned ImpreciseReleaseMDKind;
1684 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
1686 unsigned CopyOnEscapeMDKind;
1688 /// NoObjCARCExceptionsMDKind - The Metadata Kind for
1689 /// clang.arc.no_objc_arc_exceptions metadata.
1690 unsigned NoObjCARCExceptionsMDKind;
1692 Constant *getRetainRVCallee(Module *M);
1693 Constant *getAutoreleaseRVCallee(Module *M);
1694 Constant *getReleaseCallee(Module *M);
1695 Constant *getRetainCallee(Module *M);
1696 Constant *getRetainBlockCallee(Module *M);
1697 Constant *getAutoreleaseCallee(Module *M);
1699 bool IsRetainBlockOptimizable(const Instruction *Inst);
1701 void OptimizeRetainCall(Function &F, Instruction *Retain);
1702 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1703 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1704 void OptimizeIndividualCalls(Function &F);
1706 void CheckForCFGHazards(const BasicBlock *BB,
1707 DenseMap<const BasicBlock *, BBState> &BBStates,
1708 BBState &MyStates) const;
1709 bool VisitInstructionBottomUp(Instruction *Inst,
1711 MapVector<Value *, RRInfo> &Retains,
1713 bool VisitBottomUp(BasicBlock *BB,
1714 DenseMap<const BasicBlock *, BBState> &BBStates,
1715 MapVector<Value *, RRInfo> &Retains);
1716 bool VisitInstructionTopDown(Instruction *Inst,
1717 DenseMap<Value *, RRInfo> &Releases,
1719 bool VisitTopDown(BasicBlock *BB,
1720 DenseMap<const BasicBlock *, BBState> &BBStates,
1721 DenseMap<Value *, RRInfo> &Releases);
1722 bool Visit(Function &F,
1723 DenseMap<const BasicBlock *, BBState> &BBStates,
1724 MapVector<Value *, RRInfo> &Retains,
1725 DenseMap<Value *, RRInfo> &Releases);
1727 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1728 MapVector<Value *, RRInfo> &Retains,
1729 DenseMap<Value *, RRInfo> &Releases,
1730 SmallVectorImpl<Instruction *> &DeadInsts,
1733 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1734 MapVector<Value *, RRInfo> &Retains,
1735 DenseMap<Value *, RRInfo> &Releases,
1738 void OptimizeWeakCalls(Function &F);
1740 bool OptimizeSequences(Function &F);
1742 void OptimizeReturns(Function &F);
1744 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1745 virtual bool doInitialization(Module &M);
1746 virtual bool runOnFunction(Function &F);
1747 virtual void releaseMemory();
1751 ObjCARCOpt() : FunctionPass(ID) {
1752 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1757 char ObjCARCOpt::ID = 0;
1758 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1759 "objc-arc", "ObjC ARC optimization", false, false)
1760 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1761 INITIALIZE_PASS_END(ObjCARCOpt,
1762 "objc-arc", "ObjC ARC optimization", false, false)
1764 Pass *llvm::createObjCARCOptPass() {
1765 return new ObjCARCOpt();
1768 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1769 AU.addRequired<ObjCARCAliasAnalysis>();
1770 AU.addRequired<AliasAnalysis>();
1771 // ARC optimization doesn't currently split critical edges.
1772 AU.setPreservesCFG();
1775 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1776 // Without the magic metadata tag, we have to assume this might be an
1777 // objc_retainBlock call inserted to convert a block pointer to an id,
1778 // in which case it really is needed.
1779 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1782 // If the pointer "escapes" (not including being used in a call),
1783 // the copy may be needed.
1784 if (DoesObjCBlockEscape(Inst))
1787 // Otherwise, it's not needed.
1791 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1792 if (!RetainRVCallee) {
1793 LLVMContext &C = M->getContext();
1794 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1795 std::vector<Type *> Params;
1796 Params.push_back(I8X);
1798 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1799 AttrListPtr Attributes;
1800 Attributes.addAttr(~0u, Attribute::NoUnwind);
1802 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1805 return RetainRVCallee;
1808 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1809 if (!AutoreleaseRVCallee) {
1810 LLVMContext &C = M->getContext();
1811 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1812 std::vector<Type *> Params;
1813 Params.push_back(I8X);
1815 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1816 AttrListPtr Attributes;
1817 Attributes.addAttr(~0u, Attribute::NoUnwind);
1818 AutoreleaseRVCallee =
1819 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1822 return AutoreleaseRVCallee;
1825 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1826 if (!ReleaseCallee) {
1827 LLVMContext &C = M->getContext();
1828 std::vector<Type *> Params;
1829 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1830 AttrListPtr Attributes;
1831 Attributes.addAttr(~0u, Attribute::NoUnwind);
1833 M->getOrInsertFunction(
1835 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1838 return ReleaseCallee;
1841 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1842 if (!RetainCallee) {
1843 LLVMContext &C = M->getContext();
1844 std::vector<Type *> Params;
1845 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1846 AttrListPtr Attributes;
1847 Attributes.addAttr(~0u, Attribute::NoUnwind);
1849 M->getOrInsertFunction(
1851 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1854 return RetainCallee;
1857 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1858 if (!RetainBlockCallee) {
1859 LLVMContext &C = M->getContext();
1860 std::vector<Type *> Params;
1861 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1862 AttrListPtr Attributes;
1863 // objc_retainBlock is not nounwind because it calls user copy constructors
1864 // which could theoretically throw.
1866 M->getOrInsertFunction(
1868 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1871 return RetainBlockCallee;
1874 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1875 if (!AutoreleaseCallee) {
1876 LLVMContext &C = M->getContext();
1877 std::vector<Type *> Params;
1878 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1879 AttrListPtr Attributes;
1880 Attributes.addAttr(~0u, Attribute::NoUnwind);
1882 M->getOrInsertFunction(
1884 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1887 return AutoreleaseCallee;
1890 /// CanAlterRefCount - Test whether the given instruction can result in a
1891 /// reference count modification (positive or negative) for the pointer's
1894 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1895 ProvenanceAnalysis &PA, InstructionClass Class) {
1897 case IC_Autorelease:
1898 case IC_AutoreleaseRV:
1900 // These operations never directly modify a reference count.
1905 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1906 assert(CS && "Only calls can alter reference counts!");
1908 // See if AliasAnalysis can help us with the call.
1909 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1910 if (AliasAnalysis::onlyReadsMemory(MRB))
1912 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1913 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1915 const Value *Op = *I;
1916 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1922 // Assume the worst.
1926 /// CanUse - Test whether the given instruction can "use" the given pointer's
1927 /// object in a way that requires the reference count to be positive.
1929 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1930 InstructionClass Class) {
1931 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1932 if (Class == IC_Call)
1935 // Consider various instructions which may have pointer arguments which are
1937 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1938 // Comparing a pointer with null, or any other constant, isn't really a use,
1939 // because we don't care what the pointer points to, or about the values
1940 // of any other dynamic reference-counted pointers.
1941 if (!IsPotentialUse(ICI->getOperand(1)))
1943 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1944 // For calls, just check the arguments (and not the callee operand).
1945 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1946 OE = CS.arg_end(); OI != OE; ++OI) {
1947 const Value *Op = *OI;
1948 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1952 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1953 // Special-case stores, because we don't care about the stored value, just
1954 // the store address.
1955 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1956 // If we can't tell what the underlying object was, assume there is a
1958 return IsPotentialUse(Op) && PA.related(Op, Ptr);
1961 // Check each operand for a match.
1962 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1964 const Value *Op = *OI;
1965 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1971 /// CanInterruptRV - Test whether the given instruction can autorelease
1972 /// any pointer or cause an autoreleasepool pop.
1974 CanInterruptRV(InstructionClass Class) {
1976 case IC_AutoreleasepoolPop:
1979 case IC_Autorelease:
1980 case IC_AutoreleaseRV:
1981 case IC_FusedRetainAutorelease:
1982 case IC_FusedRetainAutoreleaseRV:
1990 /// DependenceKind - There are several kinds of dependence-like concepts in
1992 enum DependenceKind {
1993 NeedsPositiveRetainCount,
1994 AutoreleasePoolBoundary,
1995 CanChangeRetainCount,
1996 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1997 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1998 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
2002 /// Depends - Test if there can be dependencies on Inst through Arg. This
2003 /// function only tests dependencies relevant for removing pairs of calls.
2005 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2006 ProvenanceAnalysis &PA) {
2007 // If we've reached the definition of Arg, stop.
2012 case NeedsPositiveRetainCount: {
2013 InstructionClass Class = GetInstructionClass(Inst);
2015 case IC_AutoreleasepoolPop:
2016 case IC_AutoreleasepoolPush:
2020 return CanUse(Inst, Arg, PA, Class);
2024 case AutoreleasePoolBoundary: {
2025 InstructionClass Class = GetInstructionClass(Inst);
2027 case IC_AutoreleasepoolPop:
2028 case IC_AutoreleasepoolPush:
2029 // These mark the end and begin of an autorelease pool scope.
2032 // Nothing else does this.
2037 case CanChangeRetainCount: {
2038 InstructionClass Class = GetInstructionClass(Inst);
2040 case IC_AutoreleasepoolPop:
2041 // Conservatively assume this can decrement any count.
2043 case IC_AutoreleasepoolPush:
2047 return CanAlterRefCount(Inst, Arg, PA, Class);
2051 case RetainAutoreleaseDep:
2052 switch (GetBasicInstructionClass(Inst)) {
2053 case IC_AutoreleasepoolPop:
2054 case IC_AutoreleasepoolPush:
2055 // Don't merge an objc_autorelease with an objc_retain inside a different
2056 // autoreleasepool scope.
2060 // Check for a retain of the same pointer for merging.
2061 return GetObjCArg(Inst) == Arg;
2063 // Nothing else matters for objc_retainAutorelease formation.
2067 case RetainAutoreleaseRVDep: {
2068 InstructionClass Class = GetBasicInstructionClass(Inst);
2072 // Check for a retain of the same pointer for merging.
2073 return GetObjCArg(Inst) == Arg;
2075 // Anything that can autorelease interrupts
2076 // retainAutoreleaseReturnValue formation.
2077 return CanInterruptRV(Class);
2082 return CanInterruptRV(GetBasicInstructionClass(Inst));
2085 llvm_unreachable("Invalid dependence flavor");
2088 /// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2089 /// find local and non-local dependencies on Arg.
2090 /// TODO: Cache results?
2092 FindDependencies(DependenceKind Flavor,
2094 BasicBlock *StartBB, Instruction *StartInst,
2095 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2096 SmallPtrSet<const BasicBlock *, 4> &Visited,
2097 ProvenanceAnalysis &PA) {
2098 BasicBlock::iterator StartPos = StartInst;
2100 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2101 Worklist.push_back(std::make_pair(StartBB, StartPos));
2103 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2104 Worklist.pop_back_val();
2105 BasicBlock *LocalStartBB = Pair.first;
2106 BasicBlock::iterator LocalStartPos = Pair.second;
2107 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2109 if (LocalStartPos == StartBBBegin) {
2110 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2112 // If we've reached the function entry, produce a null dependence.
2113 DependingInstructions.insert(0);
2115 // Add the predecessors to the worklist.
2117 BasicBlock *PredBB = *PI;
2118 if (Visited.insert(PredBB))
2119 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2120 } while (++PI != PE);
2124 Instruction *Inst = --LocalStartPos;
2125 if (Depends(Flavor, Inst, Arg, PA)) {
2126 DependingInstructions.insert(Inst);
2130 } while (!Worklist.empty());
2132 // Determine whether the original StartBB post-dominates all of the blocks we
2133 // visited. If not, insert a sentinal indicating that most optimizations are
2135 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2136 E = Visited.end(); I != E; ++I) {
2137 const BasicBlock *BB = *I;
2140 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2141 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2142 const BasicBlock *Succ = *SI;
2143 if (Succ != StartBB && !Visited.count(Succ)) {
2144 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2151 static bool isNullOrUndef(const Value *V) {
2152 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2155 static bool isNoopInstruction(const Instruction *I) {
2156 return isa<BitCastInst>(I) ||
2157 (isa<GetElementPtrInst>(I) &&
2158 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2161 /// OptimizeRetainCall - Turn objc_retain into
2162 /// objc_retainAutoreleasedReturnValue if the operand is a return value.
2164 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
2165 ImmutableCallSite CS(GetObjCArg(Retain));
2166 const Instruction *Call = CS.getInstruction();
2168 if (Call->getParent() != Retain->getParent()) return;
2170 // Check that the call is next to the retain.
2171 BasicBlock::const_iterator I = Call;
2173 while (isNoopInstruction(I)) ++I;
2177 // Turn it to an objc_retainAutoreleasedReturnValue..
2180 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2183 /// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
2184 /// objc_retain if the operand is not a return value. Or, if it can be paired
2185 /// with an objc_autoreleaseReturnValue, delete the pair and return true.
2187 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
2188 // Check for the argument being from an immediately preceding call or invoke.
2189 const Value *Arg = GetObjCArg(RetainRV);
2190 ImmutableCallSite CS(Arg);
2191 if (const Instruction *Call = CS.getInstruction()) {
2192 if (Call->getParent() == RetainRV->getParent()) {
2193 BasicBlock::const_iterator I = Call;
2195 while (isNoopInstruction(I)) ++I;
2196 if (&*I == RetainRV)
2198 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
2199 BasicBlock *RetainRVParent = RetainRV->getParent();
2200 if (II->getNormalDest() == RetainRVParent) {
2201 BasicBlock::const_iterator I = RetainRVParent->begin();
2202 while (isNoopInstruction(I)) ++I;
2203 if (&*I == RetainRV)
2209 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2210 // pointer. In this case, we can delete the pair.
2211 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2213 do --I; while (I != Begin && isNoopInstruction(I));
2214 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2215 GetObjCArg(I) == Arg) {
2218 EraseInstruction(I);
2219 EraseInstruction(RetainRV);
2224 // Turn it to a plain objc_retain.
2227 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2231 /// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2232 /// objc_autorelease if the result is not used as a return value.
2234 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
2235 // Check for a return of the pointer value.
2236 const Value *Ptr = GetObjCArg(AutoreleaseRV);
2237 SmallVector<const Value *, 2> Users;
2238 Users.push_back(Ptr);
2240 Ptr = Users.pop_back_val();
2241 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2243 const User *I = *UI;
2244 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2246 if (isa<BitCastInst>(I))
2249 } while (!Users.empty());
2253 cast<CallInst>(AutoreleaseRV)->
2254 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2257 /// OptimizeIndividualCalls - Visit each call, one at a time, and make
2258 /// simplifications without doing any additional analysis.
2259 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2260 // Reset all the flags in preparation for recomputing them.
2261 UsedInThisFunction = 0;
2263 // Visit all objc_* calls in F.
2264 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2265 Instruction *Inst = &*I++;
2266 InstructionClass Class = GetBasicInstructionClass(Inst);
2271 // Delete no-op casts. These function calls have special semantics, but
2272 // the semantics are entirely implemented via lowering in the front-end,
2273 // so by the time they reach the optimizer, they are just no-op calls
2274 // which return their argument.
2276 // There are gray areas here, as the ability to cast reference-counted
2277 // pointers to raw void* and back allows code to break ARC assumptions,
2278 // however these are currently considered to be unimportant.
2282 EraseInstruction(Inst);
2285 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2288 case IC_LoadWeakRetained:
2290 case IC_DestroyWeak: {
2291 CallInst *CI = cast<CallInst>(Inst);
2292 if (isNullOrUndef(CI->getArgOperand(0))) {
2294 Type *Ty = CI->getArgOperand(0)->getType();
2295 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2296 Constant::getNullValue(Ty),
2298 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2299 CI->eraseFromParent();
2306 CallInst *CI = cast<CallInst>(Inst);
2307 if (isNullOrUndef(CI->getArgOperand(0)) ||
2308 isNullOrUndef(CI->getArgOperand(1))) {
2310 Type *Ty = CI->getArgOperand(0)->getType();
2311 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2312 Constant::getNullValue(Ty),
2314 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2315 CI->eraseFromParent();
2321 OptimizeRetainCall(F, Inst);
2324 if (OptimizeRetainRVCall(F, Inst))
2327 case IC_AutoreleaseRV:
2328 OptimizeAutoreleaseRVCall(F, Inst);
2332 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2333 if (IsAutorelease(Class) && Inst->use_empty()) {
2334 CallInst *Call = cast<CallInst>(Inst);
2335 const Value *Arg = Call->getArgOperand(0);
2336 Arg = FindSingleUseIdentifiedObject(Arg);
2341 // Create the declaration lazily.
2342 LLVMContext &C = Inst->getContext();
2344 CallInst::Create(getReleaseCallee(F.getParent()),
2345 Call->getArgOperand(0), "", Call);
2346 NewCall->setMetadata(ImpreciseReleaseMDKind,
2347 MDNode::get(C, ArrayRef<Value *>()));
2348 EraseInstruction(Call);
2354 // For functions which can never be passed stack arguments, add
2356 if (IsAlwaysTail(Class)) {
2358 cast<CallInst>(Inst)->setTailCall();
2361 // Set nounwind as needed.
2362 if (IsNoThrow(Class)) {
2364 cast<CallInst>(Inst)->setDoesNotThrow();
2367 if (!IsNoopOnNull(Class)) {
2368 UsedInThisFunction |= 1 << Class;
2372 const Value *Arg = GetObjCArg(Inst);
2374 // ARC calls with null are no-ops. Delete them.
2375 if (isNullOrUndef(Arg)) {
2378 EraseInstruction(Inst);
2382 // Keep track of which of retain, release, autorelease, and retain_block
2383 // are actually present in this function.
2384 UsedInThisFunction |= 1 << Class;
2386 // If Arg is a PHI, and one or more incoming values to the
2387 // PHI are null, and the call is control-equivalent to the PHI, and there
2388 // are no relevant side effects between the PHI and the call, the call
2389 // could be pushed up to just those paths with non-null incoming values.
2390 // For now, don't bother splitting critical edges for this.
2391 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2392 Worklist.push_back(std::make_pair(Inst, Arg));
2394 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2398 const PHINode *PN = dyn_cast<PHINode>(Arg);
2401 // Determine if the PHI has any null operands, or any incoming
2403 bool HasNull = false;
2404 bool HasCriticalEdges = false;
2405 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2407 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2408 if (isNullOrUndef(Incoming))
2410 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2411 .getNumSuccessors() != 1) {
2412 HasCriticalEdges = true;
2416 // If we have null operands and no critical edges, optimize.
2417 if (!HasCriticalEdges && HasNull) {
2418 SmallPtrSet<Instruction *, 4> DependingInstructions;
2419 SmallPtrSet<const BasicBlock *, 4> Visited;
2421 // Check that there is nothing that cares about the reference
2422 // count between the call and the phi.
2425 case IC_RetainBlock:
2426 // These can always be moved up.
2429 // These can't be moved across things that care about the retain count.
2430 FindDependencies(NeedsPositiveRetainCount, Arg,
2431 Inst->getParent(), Inst,
2432 DependingInstructions, Visited, PA);
2434 case IC_Autorelease:
2435 // These can't be moved across autorelease pool scope boundaries.
2436 FindDependencies(AutoreleasePoolBoundary, Arg,
2437 Inst->getParent(), Inst,
2438 DependingInstructions, Visited, PA);
2441 case IC_AutoreleaseRV:
2442 // Don't move these; the RV optimization depends on the autoreleaseRV
2443 // being tail called, and the retainRV being immediately after a call
2444 // (which might still happen if we get lucky with codegen layout, but
2445 // it's not worth taking the chance).
2448 llvm_unreachable("Invalid dependence flavor");
2451 if (DependingInstructions.size() == 1 &&
2452 *DependingInstructions.begin() == PN) {
2455 // Clone the call into each predecessor that has a non-null value.
2456 CallInst *CInst = cast<CallInst>(Inst);
2457 Type *ParamTy = CInst->getArgOperand(0)->getType();
2458 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2460 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2461 if (!isNullOrUndef(Incoming)) {
2462 CallInst *Clone = cast<CallInst>(CInst->clone());
2463 Value *Op = PN->getIncomingValue(i);
2464 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2465 if (Op->getType() != ParamTy)
2466 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2467 Clone->setArgOperand(0, Op);
2468 Clone->insertBefore(InsertPos);
2469 Worklist.push_back(std::make_pair(Clone, Incoming));
2472 // Erase the original call.
2473 EraseInstruction(CInst);
2477 } while (!Worklist.empty());
2481 /// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2482 /// control flow, or other CFG structures where moving code across the edge
2483 /// would result in it being executed more.
2485 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2486 DenseMap<const BasicBlock *, BBState> &BBStates,
2487 BBState &MyStates) const {
2488 // If any top-down local-use or possible-dec has a succ which is earlier in
2489 // the sequence, forget it.
2490 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
2491 E = MyStates.top_down_ptr_end(); I != E; ++I)
2492 switch (I->second.GetSeq()) {
2495 const Value *Arg = I->first;
2496 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2497 bool SomeSuccHasSame = false;
2498 bool AllSuccsHaveSame = true;
2499 PtrState &S = I->second;
2500 succ_const_iterator SI(TI), SE(TI, false);
2502 // If the terminator is an invoke marked with the
2503 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2504 // ignored, for ARC purposes.
2505 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2508 for (; SI != SE; ++SI) {
2509 Sequence SuccSSeq = S_None;
2510 bool SuccSRRIKnownSafe = false;
2511 // If VisitBottomUp has pointer information for this successor, take what we
2513 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2515 assert(BBI != BBStates.end());
2516 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2517 SuccSSeq = SuccS.GetSeq();
2518 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2521 case S_CanRelease: {
2522 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2523 S.ClearSequenceProgress();
2529 SomeSuccHasSame = true;
2533 case S_MovableRelease:
2534 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2535 AllSuccsHaveSame = false;
2538 llvm_unreachable("bottom-up pointer in retain state!");
2541 // If the state at the other end of any of the successor edges
2542 // matches the current state, require all edges to match. This
2543 // guards against loops in the middle of a sequence.
2544 if (SomeSuccHasSame && !AllSuccsHaveSame)
2545 S.ClearSequenceProgress();
2548 case S_CanRelease: {
2549 const Value *Arg = I->first;
2550 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2551 bool SomeSuccHasSame = false;
2552 bool AllSuccsHaveSame = true;
2553 PtrState &S = I->second;
2554 succ_const_iterator SI(TI), SE(TI, false);
2556 // If the terminator is an invoke marked with the
2557 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2558 // ignored, for ARC purposes.
2559 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2562 for (; SI != SE; ++SI) {
2563 Sequence SuccSSeq = S_None;
2564 bool SuccSRRIKnownSafe = false;
2565 // If VisitBottomUp has pointer information for this successor, take what we
2567 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2569 assert(BBI != BBStates.end());
2570 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2571 SuccSSeq = SuccS.GetSeq();
2572 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2575 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2576 S.ClearSequenceProgress();
2582 SomeSuccHasSame = true;
2586 case S_MovableRelease:
2588 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2589 AllSuccsHaveSame = false;
2592 llvm_unreachable("bottom-up pointer in retain state!");
2595 // If the state at the other end of any of the successor edges
2596 // matches the current state, require all edges to match. This
2597 // guards against loops in the middle of a sequence.
2598 if (SomeSuccHasSame && !AllSuccsHaveSame)
2599 S.ClearSequenceProgress();
2606 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
2608 MapVector<Value *, RRInfo> &Retains,
2609 BBState &MyStates) {
2610 bool NestingDetected = false;
2611 InstructionClass Class = GetInstructionClass(Inst);
2612 const Value *Arg = 0;
2616 Arg = GetObjCArg(Inst);
2618 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2620 // If we see two releases in a row on the same pointer. If so, make
2621 // a note, and we'll cicle back to revisit it after we've
2622 // hopefully eliminated the second release, which may allow us to
2623 // eliminate the first release too.
2624 // Theoretically we could implement removal of nested retain+release
2625 // pairs by making PtrState hold a stack of states, but this is
2626 // simple and avoids adding overhead for the non-nested case.
2627 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2628 NestingDetected = true;
2630 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2631 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
2632 S.RRI.ReleaseMetadata = ReleaseMetadata;
2633 S.RRI.KnownSafe = S.IsKnownNested() || S.IsKnownIncremented();
2634 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2635 S.RRI.Calls.insert(Inst);
2637 S.IncrementNestCount();
2640 case IC_RetainBlock:
2641 // An objc_retainBlock call with just a use may need to be kept,
2642 // because it may be copying a block from the stack to the heap.
2643 if (!IsRetainBlockOptimizable(Inst))
2648 Arg = GetObjCArg(Inst);
2650 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2651 S.SetKnownPositiveRefCount();
2652 S.DecrementNestCount();
2654 switch (S.GetSeq()) {
2657 case S_MovableRelease:
2659 S.RRI.ReverseInsertPts.clear();
2662 // Don't do retain+release tracking for IC_RetainRV, because it's
2663 // better to let it remain as the first instruction after a call.
2664 if (Class != IC_RetainRV) {
2665 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2666 Retains[Inst] = S.RRI;
2668 S.ClearSequenceProgress();
2673 llvm_unreachable("bottom-up pointer in retain state!");
2675 return NestingDetected;
2677 case IC_AutoreleasepoolPop:
2678 // Conservatively, clear MyStates for all known pointers.
2679 MyStates.clearBottomUpPointers();
2680 return NestingDetected;
2681 case IC_AutoreleasepoolPush:
2683 // These are irrelevant.
2684 return NestingDetected;
2689 // Consider any other possible effects of this instruction on each
2690 // pointer being tracked.
2691 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2692 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2693 const Value *Ptr = MI->first;
2695 continue; // Handled above.
2696 PtrState &S = MI->second;
2697 Sequence Seq = S.GetSeq();
2699 // Check for possible releases.
2700 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2704 S.SetSeq(S_CanRelease);
2708 case S_MovableRelease:
2713 llvm_unreachable("bottom-up pointer in retain state!");
2717 // Check for possible direct uses.
2720 case S_MovableRelease:
2721 if (CanUse(Inst, Ptr, PA, Class)) {
2722 assert(S.RRI.ReverseInsertPts.empty());
2723 // If this is an invoke instruction, we're scanning it as part of
2724 // one of its successor blocks, since we can't insert code after it
2725 // in its own block, and we don't want to split critical edges.
2726 if (isa<InvokeInst>(Inst))
2727 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2729 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2731 } else if (Seq == S_Release &&
2732 (Class == IC_User || Class == IC_CallOrUser)) {
2733 // Non-movable releases depend on any possible objc pointer use.
2735 assert(S.RRI.ReverseInsertPts.empty());
2736 // As above; handle invoke specially.
2737 if (isa<InvokeInst>(Inst))
2738 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2740 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2744 if (CanUse(Inst, Ptr, PA, Class))
2752 llvm_unreachable("bottom-up pointer in retain state!");
2756 return NestingDetected;
2760 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2761 DenseMap<const BasicBlock *, BBState> &BBStates,
2762 MapVector<Value *, RRInfo> &Retains) {
2763 bool NestingDetected = false;
2764 BBState &MyStates = BBStates[BB];
2766 // Merge the states from each successor to compute the initial state
2767 // for the current block.
2768 for (BBState::edge_iterator SI(MyStates.succ_begin()),
2769 SE(MyStates.succ_end()); SI != SE; ++SI) {
2770 const BasicBlock *Succ = *SI;
2771 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2772 assert(I != BBStates.end());
2773 MyStates.InitFromSucc(I->second);
2775 for (; SI != SE; ++SI) {
2777 I = BBStates.find(Succ);
2778 assert(I != BBStates.end());
2779 MyStates.MergeSucc(I->second);
2784 // Visit all the instructions, bottom-up.
2785 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2786 Instruction *Inst = llvm::prior(I);
2788 // Invoke instructions are visited as part of their successors (below).
2789 if (isa<InvokeInst>(Inst))
2792 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2795 // If there's a predecessor with an invoke, visit the invoke as if it were
2796 // part of this block, since we can't insert code after an invoke in its own
2797 // block, and we don't want to split critical edges.
2798 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2799 PE(MyStates.pred_end()); PI != PE; ++PI) {
2800 BasicBlock *Pred = *PI;
2801 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2802 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
2805 return NestingDetected;
2809 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2810 DenseMap<Value *, RRInfo> &Releases,
2811 BBState &MyStates) {
2812 bool NestingDetected = false;
2813 InstructionClass Class = GetInstructionClass(Inst);
2814 const Value *Arg = 0;
2817 case IC_RetainBlock:
2818 // An objc_retainBlock call with just a use may need to be kept,
2819 // because it may be copying a block from the stack to the heap.
2820 if (!IsRetainBlockOptimizable(Inst))
2825 Arg = GetObjCArg(Inst);
2827 PtrState &S = MyStates.getPtrTopDownState(Arg);
2829 // Don't do retain+release tracking for IC_RetainRV, because it's
2830 // better to let it remain as the first instruction after a call.
2831 if (Class != IC_RetainRV) {
2832 // If we see two retains in a row on the same pointer. If so, make
2833 // a note, and we'll cicle back to revisit it after we've
2834 // hopefully eliminated the second retain, which may allow us to
2835 // eliminate the first retain too.
2836 // Theoretically we could implement removal of nested retain+release
2837 // pairs by making PtrState hold a stack of states, but this is
2838 // simple and avoids adding overhead for the non-nested case.
2839 if (S.GetSeq() == S_Retain)
2840 NestingDetected = true;
2842 S.ResetSequenceProgress(S_Retain);
2843 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2844 // Don't check S.IsKnownIncremented() here because it's not sufficient.
2845 S.RRI.KnownSafe = S.IsKnownNested();
2846 S.RRI.Calls.insert(Inst);
2849 S.IncrementNestCount();
2850 return NestingDetected;
2853 Arg = GetObjCArg(Inst);
2855 PtrState &S = MyStates.getPtrTopDownState(Arg);
2856 S.DecrementNestCount();
2858 switch (S.GetSeq()) {
2861 S.RRI.ReverseInsertPts.clear();
2864 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2865 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2866 Releases[Inst] = S.RRI;
2867 S.ClearSequenceProgress();
2873 case S_MovableRelease:
2874 llvm_unreachable("top-down pointer in release state!");
2878 case IC_AutoreleasepoolPop:
2879 // Conservatively, clear MyStates for all known pointers.
2880 MyStates.clearTopDownPointers();
2881 return NestingDetected;
2882 case IC_AutoreleasepoolPush:
2884 // These are irrelevant.
2885 return NestingDetected;
2890 // Consider any other possible effects of this instruction on each
2891 // pointer being tracked.
2892 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2893 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2894 const Value *Ptr = MI->first;
2896 continue; // Handled above.
2897 PtrState &S = MI->second;
2898 Sequence Seq = S.GetSeq();
2900 // Check for possible releases.
2901 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2905 S.SetSeq(S_CanRelease);
2906 assert(S.RRI.ReverseInsertPts.empty());
2907 S.RRI.ReverseInsertPts.insert(Inst);
2909 // One call can't cause a transition from S_Retain to S_CanRelease
2910 // and S_CanRelease to S_Use. If we've made the first transition,
2919 case S_MovableRelease:
2920 llvm_unreachable("top-down pointer in release state!");
2924 // Check for possible direct uses.
2927 if (CanUse(Inst, Ptr, PA, Class))
2936 case S_MovableRelease:
2937 llvm_unreachable("top-down pointer in release state!");
2941 return NestingDetected;
2945 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2946 DenseMap<const BasicBlock *, BBState> &BBStates,
2947 DenseMap<Value *, RRInfo> &Releases) {
2948 bool NestingDetected = false;
2949 BBState &MyStates = BBStates[BB];
2951 // Merge the states from each predecessor to compute the initial state
2952 // for the current block.
2953 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2954 PE(MyStates.pred_end()); PI != PE; ++PI) {
2955 const BasicBlock *Pred = *PI;
2956 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2957 assert(I != BBStates.end());
2958 MyStates.InitFromPred(I->second);
2960 for (; PI != PE; ++PI) {
2962 I = BBStates.find(Pred);
2963 assert(I != BBStates.end());
2964 MyStates.MergePred(I->second);
2969 // Visit all the instructions, top-down.
2970 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2971 Instruction *Inst = I;
2972 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
2975 CheckForCFGHazards(BB, BBStates, MyStates);
2976 return NestingDetected;
2980 ComputePostOrders(Function &F,
2981 SmallVectorImpl<BasicBlock *> &PostOrder,
2982 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
2983 unsigned NoObjCARCExceptionsMDKind,
2984 DenseMap<const BasicBlock *, BBState> &BBStates) {
2985 /// Visited - The visited set, for doing DFS walks.
2986 SmallPtrSet<BasicBlock *, 16> Visited;
2988 // Do DFS, computing the PostOrder.
2989 SmallPtrSet<BasicBlock *, 16> OnStack;
2990 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2992 // Functions always have exactly one entry block, and we don't have
2993 // any other block that we treat like an entry block.
2994 BasicBlock *EntryBB = &F.getEntryBlock();
2995 BBStates[EntryBB].SetAsEntry();
2997 SuccStack.push_back(std::make_pair(EntryBB, succ_begin(EntryBB)));
2998 Visited.insert(EntryBB);
2999 OnStack.insert(EntryBB);
3002 BasicBlock *CurrBB = SuccStack.back().first;
3003 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3004 succ_iterator SE(TI, false);
3006 // If the terminator is an invoke marked with the
3007 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
3008 // ignored, for ARC purposes.
3009 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
3012 while (SuccStack.back().second != SE) {
3013 BasicBlock *SuccBB = *SuccStack.back().second++;
3014 if (Visited.insert(SuccBB)) {
3015 SuccStack.push_back(std::make_pair(SuccBB, succ_begin(SuccBB)));
3016 BBStates[CurrBB].addSucc(SuccBB);
3017 BBStates[SuccBB].addPred(CurrBB);
3018 OnStack.insert(SuccBB);
3022 if (!OnStack.count(SuccBB)) {
3023 BBStates[CurrBB].addSucc(SuccBB);
3024 BBStates[SuccBB].addPred(CurrBB);
3027 OnStack.erase(CurrBB);
3028 PostOrder.push_back(CurrBB);
3029 SuccStack.pop_back();
3030 } while (!SuccStack.empty());
3034 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
3035 // Functions may have many exits, and there also blocks which we treat
3036 // as exits due to ignored edges.
3037 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3038 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3039 BasicBlock *ExitBB = I;
3040 BBState &MyStates = BBStates[ExitBB];
3041 if (!MyStates.isExit())
3044 MyStates.SetAsExit();
3046 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
3047 Visited.insert(ExitBB);
3048 while (!PredStack.empty()) {
3049 reverse_dfs_next_succ:
3050 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3051 while (PredStack.back().second != PE) {
3052 BasicBlock *BB = *PredStack.back().second++;
3053 if (Visited.insert(BB)) {
3054 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
3055 goto reverse_dfs_next_succ;
3058 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3063 // Visit - Visit the function both top-down and bottom-up.
3065 ObjCARCOpt::Visit(Function &F,
3066 DenseMap<const BasicBlock *, BBState> &BBStates,
3067 MapVector<Value *, RRInfo> &Retains,
3068 DenseMap<Value *, RRInfo> &Releases) {
3070 // Use reverse-postorder traversals, because we magically know that loops
3071 // will be well behaved, i.e. they won't repeatedly call retain on a single
3072 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3073 // class here because we want the reverse-CFG postorder to consider each
3074 // function exit point, and we want to ignore selected cycle edges.
3075 SmallVector<BasicBlock *, 16> PostOrder;
3076 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
3077 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3078 NoObjCARCExceptionsMDKind,
3081 // Use reverse-postorder on the reverse CFG for bottom-up.
3082 bool BottomUpNestingDetected = false;
3083 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3084 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3086 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
3088 // Use reverse-postorder for top-down.
3089 bool TopDownNestingDetected = false;
3090 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3091 PostOrder.rbegin(), E = PostOrder.rend();
3093 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
3095 return TopDownNestingDetected && BottomUpNestingDetected;
3098 /// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
3099 void ObjCARCOpt::MoveCalls(Value *Arg,
3100 RRInfo &RetainsToMove,
3101 RRInfo &ReleasesToMove,
3102 MapVector<Value *, RRInfo> &Retains,
3103 DenseMap<Value *, RRInfo> &Releases,
3104 SmallVectorImpl<Instruction *> &DeadInsts,
3106 Type *ArgTy = Arg->getType();
3107 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
3109 // Insert the new retain and release calls.
3110 for (SmallPtrSet<Instruction *, 2>::const_iterator
3111 PI = ReleasesToMove.ReverseInsertPts.begin(),
3112 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3113 Instruction *InsertPt = *PI;
3114 Value *MyArg = ArgTy == ParamTy ? Arg :
3115 new BitCastInst(Arg, ParamTy, "", InsertPt);
3117 CallInst::Create(RetainsToMove.IsRetainBlock ?
3118 getRetainBlockCallee(M) : getRetainCallee(M),
3119 MyArg, "", InsertPt);
3120 Call->setDoesNotThrow();
3121 if (RetainsToMove.IsRetainBlock)
3122 Call->setMetadata(CopyOnEscapeMDKind,
3123 MDNode::get(M->getContext(), ArrayRef<Value *>()));
3125 Call->setTailCall();
3127 for (SmallPtrSet<Instruction *, 2>::const_iterator
3128 PI = RetainsToMove.ReverseInsertPts.begin(),
3129 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3130 Instruction *InsertPt = *PI;
3131 Value *MyArg = ArgTy == ParamTy ? Arg :
3132 new BitCastInst(Arg, ParamTy, "", InsertPt);
3133 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3135 // Attach a clang.imprecise_release metadata tag, if appropriate.
3136 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3137 Call->setMetadata(ImpreciseReleaseMDKind, M);
3138 Call->setDoesNotThrow();
3139 if (ReleasesToMove.IsTailCallRelease)
3140 Call->setTailCall();
3143 // Delete the original retain and release calls.
3144 for (SmallPtrSet<Instruction *, 2>::const_iterator
3145 AI = RetainsToMove.Calls.begin(),
3146 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3147 Instruction *OrigRetain = *AI;
3148 Retains.blot(OrigRetain);
3149 DeadInsts.push_back(OrigRetain);
3151 for (SmallPtrSet<Instruction *, 2>::const_iterator
3152 AI = ReleasesToMove.Calls.begin(),
3153 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3154 Instruction *OrigRelease = *AI;
3155 Releases.erase(OrigRelease);
3156 DeadInsts.push_back(OrigRelease);
3160 /// PerformCodePlacement - Identify pairings between the retains and releases,
3161 /// and delete and/or move them.
3163 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3165 MapVector<Value *, RRInfo> &Retains,
3166 DenseMap<Value *, RRInfo> &Releases,
3168 bool AnyPairsCompletelyEliminated = false;
3169 RRInfo RetainsToMove;
3170 RRInfo ReleasesToMove;
3171 SmallVector<Instruction *, 4> NewRetains;
3172 SmallVector<Instruction *, 4> NewReleases;
3173 SmallVector<Instruction *, 8> DeadInsts;
3175 // Visit each retain.
3176 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
3177 E = Retains.end(); I != E; ++I) {
3178 Value *V = I->first;
3179 if (!V) continue; // blotted
3181 Instruction *Retain = cast<Instruction>(V);
3182 Value *Arg = GetObjCArg(Retain);
3184 // If the object being released is in static or stack storage, we know it's
3185 // not being managed by ObjC reference counting, so we can delete pairs
3186 // regardless of what possible decrements or uses lie between them.
3187 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
3189 // A constant pointer can't be pointing to an object on the heap. It may
3190 // be reference-counted, but it won't be deleted.
3191 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3192 if (const GlobalVariable *GV =
3193 dyn_cast<GlobalVariable>(
3194 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3195 if (GV->isConstant())
3198 // If a pair happens in a region where it is known that the reference count
3199 // is already incremented, we can similarly ignore possible decrements.
3200 bool KnownSafeTD = true, KnownSafeBU = true;
3202 // Connect the dots between the top-down-collected RetainsToMove and
3203 // bottom-up-collected ReleasesToMove to form sets of related calls.
3204 // This is an iterative process so that we connect multiple releases
3205 // to multiple retains if needed.
3206 unsigned OldDelta = 0;
3207 unsigned NewDelta = 0;
3208 unsigned OldCount = 0;
3209 unsigned NewCount = 0;
3210 bool FirstRelease = true;
3211 bool FirstRetain = true;
3212 NewRetains.push_back(Retain);
3214 for (SmallVectorImpl<Instruction *>::const_iterator
3215 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3216 Instruction *NewRetain = *NI;
3217 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3218 assert(It != Retains.end());
3219 const RRInfo &NewRetainRRI = It->second;
3220 KnownSafeTD &= NewRetainRRI.KnownSafe;
3221 for (SmallPtrSet<Instruction *, 2>::const_iterator
3222 LI = NewRetainRRI.Calls.begin(),
3223 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3224 Instruction *NewRetainRelease = *LI;
3225 DenseMap<Value *, RRInfo>::const_iterator Jt =
3226 Releases.find(NewRetainRelease);
3227 if (Jt == Releases.end())
3229 const RRInfo &NewRetainReleaseRRI = Jt->second;
3230 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3231 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3233 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3235 // Merge the ReleaseMetadata and IsTailCallRelease values.
3237 ReleasesToMove.ReleaseMetadata =
3238 NewRetainReleaseRRI.ReleaseMetadata;
3239 ReleasesToMove.IsTailCallRelease =
3240 NewRetainReleaseRRI.IsTailCallRelease;
3241 FirstRelease = false;
3243 if (ReleasesToMove.ReleaseMetadata !=
3244 NewRetainReleaseRRI.ReleaseMetadata)
3245 ReleasesToMove.ReleaseMetadata = 0;
3246 if (ReleasesToMove.IsTailCallRelease !=
3247 NewRetainReleaseRRI.IsTailCallRelease)
3248 ReleasesToMove.IsTailCallRelease = false;
3251 // Collect the optimal insertion points.
3253 for (SmallPtrSet<Instruction *, 2>::const_iterator
3254 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3255 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3257 Instruction *RIP = *RI;
3258 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3259 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3261 NewReleases.push_back(NewRetainRelease);
3266 if (NewReleases.empty()) break;
3268 // Back the other way.
3269 for (SmallVectorImpl<Instruction *>::const_iterator
3270 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3271 Instruction *NewRelease = *NI;
3272 DenseMap<Value *, RRInfo>::const_iterator It =
3273 Releases.find(NewRelease);
3274 assert(It != Releases.end());
3275 const RRInfo &NewReleaseRRI = It->second;
3276 KnownSafeBU &= NewReleaseRRI.KnownSafe;
3277 for (SmallPtrSet<Instruction *, 2>::const_iterator
3278 LI = NewReleaseRRI.Calls.begin(),
3279 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3280 Instruction *NewReleaseRetain = *LI;
3281 MapVector<Value *, RRInfo>::const_iterator Jt =
3282 Retains.find(NewReleaseRetain);
3283 if (Jt == Retains.end())
3285 const RRInfo &NewReleaseRetainRRI = Jt->second;
3286 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3287 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3288 unsigned PathCount =
3289 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3290 OldDelta += PathCount;
3291 OldCount += PathCount;
3293 // Merge the IsRetainBlock values.
3295 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3296 FirstRetain = false;
3297 } else if (ReleasesToMove.IsRetainBlock !=
3298 NewReleaseRetainRRI.IsRetainBlock)
3299 // It's not possible to merge the sequences if one uses
3300 // objc_retain and the other uses objc_retainBlock.
3303 // Collect the optimal insertion points.
3305 for (SmallPtrSet<Instruction *, 2>::const_iterator
3306 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3307 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3309 Instruction *RIP = *RI;
3310 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3311 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3312 NewDelta += PathCount;
3313 NewCount += PathCount;
3316 NewRetains.push_back(NewReleaseRetain);
3320 NewReleases.clear();
3321 if (NewRetains.empty()) break;
3324 // If the pointer is known incremented or nested, we can safely delete the
3325 // pair regardless of what's between them.
3326 if (KnownSafeTD || KnownSafeBU) {
3327 RetainsToMove.ReverseInsertPts.clear();
3328 ReleasesToMove.ReverseInsertPts.clear();
3331 // Determine whether the new insertion points we computed preserve the
3332 // balance of retain and release calls through the program.
3333 // TODO: If the fully aggressive solution isn't valid, try to find a
3334 // less aggressive solution which is.
3339 // Determine whether the original call points are balanced in the retain and
3340 // release calls through the program. If not, conservatively don't touch
3342 // TODO: It's theoretically possible to do code motion in this case, as
3343 // long as the existing imbalances are maintained.
3347 // Ok, everything checks out and we're all set. Let's move some code!
3349 assert(OldCount != 0 && "Unreachable code?");
3350 AnyPairsCompletelyEliminated = NewCount == 0;
3351 NumRRs += OldCount - NewCount;
3352 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3353 Retains, Releases, DeadInsts, M);
3356 NewReleases.clear();
3358 RetainsToMove.clear();
3359 ReleasesToMove.clear();
3362 // Now that we're done moving everything, we can delete the newly dead
3363 // instructions, as we no longer need them as insert points.
3364 while (!DeadInsts.empty())
3365 EraseInstruction(DeadInsts.pop_back_val());
3367 return AnyPairsCompletelyEliminated;
3370 /// OptimizeWeakCalls - Weak pointer optimizations.
3371 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3372 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3373 // itself because it uses AliasAnalysis and we need to do provenance
3375 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3376 Instruction *Inst = &*I++;
3377 InstructionClass Class = GetBasicInstructionClass(Inst);
3378 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3381 // Delete objc_loadWeak calls with no users.
3382 if (Class == IC_LoadWeak && Inst->use_empty()) {
3383 Inst->eraseFromParent();
3387 // TODO: For now, just look for an earlier available version of this value
3388 // within the same block. Theoretically, we could do memdep-style non-local
3389 // analysis too, but that would want caching. A better approach would be to
3390 // use the technique that EarlyCSE uses.
3391 inst_iterator Current = llvm::prior(I);
3392 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3393 for (BasicBlock::iterator B = CurrentBB->begin(),
3394 J = Current.getInstructionIterator();
3396 Instruction *EarlierInst = &*llvm::prior(J);
3397 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3398 switch (EarlierClass) {
3400 case IC_LoadWeakRetained: {
3401 // If this is loading from the same pointer, replace this load's value
3403 CallInst *Call = cast<CallInst>(Inst);
3404 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3405 Value *Arg = Call->getArgOperand(0);
3406 Value *EarlierArg = EarlierCall->getArgOperand(0);
3407 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3408 case AliasAnalysis::MustAlias:
3410 // If the load has a builtin retain, insert a plain retain for it.
3411 if (Class == IC_LoadWeakRetained) {
3413 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3417 // Zap the fully redundant load.
3418 Call->replaceAllUsesWith(EarlierCall);
3419 Call->eraseFromParent();
3421 case AliasAnalysis::MayAlias:
3422 case AliasAnalysis::PartialAlias:
3424 case AliasAnalysis::NoAlias:
3431 // If this is storing to the same pointer and has the same size etc.
3432 // replace this load's value with the stored value.
3433 CallInst *Call = cast<CallInst>(Inst);
3434 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3435 Value *Arg = Call->getArgOperand(0);
3436 Value *EarlierArg = EarlierCall->getArgOperand(0);
3437 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3438 case AliasAnalysis::MustAlias:
3440 // If the load has a builtin retain, insert a plain retain for it.
3441 if (Class == IC_LoadWeakRetained) {
3443 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3447 // Zap the fully redundant load.
3448 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3449 Call->eraseFromParent();
3451 case AliasAnalysis::MayAlias:
3452 case AliasAnalysis::PartialAlias:
3454 case AliasAnalysis::NoAlias:
3461 // TOOD: Grab the copied value.
3463 case IC_AutoreleasepoolPush:
3466 // Weak pointers are only modified through the weak entry points
3467 // (and arbitrary calls, which could call the weak entry points).
3470 // Anything else could modify the weak pointer.
3477 // Then, for each destroyWeak with an alloca operand, check to see if
3478 // the alloca and all its users can be zapped.
3479 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3480 Instruction *Inst = &*I++;
3481 InstructionClass Class = GetBasicInstructionClass(Inst);
3482 if (Class != IC_DestroyWeak)
3485 CallInst *Call = cast<CallInst>(Inst);
3486 Value *Arg = Call->getArgOperand(0);
3487 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3488 for (Value::use_iterator UI = Alloca->use_begin(),
3489 UE = Alloca->use_end(); UI != UE; ++UI) {
3490 const Instruction *UserInst = cast<Instruction>(*UI);
3491 switch (GetBasicInstructionClass(UserInst)) {
3494 case IC_DestroyWeak:
3501 for (Value::use_iterator UI = Alloca->use_begin(),
3502 UE = Alloca->use_end(); UI != UE; ) {
3503 CallInst *UserInst = cast<CallInst>(*UI++);
3504 if (!UserInst->use_empty())
3505 UserInst->replaceAllUsesWith(UserInst->getArgOperand(0));
3506 UserInst->eraseFromParent();
3508 Alloca->eraseFromParent();
3514 /// OptimizeSequences - Identify program paths which execute sequences of
3515 /// retains and releases which can be eliminated.
3516 bool ObjCARCOpt::OptimizeSequences(Function &F) {
3517 /// Releases, Retains - These are used to store the results of the main flow
3518 /// analysis. These use Value* as the key instead of Instruction* so that the
3519 /// map stays valid when we get around to rewriting code and calls get
3520 /// replaced by arguments.
3521 DenseMap<Value *, RRInfo> Releases;
3522 MapVector<Value *, RRInfo> Retains;
3524 /// BBStates, This is used during the traversal of the function to track the
3525 /// states for each identified object at each block.
3526 DenseMap<const BasicBlock *, BBState> BBStates;
3528 // Analyze the CFG of the function, and all instructions.
3529 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3532 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3536 /// OptimizeReturns - Look for this pattern:
3538 /// %call = call i8* @something(...)
3539 /// %2 = call i8* @objc_retain(i8* %call)
3540 /// %3 = call i8* @objc_autorelease(i8* %2)
3543 /// And delete the retain and autorelease.
3545 /// Otherwise if it's just this:
3547 /// %3 = call i8* @objc_autorelease(i8* %2)
3550 /// convert the autorelease to autoreleaseRV.
3551 void ObjCARCOpt::OptimizeReturns(Function &F) {
3552 if (!F.getReturnType()->isPointerTy())
3555 SmallPtrSet<Instruction *, 4> DependingInstructions;
3556 SmallPtrSet<const BasicBlock *, 4> Visited;
3557 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3558 BasicBlock *BB = FI;
3559 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3562 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3563 FindDependencies(NeedsPositiveRetainCount, Arg,
3564 BB, Ret, DependingInstructions, Visited, PA);
3565 if (DependingInstructions.size() != 1)
3569 CallInst *Autorelease =
3570 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3573 InstructionClass AutoreleaseClass =
3574 GetBasicInstructionClass(Autorelease);
3575 if (!IsAutorelease(AutoreleaseClass))
3577 if (GetObjCArg(Autorelease) != Arg)
3580 DependingInstructions.clear();
3583 // Check that there is nothing that can affect the reference
3584 // count between the autorelease and the retain.
3585 FindDependencies(CanChangeRetainCount, Arg,
3586 BB, Autorelease, DependingInstructions, Visited, PA);
3587 if (DependingInstructions.size() != 1)
3592 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3594 // Check that we found a retain with the same argument.
3596 !IsRetain(GetBasicInstructionClass(Retain)) ||
3597 GetObjCArg(Retain) != Arg)
3600 DependingInstructions.clear();
3603 // Convert the autorelease to an autoreleaseRV, since it's
3604 // returning the value.
3605 if (AutoreleaseClass == IC_Autorelease) {
3606 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3607 AutoreleaseClass = IC_AutoreleaseRV;
3610 // Check that there is nothing that can affect the reference
3611 // count between the retain and the call.
3612 // Note that Retain need not be in BB.
3613 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3614 DependingInstructions, Visited, PA);
3615 if (DependingInstructions.size() != 1)
3620 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3622 // Check that the pointer is the return value of the call.
3623 if (!Call || Arg != Call)
3626 // Check that the call is a regular call.
3627 InstructionClass Class = GetBasicInstructionClass(Call);
3628 if (Class != IC_CallOrUser && Class != IC_Call)
3631 // If so, we can zap the retain and autorelease.
3634 EraseInstruction(Retain);
3635 EraseInstruction(Autorelease);
3641 DependingInstructions.clear();
3646 bool ObjCARCOpt::doInitialization(Module &M) {
3650 // If nothing in the Module uses ARC, don't do anything.
3651 Run = ModuleHasARC(M);
3655 // Identify the imprecise release metadata kind.
3656 ImpreciseReleaseMDKind =
3657 M.getContext().getMDKindID("clang.imprecise_release");
3658 CopyOnEscapeMDKind =
3659 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3660 NoObjCARCExceptionsMDKind =
3661 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3663 // Intuitively, objc_retain and others are nocapture, however in practice
3664 // they are not, because they return their argument value. And objc_release
3665 // calls finalizers which can have arbitrary side effects.
3667 // These are initialized lazily.
3669 AutoreleaseRVCallee = 0;
3672 RetainBlockCallee = 0;
3673 AutoreleaseCallee = 0;
3678 bool ObjCARCOpt::runOnFunction(Function &F) {
3682 // If nothing in the Module uses ARC, don't do anything.
3688 PA.setAA(&getAnalysis<AliasAnalysis>());
3690 // This pass performs several distinct transformations. As a compile-time aid
3691 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3692 // library functions aren't declared.
3694 // Preliminary optimizations. This also computs UsedInThisFunction.
3695 OptimizeIndividualCalls(F);
3697 // Optimizations for weak pointers.
3698 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3699 (1 << IC_LoadWeakRetained) |
3700 (1 << IC_StoreWeak) |
3701 (1 << IC_InitWeak) |
3702 (1 << IC_CopyWeak) |
3703 (1 << IC_MoveWeak) |
3704 (1 << IC_DestroyWeak)))
3705 OptimizeWeakCalls(F);
3707 // Optimizations for retain+release pairs.
3708 if (UsedInThisFunction & ((1 << IC_Retain) |
3709 (1 << IC_RetainRV) |
3710 (1 << IC_RetainBlock)))
3711 if (UsedInThisFunction & (1 << IC_Release))
3712 // Run OptimizeSequences until it either stops making changes or
3713 // no retain+release pair nesting is detected.
3714 while (OptimizeSequences(F)) {}
3716 // Optimizations if objc_autorelease is used.
3717 if (UsedInThisFunction &
3718 ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
3724 void ObjCARCOpt::releaseMemory() {
3728 //===----------------------------------------------------------------------===//
3730 //===----------------------------------------------------------------------===//
3732 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
3733 // dominated by single calls.
3735 #include "llvm/Operator.h"
3736 #include "llvm/InlineAsm.h"
3737 #include "llvm/Analysis/Dominators.h"
3739 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3742 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3743 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3744 class ObjCARCContract : public FunctionPass {
3748 ProvenanceAnalysis PA;
3750 /// Run - A flag indicating whether this optimization pass should run.
3753 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3754 /// functions, for use in creating calls to them. These are initialized
3755 /// lazily to avoid cluttering up the Module with unused declarations.
3756 Constant *StoreStrongCallee,
3757 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3759 /// RetainRVMarker - The inline asm string to insert between calls and
3760 /// RetainRV calls to make the optimization work on targets which need it.
3761 const MDString *RetainRVMarker;
3763 /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
3764 /// at the end of walking the function we have found no alloca
3765 /// instructions, these calls can be marked "tail".
3766 DenseSet<CallInst *> StoreStrongCalls;
3768 Constant *getStoreStrongCallee(Module *M);
3769 Constant *getRetainAutoreleaseCallee(Module *M);
3770 Constant *getRetainAutoreleaseRVCallee(Module *M);
3772 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3773 InstructionClass Class,
3774 SmallPtrSet<Instruction *, 4>
3775 &DependingInstructions,
3776 SmallPtrSet<const BasicBlock *, 4>
3779 void ContractRelease(Instruction *Release,
3780 inst_iterator &Iter);
3782 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3783 virtual bool doInitialization(Module &M);
3784 virtual bool runOnFunction(Function &F);
3788 ObjCARCContract() : FunctionPass(ID) {
3789 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3794 char ObjCARCContract::ID = 0;
3795 INITIALIZE_PASS_BEGIN(ObjCARCContract,
3796 "objc-arc-contract", "ObjC ARC contraction", false, false)
3797 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3798 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3799 INITIALIZE_PASS_END(ObjCARCContract,
3800 "objc-arc-contract", "ObjC ARC contraction", false, false)
3802 Pass *llvm::createObjCARCContractPass() {
3803 return new ObjCARCContract();
3806 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3807 AU.addRequired<AliasAnalysis>();
3808 AU.addRequired<DominatorTree>();
3809 AU.setPreservesCFG();
3812 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3813 if (!StoreStrongCallee) {
3814 LLVMContext &C = M->getContext();
3815 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3816 Type *I8XX = PointerType::getUnqual(I8X);
3817 std::vector<Type *> Params;
3818 Params.push_back(I8XX);
3819 Params.push_back(I8X);
3821 AttrListPtr Attributes;
3822 Attributes.addAttr(~0u, Attribute::NoUnwind);
3823 Attributes.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 std::vector<Type *> Params;
3839 Params.push_back(I8X);
3841 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3842 AttrListPtr Attributes;
3843 Attributes.addAttr(~0u, Attribute::NoUnwind);
3844 RetainAutoreleaseCallee =
3845 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3847 return RetainAutoreleaseCallee;
3850 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3851 if (!RetainAutoreleaseRVCallee) {
3852 LLVMContext &C = M->getContext();
3853 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3854 std::vector<Type *> Params;
3855 Params.push_back(I8X);
3857 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3858 AttrListPtr Attributes;
3859 Attributes.addAttr(~0u, Attribute::NoUnwind);
3860 RetainAutoreleaseRVCallee =
3861 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3864 return RetainAutoreleaseRVCallee;
3867 /// ContractAutorelease - Merge an autorelease with a retain into a fused call.
3869 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3870 InstructionClass Class,
3871 SmallPtrSet<Instruction *, 4>
3872 &DependingInstructions,
3873 SmallPtrSet<const BasicBlock *, 4>
3875 const Value *Arg = GetObjCArg(Autorelease);
3877 // Check that there are no instructions between the retain and the autorelease
3878 // (such as an autorelease_pop) which may change the count.
3879 CallInst *Retain = 0;
3880 if (Class == IC_AutoreleaseRV)
3881 FindDependencies(RetainAutoreleaseRVDep, Arg,
3882 Autorelease->getParent(), Autorelease,
3883 DependingInstructions, Visited, PA);
3885 FindDependencies(RetainAutoreleaseDep, Arg,
3886 Autorelease->getParent(), Autorelease,
3887 DependingInstructions, Visited, PA);
3890 if (DependingInstructions.size() != 1) {
3891 DependingInstructions.clear();
3895 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3896 DependingInstructions.clear();
3899 GetBasicInstructionClass(Retain) != IC_Retain ||
3900 GetObjCArg(Retain) != Arg)
3906 if (Class == IC_AutoreleaseRV)
3907 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3909 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3911 EraseInstruction(Autorelease);
3915 /// ContractRelease - Attempt to merge an objc_release with a store, load, and
3916 /// objc_retain to form an objc_storeStrong. This can be a little tricky because
3917 /// the instructions don't always appear in order, and there may be unrelated
3918 /// intervening instructions.
3919 void ObjCARCContract::ContractRelease(Instruction *Release,
3920 inst_iterator &Iter) {
3921 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
3922 if (!Load || !Load->isSimple()) return;
3924 // For now, require everything to be in one basic block.
3925 BasicBlock *BB = Release->getParent();
3926 if (Load->getParent() != BB) return;
3928 // Walk down to find the store.
3929 BasicBlock::iterator I = Load, End = BB->end();
3931 AliasAnalysis::Location Loc = AA->getLocation(Load);
3934 IsRetain(GetBasicInstructionClass(I)) ||
3935 !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
3937 StoreInst *Store = dyn_cast<StoreInst>(I);
3938 if (!Store || !Store->isSimple()) return;
3939 if (Store->getPointerOperand() != Loc.Ptr) return;
3941 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3943 // Walk up to find the retain.
3945 BasicBlock::iterator Begin = BB->begin();
3946 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3948 Instruction *Retain = I;
3949 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3950 if (GetObjCArg(Retain) != New) return;
3955 LLVMContext &C = Release->getContext();
3956 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3957 Type *I8XX = PointerType::getUnqual(I8X);
3959 Value *Args[] = { Load->getPointerOperand(), New };
3960 if (Args[0]->getType() != I8XX)
3961 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3962 if (Args[1]->getType() != I8X)
3963 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3964 CallInst *StoreStrong =
3965 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
3967 StoreStrong->setDoesNotThrow();
3968 StoreStrong->setDebugLoc(Store->getDebugLoc());
3970 // We can't set the tail flag yet, because we haven't yet determined
3971 // whether there are any escaping allocas. Remember this call, so that
3972 // we can set the tail flag once we know it's safe.
3973 StoreStrongCalls.insert(StoreStrong);
3975 if (&*Iter == Store) ++Iter;
3976 Store->eraseFromParent();
3977 Release->eraseFromParent();
3978 EraseInstruction(Retain);
3979 if (Load->use_empty())
3980 Load->eraseFromParent();
3983 bool ObjCARCContract::doInitialization(Module &M) {
3984 // If nothing in the Module uses ARC, don't do anything.
3985 Run = ModuleHasARC(M);
3989 // These are initialized lazily.
3990 StoreStrongCallee = 0;
3991 RetainAutoreleaseCallee = 0;
3992 RetainAutoreleaseRVCallee = 0;
3994 // Initialize RetainRVMarker.
3996 if (NamedMDNode *NMD =
3997 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3998 if (NMD->getNumOperands() == 1) {
3999 const MDNode *N = NMD->getOperand(0);
4000 if (N->getNumOperands() == 1)
4001 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4008 bool ObjCARCContract::runOnFunction(Function &F) {
4012 // If nothing in the Module uses ARC, don't do anything.
4017 AA = &getAnalysis<AliasAnalysis>();
4018 DT = &getAnalysis<DominatorTree>();
4020 PA.setAA(&getAnalysis<AliasAnalysis>());
4022 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4023 // keyword. Be conservative if the function has variadic arguments.
4024 // It seems that functions which "return twice" are also unsafe for the
4025 // "tail" argument, because they are setjmp, which could need to
4026 // return to an earlier stack state.
4027 bool TailOkForStoreStrongs = !F.isVarArg() && !F.callsFunctionThatReturnsTwice();
4029 // For ObjC library calls which return their argument, replace uses of the
4030 // argument with uses of the call return value, if it dominates the use. This
4031 // reduces register pressure.
4032 SmallPtrSet<Instruction *, 4> DependingInstructions;
4033 SmallPtrSet<const BasicBlock *, 4> Visited;
4034 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4035 Instruction *Inst = &*I++;
4037 // Only these library routines return their argument. In particular,
4038 // objc_retainBlock does not necessarily return its argument.
4039 InstructionClass Class = GetBasicInstructionClass(Inst);
4042 case IC_FusedRetainAutorelease:
4043 case IC_FusedRetainAutoreleaseRV:
4045 case IC_Autorelease:
4046 case IC_AutoreleaseRV:
4047 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4051 // If we're compiling for a target which needs a special inline-asm
4052 // marker to do the retainAutoreleasedReturnValue optimization,
4054 if (!RetainRVMarker)
4056 BasicBlock::iterator BBI = Inst;
4058 while (isNoopInstruction(BBI)) --BBI;
4059 if (&*BBI == GetObjCArg(Inst)) {
4062 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4063 /*isVarArg=*/false),
4064 RetainRVMarker->getString(),
4065 /*Constraints=*/"", /*hasSideEffects=*/true);
4066 CallInst::Create(IA, "", Inst);
4071 // objc_initWeak(p, null) => *p = null
4072 CallInst *CI = cast<CallInst>(Inst);
4073 if (isNullOrUndef(CI->getArgOperand(1))) {
4075 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4077 new StoreInst(Null, CI->getArgOperand(0), CI);
4078 CI->replaceAllUsesWith(Null);
4079 CI->eraseFromParent();
4084 ContractRelease(Inst, I);
4087 // Be conservative if the function has any alloca instructions.
4088 // Technically we only care about escaping alloca instructions,
4089 // but this is sufficient to handle some interesting cases.
4090 if (isa<AllocaInst>(Inst))
4091 TailOkForStoreStrongs = false;
4097 // Don't use GetObjCArg because we don't want to look through bitcasts
4098 // and such; to do the replacement, the argument must have type i8*.
4099 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4101 // If we're compiling bugpointed code, don't get in trouble.
4102 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4104 // Look through the uses of the pointer.
4105 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4107 Use &U = UI.getUse();
4108 unsigned OperandNo = UI.getOperandNo();
4109 ++UI; // Increment UI now, because we may unlink its element.
4111 // If the call's return value dominates a use of the call's argument
4112 // value, rewrite the use to use the return value. We check for
4113 // reachability here because an unreachable call is considered to
4114 // trivially dominate itself, which would lead us to rewriting its
4115 // argument in terms of its return value, which would lead to
4116 // infinite loops in GetObjCArg.
4117 if (DT->isReachableFromEntry(U) &&
4118 DT->dominates(Inst, U)) {
4120 Instruction *Replacement = Inst;
4121 Type *UseTy = U.get()->getType();
4122 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
4123 // For PHI nodes, insert the bitcast in the predecessor block.
4125 PHINode::getIncomingValueNumForOperand(OperandNo);
4127 PHI->getIncomingBlock(ValNo);
4128 if (Replacement->getType() != UseTy)
4129 Replacement = new BitCastInst(Replacement, UseTy, "",
4131 // While we're here, rewrite all edges for this PHI, rather
4132 // than just one use at a time, to minimize the number of
4133 // bitcasts we emit.
4134 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4135 if (PHI->getIncomingBlock(i) == BB) {
4136 // Keep the UI iterator valid.
4137 if (&PHI->getOperandUse(
4138 PHINode::getOperandNumForIncomingValue(i)) ==
4141 PHI->setIncomingValue(i, Replacement);
4144 if (Replacement->getType() != UseTy)
4145 Replacement = new BitCastInst(Replacement, UseTy, "",
4146 cast<Instruction>(U.getUser()));
4152 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
4153 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4154 Arg = BI->getOperand(0);
4155 else if (isa<GEPOperator>(Arg) &&
4156 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4157 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4158 else if (isa<GlobalAlias>(Arg) &&
4159 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4160 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4166 // If this function has no escaping allocas or suspicious vararg usage,
4167 // objc_storeStrong calls can be marked with the "tail" keyword.
4168 if (TailOkForStoreStrongs)
4169 for (DenseSet<CallInst *>::iterator I = StoreStrongCalls.begin(),
4170 E = StoreStrongCalls.end(); I != E; ++I)
4171 (*I)->setTailCall();
4172 StoreStrongCalls.clear();