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[](KeyT Arg) {
92 std::pair<typename MapTy::iterator, bool> Pair =
93 Map.insert(std::make_pair(Arg, size_t(0)));
95 Pair.first->second = Vector.size();
96 Vector.push_back(std::make_pair(Arg, ValueT()));
97 return Vector.back().second;
99 return Vector[Pair.first->second].second;
102 std::pair<iterator, bool>
103 insert(const std::pair<KeyT, ValueT> &InsertPair) {
104 std::pair<typename MapTy::iterator, bool> Pair =
105 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
107 Pair.first->second = Vector.size();
108 Vector.push_back(InsertPair);
109 return std::make_pair(llvm::prior(Vector.end()), true);
111 return std::make_pair(Vector.begin() + Pair.first->second, false);
114 const_iterator find(KeyT Key) const {
115 typename MapTy::const_iterator It = Map.find(Key);
116 if (It == Map.end()) return Vector.end();
117 return Vector.begin() + It->second;
120 /// blot - This is similar to erase, but instead of removing the element
121 /// from the vector, it just zeros out the key in the vector. This leaves
122 /// iterators intact, but clients must be prepared for zeroed-out keys when
124 void blot(KeyT Key) {
125 typename MapTy::iterator It = Map.find(Key);
126 if (It == Map.end()) return;
127 Vector[It->second].first = KeyT();
138 //===----------------------------------------------------------------------===//
140 //===----------------------------------------------------------------------===//
143 /// InstructionClass - A simple classification for instructions.
144 enum InstructionClass {
145 IC_Retain, ///< objc_retain
146 IC_RetainRV, ///< objc_retainAutoreleasedReturnValue
147 IC_RetainBlock, ///< objc_retainBlock
148 IC_Release, ///< objc_release
149 IC_Autorelease, ///< objc_autorelease
150 IC_AutoreleaseRV, ///< objc_autoreleaseReturnValue
151 IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
152 IC_AutoreleasepoolPop, ///< objc_autoreleasePoolPop
153 IC_NoopCast, ///< objc_retainedObject, etc.
154 IC_FusedRetainAutorelease, ///< objc_retainAutorelease
155 IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
156 IC_LoadWeakRetained, ///< objc_loadWeakRetained (primitive)
157 IC_StoreWeak, ///< objc_storeWeak (primitive)
158 IC_InitWeak, ///< objc_initWeak (derived)
159 IC_LoadWeak, ///< objc_loadWeak (derived)
160 IC_MoveWeak, ///< objc_moveWeak (derived)
161 IC_CopyWeak, ///< objc_copyWeak (derived)
162 IC_DestroyWeak, ///< objc_destroyWeak (derived)
163 IC_CallOrUser, ///< could call objc_release and/or "use" pointers
164 IC_Call, ///< could call objc_release
165 IC_User, ///< could "use" a pointer
166 IC_None ///< anything else
170 /// IsPotentialUse - Test whether the given value is possible a
171 /// reference-counted pointer.
172 static bool IsPotentialUse(const Value *Op) {
173 // Pointers to static or stack storage are not reference-counted pointers.
174 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
176 // Special arguments are not reference-counted.
177 if (const Argument *Arg = dyn_cast<Argument>(Op))
178 if (Arg->hasByValAttr() ||
179 Arg->hasNestAttr() ||
180 Arg->hasStructRetAttr())
182 // Only consider values with pointer types.
183 // It seemes intuitive to exclude function pointer types as well, since
184 // functions are never reference-counted, however clang occasionally
185 // bitcasts reference-counted pointers to function-pointer type
187 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
190 // Conservatively assume anything else is a potential use.
194 /// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind
195 /// of construct CS is.
196 static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
197 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
199 if (IsPotentialUse(*I))
200 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
202 return CS.onlyReadsMemory() ? IC_None : IC_Call;
205 /// GetFunctionClass - Determine if F is one of the special known Functions.
206 /// If it isn't, return IC_CallOrUser.
207 static InstructionClass GetFunctionClass(const Function *F) {
208 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
212 return StringSwitch<InstructionClass>(F->getName())
213 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
214 .Default(IC_CallOrUser);
217 const Argument *A0 = AI++;
219 // Argument is a pointer.
220 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
221 Type *ETy = PTy->getElementType();
223 if (ETy->isIntegerTy(8))
224 return StringSwitch<InstructionClass>(F->getName())
225 .Case("objc_retain", IC_Retain)
226 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
227 .Case("objc_retainBlock", IC_RetainBlock)
228 .Case("objc_release", IC_Release)
229 .Case("objc_autorelease", IC_Autorelease)
230 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
231 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
232 .Case("objc_retainedObject", IC_NoopCast)
233 .Case("objc_unretainedObject", IC_NoopCast)
234 .Case("objc_unretainedPointer", IC_NoopCast)
235 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
236 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
237 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
238 .Default(IC_CallOrUser);
241 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
242 if (Pte->getElementType()->isIntegerTy(8))
243 return StringSwitch<InstructionClass>(F->getName())
244 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
245 .Case("objc_loadWeak", IC_LoadWeak)
246 .Case("objc_destroyWeak", IC_DestroyWeak)
247 .Default(IC_CallOrUser);
250 // Two arguments, first is i8**.
251 const Argument *A1 = AI++;
253 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
254 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
255 if (Pte->getElementType()->isIntegerTy(8))
256 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
257 Type *ETy1 = PTy1->getElementType();
258 // Second argument is i8*
259 if (ETy1->isIntegerTy(8))
260 return StringSwitch<InstructionClass>(F->getName())
261 .Case("objc_storeWeak", IC_StoreWeak)
262 .Case("objc_initWeak", IC_InitWeak)
263 .Default(IC_CallOrUser);
264 // Second argument is i8**.
265 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
266 if (Pte1->getElementType()->isIntegerTy(8))
267 return StringSwitch<InstructionClass>(F->getName())
268 .Case("objc_moveWeak", IC_MoveWeak)
269 .Case("objc_copyWeak", IC_CopyWeak)
270 .Default(IC_CallOrUser);
274 return IC_CallOrUser;
277 /// GetInstructionClass - Determine what kind of construct V is.
278 static InstructionClass GetInstructionClass(const Value *V) {
279 if (const Instruction *I = dyn_cast<Instruction>(V)) {
280 // Any instruction other than bitcast and gep with a pointer operand have a
281 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
282 // to a subsequent use, rather than using it themselves, in this sense.
283 // As a short cut, several other opcodes are known to have no pointer
284 // operands of interest. And ret is never followed by a release, so it's
285 // not interesting to examine.
286 switch (I->getOpcode()) {
287 case Instruction::Call: {
288 const CallInst *CI = cast<CallInst>(I);
289 // Check for calls to special functions.
290 if (const Function *F = CI->getCalledFunction()) {
291 InstructionClass Class = GetFunctionClass(F);
292 if (Class != IC_CallOrUser)
295 // None of the intrinsic functions do objc_release. For intrinsics, the
296 // only question is whether or not they may be users.
297 switch (F->getIntrinsicID()) {
299 case Intrinsic::bswap: case Intrinsic::ctpop:
300 case Intrinsic::ctlz: case Intrinsic::cttz:
301 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
302 case Intrinsic::stacksave: case Intrinsic::stackrestore:
303 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
304 // Don't let dbg info affect our results.
305 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
306 // Short cut: Some intrinsics obviously don't use ObjC pointers.
309 for (Function::const_arg_iterator AI = F->arg_begin(),
310 AE = F->arg_end(); AI != AE; ++AI)
311 if (IsPotentialUse(AI))
316 return GetCallSiteClass(CI);
318 case Instruction::Invoke:
319 return GetCallSiteClass(cast<InvokeInst>(I));
320 case Instruction::BitCast:
321 case Instruction::GetElementPtr:
322 case Instruction::Select: case Instruction::PHI:
323 case Instruction::Ret: case Instruction::Br:
324 case Instruction::Switch: case Instruction::IndirectBr:
325 case Instruction::Alloca: case Instruction::VAArg:
326 case Instruction::Add: case Instruction::FAdd:
327 case Instruction::Sub: case Instruction::FSub:
328 case Instruction::Mul: case Instruction::FMul:
329 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
330 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
331 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
332 case Instruction::And: case Instruction::Or: case Instruction::Xor:
333 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
334 case Instruction::IntToPtr: case Instruction::FCmp:
335 case Instruction::FPTrunc: case Instruction::FPExt:
336 case Instruction::FPToUI: case Instruction::FPToSI:
337 case Instruction::UIToFP: case Instruction::SIToFP:
338 case Instruction::InsertElement: case Instruction::ExtractElement:
339 case Instruction::ShuffleVector:
340 case Instruction::ExtractValue:
342 case Instruction::ICmp:
343 // Comparing a pointer with null, or any other constant, isn't an
344 // interesting use, because we don't care what the pointer points to, or
345 // about the values of any other dynamic reference-counted pointers.
346 if (IsPotentialUse(I->getOperand(1)))
350 // For anything else, check all the operands.
351 // Note that this includes both operands of a Store: while the first
352 // operand isn't actually being dereferenced, it is being stored to
353 // memory where we can no longer track who might read it and dereference
354 // it, so we have to consider it potentially used.
355 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
357 if (IsPotentialUse(*OI))
362 // Otherwise, it's totally inert for ARC purposes.
366 /// GetBasicInstructionClass - Determine what kind of construct V is. This is
367 /// similar to GetInstructionClass except that it only detects objc runtine
368 /// calls. This allows it to be faster.
369 static InstructionClass GetBasicInstructionClass(const Value *V) {
370 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
371 if (const Function *F = CI->getCalledFunction())
372 return GetFunctionClass(F);
373 // Otherwise, be conservative.
374 return IC_CallOrUser;
377 // Otherwise, be conservative.
378 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
381 /// IsRetain - Test if the the given class is objc_retain or
383 static bool IsRetain(InstructionClass Class) {
384 return Class == IC_Retain ||
385 Class == IC_RetainRV;
388 /// IsAutorelease - Test if the the given class is objc_autorelease or
390 static bool IsAutorelease(InstructionClass Class) {
391 return Class == IC_Autorelease ||
392 Class == IC_AutoreleaseRV;
395 /// IsForwarding - Test if the given class represents instructions which return
396 /// their argument verbatim.
397 static bool IsForwarding(InstructionClass Class) {
398 // objc_retainBlock technically doesn't always return its argument
399 // verbatim, but it doesn't matter for our purposes here.
400 return Class == IC_Retain ||
401 Class == IC_RetainRV ||
402 Class == IC_Autorelease ||
403 Class == IC_AutoreleaseRV ||
404 Class == IC_RetainBlock ||
405 Class == IC_NoopCast;
408 /// IsNoopOnNull - Test if the given class represents instructions which do
409 /// nothing if passed a null pointer.
410 static bool IsNoopOnNull(InstructionClass Class) {
411 return Class == IC_Retain ||
412 Class == IC_RetainRV ||
413 Class == IC_Release ||
414 Class == IC_Autorelease ||
415 Class == IC_AutoreleaseRV ||
416 Class == IC_RetainBlock;
419 /// IsAlwaysTail - Test if the given class represents instructions which are
420 /// always safe to mark with the "tail" keyword.
421 static bool IsAlwaysTail(InstructionClass Class) {
422 // IC_RetainBlock may be given a stack argument.
423 return Class == IC_Retain ||
424 Class == IC_RetainRV ||
425 Class == IC_Autorelease ||
426 Class == IC_AutoreleaseRV;
429 /// IsNoThrow - Test if the given class represents instructions which are always
430 /// safe to mark with the nounwind attribute..
431 static bool IsNoThrow(InstructionClass Class) {
432 // objc_retainBlock is not nounwind because it calls user copy constructors
433 // which could theoretically throw.
434 return Class == IC_Retain ||
435 Class == IC_RetainRV ||
436 Class == IC_Release ||
437 Class == IC_Autorelease ||
438 Class == IC_AutoreleaseRV ||
439 Class == IC_AutoreleasepoolPush ||
440 Class == IC_AutoreleasepoolPop;
443 /// EraseInstruction - Erase the given instruction. ObjC calls return their
444 /// argument verbatim, so if it's such a call and the return value has users,
445 /// replace them with the argument value.
446 static void EraseInstruction(Instruction *CI) {
447 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
449 bool Unused = CI->use_empty();
452 // Replace the return value with the argument.
453 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
454 "Can't delete non-forwarding instruction with users!");
455 CI->replaceAllUsesWith(OldArg);
458 CI->eraseFromParent();
461 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
464 /// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
465 /// also knows how to look through objc_retain and objc_autorelease calls, which
466 /// we know to return their argument verbatim.
467 static const Value *GetUnderlyingObjCPtr(const Value *V) {
469 V = GetUnderlyingObject(V);
470 if (!IsForwarding(GetBasicInstructionClass(V)))
472 V = cast<CallInst>(V)->getArgOperand(0);
478 /// StripPointerCastsAndObjCCalls - This is a wrapper around
479 /// Value::stripPointerCasts which also knows how to look through objc_retain
480 /// and objc_autorelease calls, which we know to return their argument verbatim.
481 static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
483 V = V->stripPointerCasts();
484 if (!IsForwarding(GetBasicInstructionClass(V)))
486 V = cast<CallInst>(V)->getArgOperand(0);
491 /// StripPointerCastsAndObjCCalls - This is a wrapper around
492 /// Value::stripPointerCasts which also knows how to look through objc_retain
493 /// and objc_autorelease calls, which we know to return their argument verbatim.
494 static Value *StripPointerCastsAndObjCCalls(Value *V) {
496 V = V->stripPointerCasts();
497 if (!IsForwarding(GetBasicInstructionClass(V)))
499 V = cast<CallInst>(V)->getArgOperand(0);
504 /// GetObjCArg - Assuming the given instruction is one of the special calls such
505 /// as objc_retain or objc_release, return the argument value, stripped of no-op
506 /// casts and forwarding calls.
507 static Value *GetObjCArg(Value *Inst) {
508 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
511 /// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
512 /// isObjCIdentifiedObject, except that it uses special knowledge of
513 /// ObjC conventions...
514 static bool IsObjCIdentifiedObject(const Value *V) {
515 // Assume that call results and arguments have their own "provenance".
516 // Constants (including GlobalVariables) and Allocas are never
517 // reference-counted.
518 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
519 isa<Argument>(V) || isa<Constant>(V) ||
523 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
524 const Value *Pointer =
525 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
526 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
527 // A constant pointer can't be pointing to an object on the heap. It may
528 // be reference-counted, but it won't be deleted.
529 if (GV->isConstant())
531 StringRef Name = GV->getName();
532 // These special variables are known to hold values which are not
533 // reference-counted pointers.
534 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
535 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
536 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
537 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
538 Name.startswith("\01l_objc_msgSend_fixup_"))
546 /// FindSingleUseIdentifiedObject - This is similar to
547 /// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
548 /// with multiple uses.
549 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
550 if (Arg->hasOneUse()) {
551 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
552 return FindSingleUseIdentifiedObject(BC->getOperand(0));
553 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
554 if (GEP->hasAllZeroIndices())
555 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
556 if (IsForwarding(GetBasicInstructionClass(Arg)))
557 return FindSingleUseIdentifiedObject(
558 cast<CallInst>(Arg)->getArgOperand(0));
559 if (!IsObjCIdentifiedObject(Arg))
564 // If we found an identifiable object but it has multiple uses, but they
565 // are trivial uses, we can still consider this to be a single-use
567 if (IsObjCIdentifiedObject(Arg)) {
568 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
571 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
581 /// ModuleHasARC - Test if the given module looks interesting to run ARC
583 static bool ModuleHasARC(const Module &M) {
585 M.getNamedValue("objc_retain") ||
586 M.getNamedValue("objc_release") ||
587 M.getNamedValue("objc_autorelease") ||
588 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
589 M.getNamedValue("objc_retainBlock") ||
590 M.getNamedValue("objc_autoreleaseReturnValue") ||
591 M.getNamedValue("objc_autoreleasePoolPush") ||
592 M.getNamedValue("objc_loadWeakRetained") ||
593 M.getNamedValue("objc_loadWeak") ||
594 M.getNamedValue("objc_destroyWeak") ||
595 M.getNamedValue("objc_storeWeak") ||
596 M.getNamedValue("objc_initWeak") ||
597 M.getNamedValue("objc_moveWeak") ||
598 M.getNamedValue("objc_copyWeak") ||
599 M.getNamedValue("objc_retainedObject") ||
600 M.getNamedValue("objc_unretainedObject") ||
601 M.getNamedValue("objc_unretainedPointer");
604 /// DoesObjCBlockEscape - Test whether the given pointer, which is an
605 /// Objective C block pointer, does not "escape". This differs from regular
606 /// escape analysis in that a use as an argument to a call is not considered
608 static bool DoesObjCBlockEscape(const Value *BlockPtr) {
609 // Walk the def-use chains.
610 SmallVector<const Value *, 4> Worklist;
611 Worklist.push_back(BlockPtr);
613 const Value *V = Worklist.pop_back_val();
614 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
616 const User *UUser = *UI;
617 // Special - Use by a call (callee or argument) is not considered
619 if (isa<CallInst>(UUser) || isa<InvokeInst>(UUser))
621 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
622 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
623 Worklist.push_back(UUser);
628 } while (!Worklist.empty());
634 //===----------------------------------------------------------------------===//
635 // ARC AliasAnalysis.
636 //===----------------------------------------------------------------------===//
638 #include "llvm/Pass.h"
639 #include "llvm/Analysis/AliasAnalysis.h"
640 #include "llvm/Analysis/Passes.h"
643 /// ObjCARCAliasAnalysis - This is a simple alias analysis
644 /// implementation that uses knowledge of ARC constructs to answer queries.
646 /// TODO: This class could be generalized to know about other ObjC-specific
647 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
648 /// even though their offsets are dynamic.
649 class ObjCARCAliasAnalysis : public ImmutablePass,
650 public AliasAnalysis {
652 static char ID; // Class identification, replacement for typeinfo
653 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
654 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
658 virtual void initializePass() {
659 InitializeAliasAnalysis(this);
662 /// getAdjustedAnalysisPointer - This method is used when a pass implements
663 /// an analysis interface through multiple inheritance. If needed, it
664 /// should override this to adjust the this pointer as needed for the
665 /// specified pass info.
666 virtual void *getAdjustedAnalysisPointer(const void *PI) {
667 if (PI == &AliasAnalysis::ID)
668 return (AliasAnalysis*)this;
672 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
673 virtual AliasResult alias(const Location &LocA, const Location &LocB);
674 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
675 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
676 virtual ModRefBehavior getModRefBehavior(const Function *F);
677 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
678 const Location &Loc);
679 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
680 ImmutableCallSite CS2);
682 } // End of anonymous namespace
684 // Register this pass...
685 char ObjCARCAliasAnalysis::ID = 0;
686 INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
687 "ObjC-ARC-Based Alias Analysis", false, true, false)
689 ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
690 return new ObjCARCAliasAnalysis();
694 ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
695 AU.setPreservesAll();
696 AliasAnalysis::getAnalysisUsage(AU);
699 AliasAnalysis::AliasResult
700 ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
702 return AliasAnalysis::alias(LocA, LocB);
704 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
705 // precise alias query.
706 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
707 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
709 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
710 Location(SB, LocB.Size, LocB.TBAATag));
711 if (Result != MayAlias)
714 // If that failed, climb to the underlying object, including climbing through
715 // ObjC-specific no-ops, and try making an imprecise alias query.
716 const Value *UA = GetUnderlyingObjCPtr(SA);
717 const Value *UB = GetUnderlyingObjCPtr(SB);
718 if (UA != SA || UB != SB) {
719 Result = AliasAnalysis::alias(Location(UA), Location(UB));
720 // We can't use MustAlias or PartialAlias results here because
721 // GetUnderlyingObjCPtr may return an offsetted pointer value.
722 if (Result == NoAlias)
726 // If that failed, fail. We don't need to chain here, since that's covered
727 // by the earlier precise query.
732 ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
735 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
737 // First, strip off no-ops, including ObjC-specific no-ops, and try making
738 // a precise alias query.
739 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
740 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
744 // If that failed, climb to the underlying object, including climbing through
745 // ObjC-specific no-ops, and try making an imprecise alias query.
746 const Value *U = GetUnderlyingObjCPtr(S);
748 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
750 // If that failed, fail. We don't need to chain here, since that's covered
751 // by the earlier precise query.
755 AliasAnalysis::ModRefBehavior
756 ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
757 // We have nothing to do. Just chain to the next AliasAnalysis.
758 return AliasAnalysis::getModRefBehavior(CS);
761 AliasAnalysis::ModRefBehavior
762 ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
764 return AliasAnalysis::getModRefBehavior(F);
766 switch (GetFunctionClass(F)) {
768 return DoesNotAccessMemory;
773 return AliasAnalysis::getModRefBehavior(F);
776 AliasAnalysis::ModRefResult
777 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
779 return AliasAnalysis::getModRefInfo(CS, Loc);
781 switch (GetBasicInstructionClass(CS.getInstruction())) {
785 case IC_AutoreleaseRV:
787 case IC_AutoreleasepoolPush:
788 case IC_FusedRetainAutorelease:
789 case IC_FusedRetainAutoreleaseRV:
790 // These functions don't access any memory visible to the compiler.
791 // Note that this doesn't include objc_retainBlock, becuase it updates
792 // pointers when it copies block data.
798 return AliasAnalysis::getModRefInfo(CS, Loc);
801 AliasAnalysis::ModRefResult
802 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
803 ImmutableCallSite CS2) {
804 // TODO: Theoretically we could check for dependencies between objc_* calls
805 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
806 return AliasAnalysis::getModRefInfo(CS1, CS2);
809 //===----------------------------------------------------------------------===//
811 //===----------------------------------------------------------------------===//
813 #include "llvm/Support/InstIterator.h"
814 #include "llvm/Transforms/Scalar.h"
817 /// ObjCARCExpand - Early ARC transformations.
818 class ObjCARCExpand : public FunctionPass {
819 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
820 virtual bool doInitialization(Module &M);
821 virtual bool runOnFunction(Function &F);
823 /// Run - A flag indicating whether this optimization pass should run.
828 ObjCARCExpand() : FunctionPass(ID) {
829 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
834 char ObjCARCExpand::ID = 0;
835 INITIALIZE_PASS(ObjCARCExpand,
836 "objc-arc-expand", "ObjC ARC expansion", false, false)
838 Pass *llvm::createObjCARCExpandPass() {
839 return new ObjCARCExpand();
842 void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
843 AU.setPreservesCFG();
846 bool ObjCARCExpand::doInitialization(Module &M) {
847 Run = ModuleHasARC(M);
851 bool ObjCARCExpand::runOnFunction(Function &F) {
855 // If nothing in the Module uses ARC, don't do anything.
859 bool Changed = false;
861 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
862 Instruction *Inst = &*I;
864 switch (GetBasicInstructionClass(Inst)) {
868 case IC_AutoreleaseRV:
869 case IC_FusedRetainAutorelease:
870 case IC_FusedRetainAutoreleaseRV:
871 // These calls return their argument verbatim, as a low-level
872 // optimization. However, this makes high-level optimizations
873 // harder. Undo any uses of this optimization that the front-end
874 // emitted here. We'll redo them in a later pass.
876 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
886 //===----------------------------------------------------------------------===//
887 // ARC autorelease pool elimination.
888 //===----------------------------------------------------------------------===//
890 #include "llvm/Constants.h"
893 /// ObjCARCAPElim - Autorelease pool elimination.
894 class ObjCARCAPElim : public ModulePass {
895 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
896 virtual bool runOnModule(Module &M);
898 bool MayAutorelease(CallSite CS);
899 bool OptimizeBB(BasicBlock *BB);
903 ObjCARCAPElim() : ModulePass(ID) {
904 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
909 char ObjCARCAPElim::ID = 0;
910 INITIALIZE_PASS(ObjCARCAPElim,
912 "ObjC ARC autorelease pool elimination",
915 Pass *llvm::createObjCARCAPElimPass() {
916 return new ObjCARCAPElim();
919 void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
920 AU.setPreservesCFG();
923 /// MayAutorelease - Interprocedurally determine if calls made by the
924 /// given call site can possibly produce autoreleases.
925 bool ObjCARCAPElim::MayAutorelease(CallSite CS) {
926 if (Function *Callee = CS.getCalledFunction()) {
927 if (Callee->isDeclaration() || Callee->mayBeOverridden())
929 for (Function::iterator I = Callee->begin(), E = Callee->end();
932 for (BasicBlock::iterator J = BB->begin(), F = BB->end(); J != F; ++J)
933 if (CallSite JCS = CallSite(J))
934 if (!JCS.onlyReadsMemory() && MayAutorelease(JCS))
943 bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
944 bool Changed = false;
946 Instruction *Push = 0;
947 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
948 Instruction *Inst = I++;
949 switch (GetBasicInstructionClass(Inst)) {
950 case IC_AutoreleasepoolPush:
953 case IC_AutoreleasepoolPop:
954 // If this pop matches a push and nothing in between can autorelease,
956 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
958 Inst->eraseFromParent();
959 Push->eraseFromParent();
964 if (MayAutorelease(CallSite(Inst)))
975 bool ObjCARCAPElim::runOnModule(Module &M) {
979 // If nothing in the Module uses ARC, don't do anything.
980 if (!ModuleHasARC(M))
983 // Find the llvm.global_ctors variable, as the first step in
984 // identifying the global constructors.
985 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
989 assert(GV->hasDefinitiveInitializer() &&
990 "llvm.global_ctors is uncooperative!");
992 bool Changed = false;
994 // Dig the constructor functions out of GV's initializer.
995 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
996 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
999 // llvm.global_ctors is an array of pairs where the second members
1000 // are constructor functions.
1001 Function *F = cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1002 // Only look at function definitions.
1003 if (F->isDeclaration())
1005 // Only look at functions with one basic block.
1006 if (llvm::next(F->begin()) != F->end())
1008 // Ok, a single-block constructor function definition. Try to optimize it.
1009 Changed |= OptimizeBB(F->begin());
1015 //===----------------------------------------------------------------------===//
1016 // ARC optimization.
1017 //===----------------------------------------------------------------------===//
1019 // TODO: On code like this:
1022 // stuff_that_cannot_release()
1023 // objc_autorelease(%x)
1024 // stuff_that_cannot_release()
1026 // stuff_that_cannot_release()
1027 // objc_autorelease(%x)
1029 // The second retain and autorelease can be deleted.
1031 // TODO: It should be possible to delete
1032 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
1033 // pairs if nothing is actually autoreleased between them. Also, autorelease
1034 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1035 // after inlining) can be turned into plain release calls.
1037 // TODO: Critical-edge splitting. If the optimial insertion point is
1038 // a critical edge, the current algorithm has to fail, because it doesn't
1039 // know how to split edges. It should be possible to make the optimizer
1040 // think in terms of edges, rather than blocks, and then split critical
1043 // TODO: OptimizeSequences could generalized to be Interprocedural.
1045 // TODO: Recognize that a bunch of other objc runtime calls have
1046 // non-escaping arguments and non-releasing arguments, and may be
1047 // non-autoreleasing.
1049 // TODO: Sink autorelease calls as far as possible. Unfortunately we
1050 // usually can't sink them past other calls, which would be the main
1051 // case where it would be useful.
1053 // TODO: The pointer returned from objc_loadWeakRetained is retained.
1055 // TODO: Delete release+retain pairs (rare).
1057 #include "llvm/GlobalAlias.h"
1058 #include "llvm/Constants.h"
1059 #include "llvm/LLVMContext.h"
1060 #include "llvm/Support/ErrorHandling.h"
1061 #include "llvm/Support/CFG.h"
1062 #include "llvm/ADT/Statistic.h"
1063 #include "llvm/ADT/SmallPtrSet.h"
1064 #include "llvm/ADT/DenseSet.h"
1066 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1067 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1068 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1069 STATISTIC(NumRets, "Number of return value forwarding "
1070 "retain+autoreleaes eliminated");
1071 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1072 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1075 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1076 /// uses many of the same techniques, except it uses special ObjC-specific
1077 /// reasoning about pointer relationships.
1078 class ProvenanceAnalysis {
1081 typedef std::pair<const Value *, const Value *> ValuePairTy;
1082 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1083 CachedResultsTy CachedResults;
1085 bool relatedCheck(const Value *A, const Value *B);
1086 bool relatedSelect(const SelectInst *A, const Value *B);
1087 bool relatedPHI(const PHINode *A, const Value *B);
1089 // Do not implement.
1090 void operator=(const ProvenanceAnalysis &);
1091 ProvenanceAnalysis(const ProvenanceAnalysis &);
1094 ProvenanceAnalysis() {}
1096 void setAA(AliasAnalysis *aa) { AA = aa; }
1098 AliasAnalysis *getAA() const { return AA; }
1100 bool related(const Value *A, const Value *B);
1103 CachedResults.clear();
1108 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1109 // If the values are Selects with the same condition, we can do a more precise
1110 // check: just check for relations between the values on corresponding arms.
1111 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
1112 if (A->getCondition() == SB->getCondition()) {
1113 if (related(A->getTrueValue(), SB->getTrueValue()))
1115 if (related(A->getFalseValue(), SB->getFalseValue()))
1120 // Check both arms of the Select node individually.
1121 if (related(A->getTrueValue(), B))
1123 if (related(A->getFalseValue(), B))
1126 // The arms both checked out.
1130 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1131 // If the values are PHIs in the same block, we can do a more precise as well
1132 // as efficient check: just check for relations between the values on
1133 // corresponding edges.
1134 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1135 if (PNB->getParent() == A->getParent()) {
1136 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1137 if (related(A->getIncomingValue(i),
1138 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1143 // Check each unique source of the PHI node against B.
1144 SmallPtrSet<const Value *, 4> UniqueSrc;
1145 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1146 const Value *PV1 = A->getIncomingValue(i);
1147 if (UniqueSrc.insert(PV1) && related(PV1, B))
1151 // All of the arms checked out.
1155 /// isStoredObjCPointer - Test if the value of P, or any value covered by its
1156 /// provenance, is ever stored within the function (not counting callees).
1157 static bool isStoredObjCPointer(const Value *P) {
1158 SmallPtrSet<const Value *, 8> Visited;
1159 SmallVector<const Value *, 8> Worklist;
1160 Worklist.push_back(P);
1163 P = Worklist.pop_back_val();
1164 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1166 const User *Ur = *UI;
1167 if (isa<StoreInst>(Ur)) {
1168 if (UI.getOperandNo() == 0)
1169 // The pointer is stored.
1171 // The pointed is stored through.
1174 if (isa<CallInst>(Ur))
1175 // The pointer is passed as an argument, ignore this.
1177 if (isa<PtrToIntInst>(P))
1178 // Assume the worst.
1180 if (Visited.insert(Ur))
1181 Worklist.push_back(Ur);
1183 } while (!Worklist.empty());
1185 // Everything checked out.
1189 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1190 // Skip past provenance pass-throughs.
1191 A = GetUnderlyingObjCPtr(A);
1192 B = GetUnderlyingObjCPtr(B);
1198 // Ask regular AliasAnalysis, for a first approximation.
1199 switch (AA->alias(A, B)) {
1200 case AliasAnalysis::NoAlias:
1202 case AliasAnalysis::MustAlias:
1203 case AliasAnalysis::PartialAlias:
1205 case AliasAnalysis::MayAlias:
1209 bool AIsIdentified = IsObjCIdentifiedObject(A);
1210 bool BIsIdentified = IsObjCIdentifiedObject(B);
1212 // An ObjC-Identified object can't alias a load if it is never locally stored.
1213 if (AIsIdentified) {
1214 if (BIsIdentified) {
1215 // If both pointers have provenance, they can be directly compared.
1219 if (isa<LoadInst>(B))
1220 return isStoredObjCPointer(A);
1223 if (BIsIdentified && isa<LoadInst>(A))
1224 return isStoredObjCPointer(B);
1227 // Special handling for PHI and Select.
1228 if (const PHINode *PN = dyn_cast<PHINode>(A))
1229 return relatedPHI(PN, B);
1230 if (const PHINode *PN = dyn_cast<PHINode>(B))
1231 return relatedPHI(PN, A);
1232 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1233 return relatedSelect(S, B);
1234 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1235 return relatedSelect(S, A);
1241 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1242 // Begin by inserting a conservative value into the map. If the insertion
1243 // fails, we have the answer already. If it succeeds, leave it there until we
1244 // compute the real answer to guard against recursive queries.
1245 if (A > B) std::swap(A, B);
1246 std::pair<CachedResultsTy::iterator, bool> Pair =
1247 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1249 return Pair.first->second;
1251 bool Result = relatedCheck(A, B);
1252 CachedResults[ValuePairTy(A, B)] = Result;
1257 // Sequence - A sequence of states that a pointer may go through in which an
1258 // objc_retain and objc_release are actually needed.
1261 S_Retain, ///< objc_retain(x)
1262 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1263 S_Use, ///< any use of x
1264 S_Stop, ///< like S_Release, but code motion is stopped
1265 S_Release, ///< objc_release(x)
1266 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1270 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1274 if (A == S_None || B == S_None)
1277 if (A > B) std::swap(A, B);
1279 // Choose the side which is further along in the sequence.
1280 if ((A == S_Retain || A == S_CanRelease) &&
1281 (B == S_CanRelease || B == S_Use))
1284 // Choose the side which is further along in the sequence.
1285 if ((A == S_Use || A == S_CanRelease) &&
1286 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
1288 // If both sides are releases, choose the more conservative one.
1289 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1291 if (A == S_Release && B == S_MovableRelease)
1299 /// RRInfo - Unidirectional information about either a
1300 /// retain-decrement-use-release sequence or release-use-decrement-retain
1301 /// reverese sequence.
1303 /// KnownSafe - After an objc_retain, the reference count of the referenced
1304 /// object is known to be positive. Similarly, before an objc_release, the
1305 /// reference count of the referenced object is known to be positive. If
1306 /// there are retain-release pairs in code regions where the retain count
1307 /// is known to be positive, they can be eliminated, regardless of any side
1308 /// effects between them.
1310 /// Also, a retain+release pair nested within another retain+release
1311 /// pair all on the known same pointer value can be eliminated, regardless
1312 /// of any intervening side effects.
1314 /// KnownSafe is true when either of these conditions is satisfied.
1317 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1318 /// opposed to objc_retain calls).
1321 /// IsTailCallRelease - True of the objc_release calls are all marked
1322 /// with the "tail" keyword.
1323 bool IsTailCallRelease;
1325 /// Partial - True of we've seen an opportunity for partial RR elimination,
1326 /// such as pushing calls into a CFG triangle or into one side of a
1328 /// TODO: Consider moving this to PtrState.
1331 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1332 /// a clang.imprecise_release tag, this is the metadata tag.
1333 MDNode *ReleaseMetadata;
1335 /// Calls - For a top-down sequence, the set of objc_retains or
1336 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1337 SmallPtrSet<Instruction *, 2> Calls;
1339 /// ReverseInsertPts - The set of optimal insert positions for
1340 /// moving calls in the opposite sequence.
1341 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1344 KnownSafe(false), IsRetainBlock(false),
1345 IsTailCallRelease(false), Partial(false),
1346 ReleaseMetadata(0) {}
1352 void RRInfo::clear() {
1354 IsRetainBlock = false;
1355 IsTailCallRelease = false;
1357 ReleaseMetadata = 0;
1359 ReverseInsertPts.clear();
1363 /// PtrState - This class summarizes several per-pointer runtime properties
1364 /// which are propogated through the flow graph.
1366 /// RefCount - The known minimum number of reference count increments.
1369 /// NestCount - The known minimum level of retain+release nesting.
1372 /// Seq - The current position in the sequence.
1376 /// RRI - Unidirectional information about the current sequence.
1377 /// TODO: Encapsulate this better.
1380 PtrState() : RefCount(0), NestCount(0), Seq(S_None) {}
1382 void SetAtLeastOneRefCount() {
1383 if (RefCount == 0) RefCount = 1;
1386 void IncrementRefCount() {
1387 if (RefCount != UINT_MAX) ++RefCount;
1390 void DecrementRefCount() {
1391 if (RefCount != 0) --RefCount;
1394 bool IsKnownIncremented() const {
1395 return RefCount > 0;
1398 void IncrementNestCount() {
1399 if (NestCount != UINT_MAX) ++NestCount;
1402 void DecrementNestCount() {
1403 if (NestCount != 0) --NestCount;
1406 bool IsKnownNested() const {
1407 return NestCount > 0;
1410 void SetSeq(Sequence NewSeq) {
1414 Sequence GetSeq() const {
1418 void ClearSequenceProgress() {
1423 void Merge(const PtrState &Other, bool TopDown);
1428 PtrState::Merge(const PtrState &Other, bool TopDown) {
1429 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1430 RefCount = std::min(RefCount, Other.RefCount);
1431 NestCount = std::min(NestCount, Other.NestCount);
1433 // We can't merge a plain objc_retain with an objc_retainBlock.
1434 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1437 // If we're not in a sequence (anymore), drop all associated state.
1438 if (Seq == S_None) {
1440 } else if (RRI.Partial || Other.RRI.Partial) {
1441 // If we're doing a merge on a path that's previously seen a partial
1442 // merge, conservatively drop the sequence, to avoid doing partial
1443 // RR elimination. If the branch predicates for the two merge differ,
1444 // mixing them is unsafe.
1448 // Conservatively merge the ReleaseMetadata information.
1449 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1450 RRI.ReleaseMetadata = 0;
1452 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
1453 RRI.IsTailCallRelease = RRI.IsTailCallRelease && Other.RRI.IsTailCallRelease;
1454 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1456 // Merge the insert point sets. If there are any differences,
1457 // that makes this a partial merge.
1458 RRI.Partial = RRI.ReverseInsertPts.size() !=
1459 Other.RRI.ReverseInsertPts.size();
1460 for (SmallPtrSet<Instruction *, 2>::const_iterator
1461 I = Other.RRI.ReverseInsertPts.begin(),
1462 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1463 RRI.Partial |= RRI.ReverseInsertPts.insert(*I);
1468 /// BBState - Per-BasicBlock state.
1470 /// TopDownPathCount - The number of unique control paths from the entry
1471 /// which can reach this block.
1472 unsigned TopDownPathCount;
1474 /// BottomUpPathCount - The number of unique control paths to exits
1475 /// from this block.
1476 unsigned BottomUpPathCount;
1478 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1479 typedef MapVector<const Value *, PtrState> MapTy;
1481 /// PerPtrTopDown - The top-down traversal uses this to record information
1482 /// known about a pointer at the bottom of each block.
1483 MapTy PerPtrTopDown;
1485 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1486 /// known about a pointer at the top of each block.
1487 MapTy PerPtrBottomUp;
1490 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1492 typedef MapTy::iterator ptr_iterator;
1493 typedef MapTy::const_iterator ptr_const_iterator;
1495 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1496 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1497 ptr_const_iterator top_down_ptr_begin() const {
1498 return PerPtrTopDown.begin();
1500 ptr_const_iterator top_down_ptr_end() const {
1501 return PerPtrTopDown.end();
1504 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1505 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1506 ptr_const_iterator bottom_up_ptr_begin() const {
1507 return PerPtrBottomUp.begin();
1509 ptr_const_iterator bottom_up_ptr_end() const {
1510 return PerPtrBottomUp.end();
1513 /// SetAsEntry - Mark this block as being an entry block, which has one
1514 /// path from the entry by definition.
1515 void SetAsEntry() { TopDownPathCount = 1; }
1517 /// SetAsExit - Mark this block as being an exit block, which has one
1518 /// path to an exit by definition.
1519 void SetAsExit() { BottomUpPathCount = 1; }
1521 PtrState &getPtrTopDownState(const Value *Arg) {
1522 return PerPtrTopDown[Arg];
1525 PtrState &getPtrBottomUpState(const Value *Arg) {
1526 return PerPtrBottomUp[Arg];
1529 void clearBottomUpPointers() {
1530 PerPtrBottomUp.clear();
1533 void clearTopDownPointers() {
1534 PerPtrTopDown.clear();
1537 void InitFromPred(const BBState &Other);
1538 void InitFromSucc(const BBState &Other);
1539 void MergePred(const BBState &Other);
1540 void MergeSucc(const BBState &Other);
1542 /// GetAllPathCount - Return the number of possible unique paths from an
1543 /// entry to an exit which pass through this block. This is only valid
1544 /// after both the top-down and bottom-up traversals are complete.
1545 unsigned GetAllPathCount() const {
1546 return TopDownPathCount * BottomUpPathCount;
1549 /// IsVisitedTopDown - Test whether the block for this BBState has been
1550 /// visited by the top-down portion of the algorithm.
1551 bool isVisitedTopDown() const {
1552 return TopDownPathCount != 0;
1557 void BBState::InitFromPred(const BBState &Other) {
1558 PerPtrTopDown = Other.PerPtrTopDown;
1559 TopDownPathCount = Other.TopDownPathCount;
1562 void BBState::InitFromSucc(const BBState &Other) {
1563 PerPtrBottomUp = Other.PerPtrBottomUp;
1564 BottomUpPathCount = Other.BottomUpPathCount;
1567 /// MergePred - The top-down traversal uses this to merge information about
1568 /// predecessors to form the initial state for a new block.
1569 void BBState::MergePred(const BBState &Other) {
1570 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1571 // loop backedge. Loop backedges are special.
1572 TopDownPathCount += Other.TopDownPathCount;
1574 // For each entry in the other set, if our set has an entry with the same key,
1575 // merge the entries. Otherwise, copy the entry and merge it with an empty
1577 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1578 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1579 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1580 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1584 // For each entry in our set, if the other set doesn't have an entry with the
1585 // same key, force it to merge with an empty entry.
1586 for (ptr_iterator MI = top_down_ptr_begin(),
1587 ME = top_down_ptr_end(); MI != ME; ++MI)
1588 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1589 MI->second.Merge(PtrState(), /*TopDown=*/true);
1592 /// MergeSucc - The bottom-up traversal uses this to merge information about
1593 /// successors to form the initial state for a new block.
1594 void BBState::MergeSucc(const BBState &Other) {
1595 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1596 // loop backedge. Loop backedges are special.
1597 BottomUpPathCount += Other.BottomUpPathCount;
1599 // For each entry in the other set, if our set has an entry with the
1600 // same key, merge the entries. Otherwise, copy the entry and merge
1601 // it with an empty entry.
1602 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1603 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1604 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1605 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1609 // For each entry in our set, if the other set doesn't have an entry
1610 // with the same key, force it to merge with an empty entry.
1611 for (ptr_iterator MI = bottom_up_ptr_begin(),
1612 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1613 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1614 MI->second.Merge(PtrState(), /*TopDown=*/false);
1618 /// ObjCARCOpt - The main ARC optimization pass.
1619 class ObjCARCOpt : public FunctionPass {
1621 ProvenanceAnalysis PA;
1623 /// Run - A flag indicating whether this optimization pass should run.
1626 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1627 /// functions, for use in creating calls to them. These are initialized
1628 /// lazily to avoid cluttering up the Module with unused declarations.
1629 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
1630 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
1632 /// UsedInThisFunciton - Flags which determine whether each of the
1633 /// interesting runtine functions is in fact used in the current function.
1634 unsigned UsedInThisFunction;
1636 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1638 unsigned ImpreciseReleaseMDKind;
1640 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
1642 unsigned CopyOnEscapeMDKind;
1644 Constant *getRetainRVCallee(Module *M);
1645 Constant *getAutoreleaseRVCallee(Module *M);
1646 Constant *getReleaseCallee(Module *M);
1647 Constant *getRetainCallee(Module *M);
1648 Constant *getRetainBlockCallee(Module *M);
1649 Constant *getAutoreleaseCallee(Module *M);
1651 bool IsRetainBlockOptimizable(const Instruction *Inst);
1653 void OptimizeRetainCall(Function &F, Instruction *Retain);
1654 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1655 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1656 void OptimizeIndividualCalls(Function &F);
1658 void CheckForCFGHazards(const BasicBlock *BB,
1659 DenseMap<const BasicBlock *, BBState> &BBStates,
1660 BBState &MyStates) const;
1661 bool VisitBottomUp(BasicBlock *BB,
1662 DenseMap<const BasicBlock *, BBState> &BBStates,
1663 MapVector<Value *, RRInfo> &Retains);
1664 bool VisitTopDown(BasicBlock *BB,
1665 DenseMap<const BasicBlock *, BBState> &BBStates,
1666 DenseMap<Value *, RRInfo> &Releases);
1667 bool Visit(Function &F,
1668 DenseMap<const BasicBlock *, BBState> &BBStates,
1669 MapVector<Value *, RRInfo> &Retains,
1670 DenseMap<Value *, RRInfo> &Releases);
1672 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1673 MapVector<Value *, RRInfo> &Retains,
1674 DenseMap<Value *, RRInfo> &Releases,
1675 SmallVectorImpl<Instruction *> &DeadInsts,
1678 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1679 MapVector<Value *, RRInfo> &Retains,
1680 DenseMap<Value *, RRInfo> &Releases,
1683 void OptimizeWeakCalls(Function &F);
1685 bool OptimizeSequences(Function &F);
1687 void OptimizeReturns(Function &F);
1689 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1690 virtual bool doInitialization(Module &M);
1691 virtual bool runOnFunction(Function &F);
1692 virtual void releaseMemory();
1696 ObjCARCOpt() : FunctionPass(ID) {
1697 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1702 char ObjCARCOpt::ID = 0;
1703 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1704 "objc-arc", "ObjC ARC optimization", false, false)
1705 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1706 INITIALIZE_PASS_END(ObjCARCOpt,
1707 "objc-arc", "ObjC ARC optimization", false, false)
1709 Pass *llvm::createObjCARCOptPass() {
1710 return new ObjCARCOpt();
1713 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1714 AU.addRequired<ObjCARCAliasAnalysis>();
1715 AU.addRequired<AliasAnalysis>();
1716 // ARC optimization doesn't currently split critical edges.
1717 AU.setPreservesCFG();
1720 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1721 // Without the magic metadata tag, we have to assume this might be an
1722 // objc_retainBlock call inserted to convert a block pointer to an id,
1723 // in which case it really is needed.
1724 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1727 // If the pointer "escapes" (not including being used in a call),
1728 // the copy may be needed.
1729 if (DoesObjCBlockEscape(Inst))
1732 // Otherwise, it's not needed.
1736 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1737 if (!RetainRVCallee) {
1738 LLVMContext &C = M->getContext();
1739 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1740 std::vector<Type *> Params;
1741 Params.push_back(I8X);
1743 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1744 AttrListPtr Attributes;
1745 Attributes.addAttr(~0u, Attribute::NoUnwind);
1747 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1750 return RetainRVCallee;
1753 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1754 if (!AutoreleaseRVCallee) {
1755 LLVMContext &C = M->getContext();
1756 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1757 std::vector<Type *> Params;
1758 Params.push_back(I8X);
1760 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1761 AttrListPtr Attributes;
1762 Attributes.addAttr(~0u, Attribute::NoUnwind);
1763 AutoreleaseRVCallee =
1764 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1767 return AutoreleaseRVCallee;
1770 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1771 if (!ReleaseCallee) {
1772 LLVMContext &C = M->getContext();
1773 std::vector<Type *> Params;
1774 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1775 AttrListPtr Attributes;
1776 Attributes.addAttr(~0u, Attribute::NoUnwind);
1778 M->getOrInsertFunction(
1780 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1783 return ReleaseCallee;
1786 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1787 if (!RetainCallee) {
1788 LLVMContext &C = M->getContext();
1789 std::vector<Type *> Params;
1790 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1791 AttrListPtr Attributes;
1792 Attributes.addAttr(~0u, Attribute::NoUnwind);
1794 M->getOrInsertFunction(
1796 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1799 return RetainCallee;
1802 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1803 if (!RetainBlockCallee) {
1804 LLVMContext &C = M->getContext();
1805 std::vector<Type *> Params;
1806 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1807 AttrListPtr Attributes;
1808 // objc_retainBlock is not nounwind because it calls user copy constructors
1809 // which could theoretically throw.
1811 M->getOrInsertFunction(
1813 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1816 return RetainBlockCallee;
1819 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1820 if (!AutoreleaseCallee) {
1821 LLVMContext &C = M->getContext();
1822 std::vector<Type *> Params;
1823 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1824 AttrListPtr Attributes;
1825 Attributes.addAttr(~0u, Attribute::NoUnwind);
1827 M->getOrInsertFunction(
1829 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1832 return AutoreleaseCallee;
1835 /// CanAlterRefCount - Test whether the given instruction can result in a
1836 /// reference count modification (positive or negative) for the pointer's
1839 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1840 ProvenanceAnalysis &PA, InstructionClass Class) {
1842 case IC_Autorelease:
1843 case IC_AutoreleaseRV:
1845 // These operations never directly modify a reference count.
1850 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1851 assert(CS && "Only calls can alter reference counts!");
1853 // See if AliasAnalysis can help us with the call.
1854 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1855 if (AliasAnalysis::onlyReadsMemory(MRB))
1857 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1858 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1860 const Value *Op = *I;
1861 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1867 // Assume the worst.
1871 /// CanUse - Test whether the given instruction can "use" the given pointer's
1872 /// object in a way that requires the reference count to be positive.
1874 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1875 InstructionClass Class) {
1876 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1877 if (Class == IC_Call)
1880 // Consider various instructions which may have pointer arguments which are
1882 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1883 // Comparing a pointer with null, or any other constant, isn't really a use,
1884 // because we don't care what the pointer points to, or about the values
1885 // of any other dynamic reference-counted pointers.
1886 if (!IsPotentialUse(ICI->getOperand(1)))
1888 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1889 // For calls, just check the arguments (and not the callee operand).
1890 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1891 OE = CS.arg_end(); OI != OE; ++OI) {
1892 const Value *Op = *OI;
1893 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1897 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1898 // Special-case stores, because we don't care about the stored value, just
1899 // the store address.
1900 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1901 // If we can't tell what the underlying object was, assume there is a
1903 return IsPotentialUse(Op) && PA.related(Op, Ptr);
1906 // Check each operand for a match.
1907 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1909 const Value *Op = *OI;
1910 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1916 /// CanInterruptRV - Test whether the given instruction can autorelease
1917 /// any pointer or cause an autoreleasepool pop.
1919 CanInterruptRV(InstructionClass Class) {
1921 case IC_AutoreleasepoolPop:
1924 case IC_Autorelease:
1925 case IC_AutoreleaseRV:
1926 case IC_FusedRetainAutorelease:
1927 case IC_FusedRetainAutoreleaseRV:
1935 /// DependenceKind - There are several kinds of dependence-like concepts in
1937 enum DependenceKind {
1938 NeedsPositiveRetainCount,
1939 CanChangeRetainCount,
1940 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1941 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1942 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1946 /// Depends - Test if there can be dependencies on Inst through Arg. This
1947 /// function only tests dependencies relevant for removing pairs of calls.
1949 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1950 ProvenanceAnalysis &PA) {
1951 // If we've reached the definition of Arg, stop.
1956 case NeedsPositiveRetainCount: {
1957 InstructionClass Class = GetInstructionClass(Inst);
1959 case IC_AutoreleasepoolPop:
1960 case IC_AutoreleasepoolPush:
1964 return CanUse(Inst, Arg, PA, Class);
1968 case CanChangeRetainCount: {
1969 InstructionClass Class = GetInstructionClass(Inst);
1971 case IC_AutoreleasepoolPop:
1972 // Conservatively assume this can decrement any count.
1974 case IC_AutoreleasepoolPush:
1978 return CanAlterRefCount(Inst, Arg, PA, Class);
1982 case RetainAutoreleaseDep:
1983 switch (GetBasicInstructionClass(Inst)) {
1984 case IC_AutoreleasepoolPop:
1985 // Don't merge an objc_autorelease with an objc_retain inside a different
1986 // autoreleasepool scope.
1990 // Check for a retain of the same pointer for merging.
1991 return GetObjCArg(Inst) == Arg;
1993 // Nothing else matters for objc_retainAutorelease formation.
1998 case RetainAutoreleaseRVDep: {
1999 InstructionClass Class = GetBasicInstructionClass(Inst);
2003 // Check for a retain of the same pointer for merging.
2004 return GetObjCArg(Inst) == Arg;
2006 // Anything that can autorelease interrupts
2007 // retainAutoreleaseReturnValue formation.
2008 return CanInterruptRV(Class);
2014 return CanInterruptRV(GetBasicInstructionClass(Inst));
2017 llvm_unreachable("Invalid dependence flavor");
2020 /// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2021 /// find local and non-local dependencies on Arg.
2022 /// TODO: Cache results?
2024 FindDependencies(DependenceKind Flavor,
2026 BasicBlock *StartBB, Instruction *StartInst,
2027 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2028 SmallPtrSet<const BasicBlock *, 4> &Visited,
2029 ProvenanceAnalysis &PA) {
2030 BasicBlock::iterator StartPos = StartInst;
2032 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2033 Worklist.push_back(std::make_pair(StartBB, StartPos));
2035 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2036 Worklist.pop_back_val();
2037 BasicBlock *LocalStartBB = Pair.first;
2038 BasicBlock::iterator LocalStartPos = Pair.second;
2039 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2041 if (LocalStartPos == StartBBBegin) {
2042 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2044 // If we've reached the function entry, produce a null dependence.
2045 DependingInstructions.insert(0);
2047 // Add the predecessors to the worklist.
2049 BasicBlock *PredBB = *PI;
2050 if (Visited.insert(PredBB))
2051 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2052 } while (++PI != PE);
2056 Instruction *Inst = --LocalStartPos;
2057 if (Depends(Flavor, Inst, Arg, PA)) {
2058 DependingInstructions.insert(Inst);
2062 } while (!Worklist.empty());
2064 // Determine whether the original StartBB post-dominates all of the blocks we
2065 // visited. If not, insert a sentinal indicating that most optimizations are
2067 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2068 E = Visited.end(); I != E; ++I) {
2069 const BasicBlock *BB = *I;
2072 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2073 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2074 const BasicBlock *Succ = *SI;
2075 if (Succ != StartBB && !Visited.count(Succ)) {
2076 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2083 static bool isNullOrUndef(const Value *V) {
2084 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2087 static bool isNoopInstruction(const Instruction *I) {
2088 return isa<BitCastInst>(I) ||
2089 (isa<GetElementPtrInst>(I) &&
2090 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2093 /// OptimizeRetainCall - Turn objc_retain into
2094 /// objc_retainAutoreleasedReturnValue if the operand is a return value.
2096 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
2097 CallSite CS(GetObjCArg(Retain));
2098 Instruction *Call = CS.getInstruction();
2100 if (Call->getParent() != Retain->getParent()) return;
2102 // Check that the call is next to the retain.
2103 BasicBlock::iterator I = Call;
2105 while (isNoopInstruction(I)) ++I;
2109 // Turn it to an objc_retainAutoreleasedReturnValue..
2112 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2115 /// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
2116 /// objc_retain if the operand is not a return value. Or, if it can be
2117 /// paired with an objc_autoreleaseReturnValue, delete the pair and
2120 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
2121 // Check for the argument being from an immediately preceding call.
2122 Value *Arg = GetObjCArg(RetainRV);
2124 if (Instruction *Call = CS.getInstruction())
2125 if (Call->getParent() == RetainRV->getParent()) {
2126 BasicBlock::iterator I = Call;
2128 while (isNoopInstruction(I)) ++I;
2129 if (&*I == RetainRV)
2133 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2134 // pointer. In this case, we can delete the pair.
2135 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2137 do --I; while (I != Begin && isNoopInstruction(I));
2138 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2139 GetObjCArg(I) == Arg) {
2142 EraseInstruction(I);
2143 EraseInstruction(RetainRV);
2148 // Turn it to a plain objc_retain.
2151 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2155 /// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2156 /// objc_autorelease if the result is not used as a return value.
2158 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
2159 // Check for a return of the pointer value.
2160 const Value *Ptr = GetObjCArg(AutoreleaseRV);
2161 SmallVector<const Value *, 2> Users;
2162 Users.push_back(Ptr);
2164 Ptr = Users.pop_back_val();
2165 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2167 const User *I = *UI;
2168 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2170 if (isa<BitCastInst>(I))
2173 } while (!Users.empty());
2177 cast<CallInst>(AutoreleaseRV)->
2178 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2181 /// OptimizeIndividualCalls - Visit each call, one at a time, and make
2182 /// simplifications without doing any additional analysis.
2183 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2184 // Reset all the flags in preparation for recomputing them.
2185 UsedInThisFunction = 0;
2187 // Visit all objc_* calls in F.
2188 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2189 Instruction *Inst = &*I++;
2190 InstructionClass Class = GetBasicInstructionClass(Inst);
2195 // Delete no-op casts. These function calls have special semantics, but
2196 // the semantics are entirely implemented via lowering in the front-end,
2197 // so by the time they reach the optimizer, they are just no-op calls
2198 // which return their argument.
2200 // There are gray areas here, as the ability to cast reference-counted
2201 // pointers to raw void* and back allows code to break ARC assumptions,
2202 // however these are currently considered to be unimportant.
2206 EraseInstruction(Inst);
2209 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2212 case IC_LoadWeakRetained:
2214 case IC_DestroyWeak: {
2215 CallInst *CI = cast<CallInst>(Inst);
2216 if (isNullOrUndef(CI->getArgOperand(0))) {
2217 Type *Ty = CI->getArgOperand(0)->getType();
2218 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2219 Constant::getNullValue(Ty),
2221 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2222 CI->eraseFromParent();
2229 CallInst *CI = cast<CallInst>(Inst);
2230 if (isNullOrUndef(CI->getArgOperand(0)) ||
2231 isNullOrUndef(CI->getArgOperand(1))) {
2232 Type *Ty = CI->getArgOperand(0)->getType();
2233 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2234 Constant::getNullValue(Ty),
2236 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2237 CI->eraseFromParent();
2243 OptimizeRetainCall(F, Inst);
2246 if (OptimizeRetainRVCall(F, Inst))
2249 case IC_AutoreleaseRV:
2250 OptimizeAutoreleaseRVCall(F, Inst);
2254 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2255 if (IsAutorelease(Class) && Inst->use_empty()) {
2256 CallInst *Call = cast<CallInst>(Inst);
2257 const Value *Arg = Call->getArgOperand(0);
2258 Arg = FindSingleUseIdentifiedObject(Arg);
2263 // Create the declaration lazily.
2264 LLVMContext &C = Inst->getContext();
2266 CallInst::Create(getReleaseCallee(F.getParent()),
2267 Call->getArgOperand(0), "", Call);
2268 NewCall->setMetadata(ImpreciseReleaseMDKind,
2269 MDNode::get(C, ArrayRef<Value *>()));
2270 EraseInstruction(Call);
2276 // For functions which can never be passed stack arguments, add
2278 if (IsAlwaysTail(Class)) {
2280 cast<CallInst>(Inst)->setTailCall();
2283 // Set nounwind as needed.
2284 if (IsNoThrow(Class)) {
2286 cast<CallInst>(Inst)->setDoesNotThrow();
2289 if (!IsNoopOnNull(Class)) {
2290 UsedInThisFunction |= 1 << Class;
2294 const Value *Arg = GetObjCArg(Inst);
2296 // ARC calls with null are no-ops. Delete them.
2297 if (isNullOrUndef(Arg)) {
2300 EraseInstruction(Inst);
2304 // Keep track of which of retain, release, autorelease, and retain_block
2305 // are actually present in this function.
2306 UsedInThisFunction |= 1 << Class;
2308 // If Arg is a PHI, and one or more incoming values to the
2309 // PHI are null, and the call is control-equivalent to the PHI, and there
2310 // are no relevant side effects between the PHI and the call, the call
2311 // could be pushed up to just those paths with non-null incoming values.
2312 // For now, don't bother splitting critical edges for this.
2313 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2314 Worklist.push_back(std::make_pair(Inst, Arg));
2316 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2320 const PHINode *PN = dyn_cast<PHINode>(Arg);
2323 // Determine if the PHI has any null operands, or any incoming
2325 bool HasNull = false;
2326 bool HasCriticalEdges = false;
2327 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2329 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2330 if (isNullOrUndef(Incoming))
2332 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2333 .getNumSuccessors() != 1) {
2334 HasCriticalEdges = true;
2338 // If we have null operands and no critical edges, optimize.
2339 if (!HasCriticalEdges && HasNull) {
2340 SmallPtrSet<Instruction *, 4> DependingInstructions;
2341 SmallPtrSet<const BasicBlock *, 4> Visited;
2343 // Check that there is nothing that cares about the reference
2344 // count between the call and the phi.
2345 FindDependencies(NeedsPositiveRetainCount, Arg,
2346 Inst->getParent(), Inst,
2347 DependingInstructions, Visited, PA);
2348 if (DependingInstructions.size() == 1 &&
2349 *DependingInstructions.begin() == PN) {
2352 // Clone the call into each predecessor that has a non-null value.
2353 CallInst *CInst = cast<CallInst>(Inst);
2354 Type *ParamTy = CInst->getArgOperand(0)->getType();
2355 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2357 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2358 if (!isNullOrUndef(Incoming)) {
2359 CallInst *Clone = cast<CallInst>(CInst->clone());
2360 Value *Op = PN->getIncomingValue(i);
2361 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2362 if (Op->getType() != ParamTy)
2363 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2364 Clone->setArgOperand(0, Op);
2365 Clone->insertBefore(InsertPos);
2366 Worklist.push_back(std::make_pair(Clone, Incoming));
2369 // Erase the original call.
2370 EraseInstruction(CInst);
2374 } while (!Worklist.empty());
2378 /// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2379 /// control flow, or other CFG structures where moving code across the edge
2380 /// would result in it being executed more.
2382 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2383 DenseMap<const BasicBlock *, BBState> &BBStates,
2384 BBState &MyStates) const {
2385 // If any top-down local-use or possible-dec has a succ which is earlier in
2386 // the sequence, forget it.
2387 for (BBState::ptr_const_iterator I = MyStates.top_down_ptr_begin(),
2388 E = MyStates.top_down_ptr_end(); I != E; ++I)
2389 switch (I->second.GetSeq()) {
2392 const Value *Arg = I->first;
2393 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2394 bool SomeSuccHasSame = false;
2395 bool AllSuccsHaveSame = true;
2396 PtrState &S = MyStates.getPtrTopDownState(Arg);
2397 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2398 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2399 switch (SuccS.GetSeq()) {
2401 case S_CanRelease: {
2402 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2403 S.ClearSequenceProgress();
2407 SomeSuccHasSame = true;
2411 case S_MovableRelease:
2412 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2413 AllSuccsHaveSame = false;
2416 llvm_unreachable("bottom-up pointer in retain state!");
2419 // If the state at the other end of any of the successor edges
2420 // matches the current state, require all edges to match. This
2421 // guards against loops in the middle of a sequence.
2422 if (SomeSuccHasSame && !AllSuccsHaveSame)
2423 S.ClearSequenceProgress();
2426 case S_CanRelease: {
2427 const Value *Arg = I->first;
2428 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2429 bool SomeSuccHasSame = false;
2430 bool AllSuccsHaveSame = true;
2431 PtrState &S = MyStates.getPtrTopDownState(Arg);
2432 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2433 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2434 switch (SuccS.GetSeq()) {
2436 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2437 S.ClearSequenceProgress();
2441 SomeSuccHasSame = true;
2445 case S_MovableRelease:
2447 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2448 AllSuccsHaveSame = false;
2451 llvm_unreachable("bottom-up pointer in retain state!");
2454 // If the state at the other end of any of the successor edges
2455 // matches the current state, require all edges to match. This
2456 // guards against loops in the middle of a sequence.
2457 if (SomeSuccHasSame && !AllSuccsHaveSame)
2458 S.ClearSequenceProgress();
2465 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2466 DenseMap<const BasicBlock *, BBState> &BBStates,
2467 MapVector<Value *, RRInfo> &Retains) {
2468 bool NestingDetected = false;
2469 BBState &MyStates = BBStates[BB];
2471 // Merge the states from each successor to compute the initial state
2472 // for the current block.
2473 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2474 succ_const_iterator SI(TI), SE(TI, false);
2476 MyStates.SetAsExit();
2479 const BasicBlock *Succ = *SI++;
2482 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2483 // If we haven't seen this node yet, then we've found a CFG cycle.
2484 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2485 if (I == BBStates.end())
2487 MyStates.InitFromSucc(I->second);
2491 I = BBStates.find(Succ);
2492 if (I != BBStates.end())
2493 MyStates.MergeSucc(I->second);
2499 // Visit all the instructions, bottom-up.
2500 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2501 Instruction *Inst = llvm::prior(I);
2502 InstructionClass Class = GetInstructionClass(Inst);
2503 const Value *Arg = 0;
2507 Arg = GetObjCArg(Inst);
2509 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2511 // If we see two releases in a row on the same pointer. If so, make
2512 // a note, and we'll cicle back to revisit it after we've
2513 // hopefully eliminated the second release, which may allow us to
2514 // eliminate the first release too.
2515 // Theoretically we could implement removal of nested retain+release
2516 // pairs by making PtrState hold a stack of states, but this is
2517 // simple and avoids adding overhead for the non-nested case.
2518 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2519 NestingDetected = true;
2523 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2524 S.SetSeq(ReleaseMetadata ? S_MovableRelease : S_Release);
2525 S.RRI.ReleaseMetadata = ReleaseMetadata;
2526 S.RRI.KnownSafe = S.IsKnownNested() || S.IsKnownIncremented();
2527 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2528 S.RRI.Calls.insert(Inst);
2530 S.IncrementRefCount();
2531 S.IncrementNestCount();
2534 case IC_RetainBlock:
2535 // An objc_retainBlock call with just a use may need to be kept,
2536 // because it may be copying a block from the stack to the heap.
2537 if (!IsRetainBlockOptimizable(Inst))
2542 Arg = GetObjCArg(Inst);
2544 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2545 S.DecrementRefCount();
2546 S.SetAtLeastOneRefCount();
2547 S.DecrementNestCount();
2549 switch (S.GetSeq()) {
2552 case S_MovableRelease:
2554 S.RRI.ReverseInsertPts.clear();
2557 // Don't do retain+release tracking for IC_RetainRV, because it's
2558 // better to let it remain as the first instruction after a call.
2559 if (Class != IC_RetainRV) {
2560 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2561 Retains[Inst] = S.RRI;
2563 S.ClearSequenceProgress();
2568 llvm_unreachable("bottom-up pointer in retain state!");
2572 case IC_AutoreleasepoolPop:
2573 // Conservatively, clear MyStates for all known pointers.
2574 MyStates.clearBottomUpPointers();
2576 case IC_AutoreleasepoolPush:
2578 // These are irrelevant.
2584 // Consider any other possible effects of this instruction on each
2585 // pointer being tracked.
2586 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2587 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2588 const Value *Ptr = MI->first;
2590 continue; // Handled above.
2591 PtrState &S = MI->second;
2592 Sequence Seq = S.GetSeq();
2594 // Check for possible releases.
2595 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2596 S.DecrementRefCount();
2599 S.SetSeq(S_CanRelease);
2603 case S_MovableRelease:
2608 llvm_unreachable("bottom-up pointer in retain state!");
2612 // Check for possible direct uses.
2615 case S_MovableRelease:
2616 if (CanUse(Inst, Ptr, PA, Class)) {
2617 assert(S.RRI.ReverseInsertPts.empty());
2618 S.RRI.ReverseInsertPts.insert(Inst);
2620 } else if (Seq == S_Release &&
2621 (Class == IC_User || Class == IC_CallOrUser)) {
2622 // Non-movable releases depend on any possible objc pointer use.
2624 assert(S.RRI.ReverseInsertPts.empty());
2625 S.RRI.ReverseInsertPts.insert(Inst);
2629 if (CanUse(Inst, Ptr, PA, Class))
2637 llvm_unreachable("bottom-up pointer in retain state!");
2642 return NestingDetected;
2646 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2647 DenseMap<const BasicBlock *, BBState> &BBStates,
2648 DenseMap<Value *, RRInfo> &Releases) {
2649 bool NestingDetected = false;
2650 BBState &MyStates = BBStates[BB];
2652 // Merge the states from each predecessor to compute the initial state
2653 // for the current block.
2654 const_pred_iterator PI(BB), PE(BB, false);
2656 MyStates.SetAsEntry();
2659 const BasicBlock *Pred = *PI++;
2662 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2663 // If we haven't seen this node yet, then we've found a CFG cycle.
2664 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2665 if (I == BBStates.end() || !I->second.isVisitedTopDown())
2667 MyStates.InitFromPred(I->second);
2671 I = BBStates.find(Pred);
2672 if (I != BBStates.end() && I->second.isVisitedTopDown())
2673 MyStates.MergePred(I->second);
2679 // Visit all the instructions, top-down.
2680 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2681 Instruction *Inst = I;
2682 InstructionClass Class = GetInstructionClass(Inst);
2683 const Value *Arg = 0;
2686 case IC_RetainBlock:
2687 // An objc_retainBlock call with just a use may need to be kept,
2688 // because it may be copying a block from the stack to the heap.
2689 if (!IsRetainBlockOptimizable(Inst))
2694 Arg = GetObjCArg(Inst);
2696 PtrState &S = MyStates.getPtrTopDownState(Arg);
2698 // Don't do retain+release tracking for IC_RetainRV, because it's
2699 // better to let it remain as the first instruction after a call.
2700 if (Class != IC_RetainRV) {
2701 // If we see two retains in a row on the same pointer. If so, make
2702 // a note, and we'll cicle back to revisit it after we've
2703 // hopefully eliminated the second retain, which may allow us to
2704 // eliminate the first retain too.
2705 // Theoretically we could implement removal of nested retain+release
2706 // pairs by making PtrState hold a stack of states, but this is
2707 // simple and avoids adding overhead for the non-nested case.
2708 if (S.GetSeq() == S_Retain)
2709 NestingDetected = true;
2713 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2714 // Don't check S.IsKnownIncremented() here because it's not
2716 S.RRI.KnownSafe = S.IsKnownNested();
2717 S.RRI.Calls.insert(Inst);
2720 S.SetAtLeastOneRefCount();
2721 S.IncrementRefCount();
2722 S.IncrementNestCount();
2726 Arg = GetObjCArg(Inst);
2728 PtrState &S = MyStates.getPtrTopDownState(Arg);
2729 S.DecrementRefCount();
2730 S.DecrementNestCount();
2732 switch (S.GetSeq()) {
2735 S.RRI.ReverseInsertPts.clear();
2738 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2739 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2740 Releases[Inst] = S.RRI;
2741 S.ClearSequenceProgress();
2747 case S_MovableRelease:
2748 llvm_unreachable("top-down pointer in release state!");
2752 case IC_AutoreleasepoolPop:
2753 // Conservatively, clear MyStates for all known pointers.
2754 MyStates.clearTopDownPointers();
2756 case IC_AutoreleasepoolPush:
2758 // These are irrelevant.
2764 // Consider any other possible effects of this instruction on each
2765 // pointer being tracked.
2766 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2767 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2768 const Value *Ptr = MI->first;
2770 continue; // Handled above.
2771 PtrState &S = MI->second;
2772 Sequence Seq = S.GetSeq();
2774 // Check for possible releases.
2775 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2776 S.DecrementRefCount();
2779 S.SetSeq(S_CanRelease);
2780 assert(S.RRI.ReverseInsertPts.empty());
2781 S.RRI.ReverseInsertPts.insert(Inst);
2783 // One call can't cause a transition from S_Retain to S_CanRelease
2784 // and S_CanRelease to S_Use. If we've made the first transition,
2793 case S_MovableRelease:
2794 llvm_unreachable("top-down pointer in release state!");
2798 // Check for possible direct uses.
2801 if (CanUse(Inst, Ptr, PA, Class))
2810 case S_MovableRelease:
2811 llvm_unreachable("top-down pointer in release state!");
2816 CheckForCFGHazards(BB, BBStates, MyStates);
2817 return NestingDetected;
2821 ComputePostOrders(Function &F,
2822 SmallVectorImpl<BasicBlock *> &PostOrder,
2823 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder) {
2824 /// Backedges - Backedges detected in the DFS. These edges will be
2825 /// ignored in the reverse-CFG DFS, so that loops with multiple exits will be
2826 /// traversed in the desired order.
2827 DenseSet<std::pair<BasicBlock *, BasicBlock *> > Backedges;
2829 /// Visited - The visited set, for doing DFS walks.
2830 SmallPtrSet<BasicBlock *, 16> Visited;
2832 // Do DFS, computing the PostOrder.
2833 SmallPtrSet<BasicBlock *, 16> OnStack;
2834 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2835 BasicBlock *EntryBB = &F.getEntryBlock();
2836 SuccStack.push_back(std::make_pair(EntryBB, succ_begin(EntryBB)));
2837 Visited.insert(EntryBB);
2838 OnStack.insert(EntryBB);
2841 succ_iterator End = succ_end(SuccStack.back().first);
2842 while (SuccStack.back().second != End) {
2843 BasicBlock *BB = *SuccStack.back().second++;
2844 if (Visited.insert(BB)) {
2845 SuccStack.push_back(std::make_pair(BB, succ_begin(BB)));
2849 if (OnStack.count(BB))
2850 Backedges.insert(std::make_pair(SuccStack.back().first, BB));
2852 OnStack.erase(SuccStack.back().first);
2853 PostOrder.push_back(SuccStack.pop_back_val().first);
2854 } while (!SuccStack.empty());
2858 // Compute the exits, which are the starting points for reverse-CFG DFS.
2859 SmallVector<BasicBlock *, 4> Exits;
2860 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2862 if (BB->getTerminator()->getNumSuccessors() == 0)
2863 Exits.push_back(BB);
2866 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2867 SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> PredStack;
2868 for (SmallVectorImpl<BasicBlock *>::iterator I = Exits.begin(), E = Exits.end();
2870 BasicBlock *ExitBB = *I;
2871 PredStack.push_back(std::make_pair(ExitBB, pred_begin(ExitBB)));
2872 Visited.insert(ExitBB);
2873 while (!PredStack.empty()) {
2874 reverse_dfs_next_succ:
2875 pred_iterator End = pred_end(PredStack.back().first);
2876 while (PredStack.back().second != End) {
2877 BasicBlock *BB = *PredStack.back().second++;
2878 // Skip backedges detected in the forward-CFG DFS.
2879 if (Backedges.count(std::make_pair(BB, PredStack.back().first)))
2881 if (Visited.insert(BB)) {
2882 PredStack.push_back(std::make_pair(BB, pred_begin(BB)));
2883 goto reverse_dfs_next_succ;
2886 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2891 // Visit - Visit the function both top-down and bottom-up.
2893 ObjCARCOpt::Visit(Function &F,
2894 DenseMap<const BasicBlock *, BBState> &BBStates,
2895 MapVector<Value *, RRInfo> &Retains,
2896 DenseMap<Value *, RRInfo> &Releases) {
2898 // Use reverse-postorder traversals, because we magically know that loops
2899 // will be well behaved, i.e. they won't repeatedly call retain on a single
2900 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2901 // class here because we want the reverse-CFG postorder to consider each
2902 // function exit point, and we want to ignore selected cycle edges.
2903 SmallVector<BasicBlock *, 16> PostOrder;
2904 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2905 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder);
2907 // Use reverse-postorder on the reverse CFG for bottom-up.
2908 bool BottomUpNestingDetected = false;
2909 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2910 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2912 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
2914 // Use reverse-postorder for top-down.
2915 bool TopDownNestingDetected = false;
2916 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2917 PostOrder.rbegin(), E = PostOrder.rend();
2919 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
2921 return TopDownNestingDetected && BottomUpNestingDetected;
2924 /// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
2925 void ObjCARCOpt::MoveCalls(Value *Arg,
2926 RRInfo &RetainsToMove,
2927 RRInfo &ReleasesToMove,
2928 MapVector<Value *, RRInfo> &Retains,
2929 DenseMap<Value *, RRInfo> &Releases,
2930 SmallVectorImpl<Instruction *> &DeadInsts,
2932 Type *ArgTy = Arg->getType();
2933 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2935 // Insert the new retain and release calls.
2936 for (SmallPtrSet<Instruction *, 2>::const_iterator
2937 PI = ReleasesToMove.ReverseInsertPts.begin(),
2938 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2939 Instruction *InsertPt = *PI;
2940 Value *MyArg = ArgTy == ParamTy ? Arg :
2941 new BitCastInst(Arg, ParamTy, "", InsertPt);
2943 CallInst::Create(RetainsToMove.IsRetainBlock ?
2944 getRetainBlockCallee(M) : getRetainCallee(M),
2945 MyArg, "", InsertPt);
2946 Call->setDoesNotThrow();
2947 if (RetainsToMove.IsRetainBlock)
2948 Call->setMetadata(CopyOnEscapeMDKind,
2949 MDNode::get(M->getContext(), ArrayRef<Value *>()));
2951 Call->setTailCall();
2953 for (SmallPtrSet<Instruction *, 2>::const_iterator
2954 PI = RetainsToMove.ReverseInsertPts.begin(),
2955 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2956 Instruction *LastUse = *PI;
2957 Instruction *InsertPts[] = { 0, 0, 0 };
2958 if (InvokeInst *II = dyn_cast<InvokeInst>(LastUse)) {
2959 // We can't insert code immediately after an invoke instruction, so
2960 // insert code at the beginning of both successor blocks instead.
2961 // The invoke's return value isn't available in the unwind block,
2962 // but our releases will never depend on it, because they must be
2963 // paired with retains from before the invoke.
2964 InsertPts[0] = II->getNormalDest()->getFirstInsertionPt();
2965 InsertPts[1] = II->getUnwindDest()->getFirstInsertionPt();
2967 // Insert code immediately after the last use.
2968 InsertPts[0] = llvm::next(BasicBlock::iterator(LastUse));
2971 for (Instruction **I = InsertPts; *I; ++I) {
2972 Instruction *InsertPt = *I;
2973 Value *MyArg = ArgTy == ParamTy ? Arg :
2974 new BitCastInst(Arg, ParamTy, "", InsertPt);
2975 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2977 // Attach a clang.imprecise_release metadata tag, if appropriate.
2978 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2979 Call->setMetadata(ImpreciseReleaseMDKind, M);
2980 Call->setDoesNotThrow();
2981 if (ReleasesToMove.IsTailCallRelease)
2982 Call->setTailCall();
2986 // Delete the original retain and release calls.
2987 for (SmallPtrSet<Instruction *, 2>::const_iterator
2988 AI = RetainsToMove.Calls.begin(),
2989 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2990 Instruction *OrigRetain = *AI;
2991 Retains.blot(OrigRetain);
2992 DeadInsts.push_back(OrigRetain);
2994 for (SmallPtrSet<Instruction *, 2>::const_iterator
2995 AI = ReleasesToMove.Calls.begin(),
2996 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2997 Instruction *OrigRelease = *AI;
2998 Releases.erase(OrigRelease);
2999 DeadInsts.push_back(OrigRelease);
3004 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3006 MapVector<Value *, RRInfo> &Retains,
3007 DenseMap<Value *, RRInfo> &Releases,
3009 bool AnyPairsCompletelyEliminated = false;
3010 RRInfo RetainsToMove;
3011 RRInfo ReleasesToMove;
3012 SmallVector<Instruction *, 4> NewRetains;
3013 SmallVector<Instruction *, 4> NewReleases;
3014 SmallVector<Instruction *, 8> DeadInsts;
3016 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
3017 E = Retains.end(); I != E; ++I) {
3018 Value *V = I->first;
3019 if (!V) continue; // blotted
3021 Instruction *Retain = cast<Instruction>(V);
3022 Value *Arg = GetObjCArg(Retain);
3024 // If the object being released is in static or stack storage, we know it's
3025 // not being managed by ObjC reference counting, so we can delete pairs
3026 // regardless of what possible decrements or uses lie between them.
3027 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
3029 // A constant pointer can't be pointing to an object on the heap. It may
3030 // be reference-counted, but it won't be deleted.
3031 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3032 if (const GlobalVariable *GV =
3033 dyn_cast<GlobalVariable>(
3034 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3035 if (GV->isConstant())
3038 // If a pair happens in a region where it is known that the reference count
3039 // is already incremented, we can similarly ignore possible decrements.
3040 bool KnownSafeTD = true, KnownSafeBU = true;
3042 // Connect the dots between the top-down-collected RetainsToMove and
3043 // bottom-up-collected ReleasesToMove to form sets of related calls.
3044 // This is an iterative process so that we connect multiple releases
3045 // to multiple retains if needed.
3046 unsigned OldDelta = 0;
3047 unsigned NewDelta = 0;
3048 unsigned OldCount = 0;
3049 unsigned NewCount = 0;
3050 bool FirstRelease = true;
3051 bool FirstRetain = true;
3052 NewRetains.push_back(Retain);
3054 for (SmallVectorImpl<Instruction *>::const_iterator
3055 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3056 Instruction *NewRetain = *NI;
3057 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3058 assert(It != Retains.end());
3059 const RRInfo &NewRetainRRI = It->second;
3060 KnownSafeTD &= NewRetainRRI.KnownSafe;
3061 for (SmallPtrSet<Instruction *, 2>::const_iterator
3062 LI = NewRetainRRI.Calls.begin(),
3063 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3064 Instruction *NewRetainRelease = *LI;
3065 DenseMap<Value *, RRInfo>::const_iterator Jt =
3066 Releases.find(NewRetainRelease);
3067 if (Jt == Releases.end())
3069 const RRInfo &NewRetainReleaseRRI = Jt->second;
3070 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3071 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3073 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3075 // Merge the ReleaseMetadata and IsTailCallRelease values.
3077 ReleasesToMove.ReleaseMetadata =
3078 NewRetainReleaseRRI.ReleaseMetadata;
3079 ReleasesToMove.IsTailCallRelease =
3080 NewRetainReleaseRRI.IsTailCallRelease;
3081 FirstRelease = false;
3083 if (ReleasesToMove.ReleaseMetadata !=
3084 NewRetainReleaseRRI.ReleaseMetadata)
3085 ReleasesToMove.ReleaseMetadata = 0;
3086 if (ReleasesToMove.IsTailCallRelease !=
3087 NewRetainReleaseRRI.IsTailCallRelease)
3088 ReleasesToMove.IsTailCallRelease = false;
3091 // Collect the optimal insertion points.
3093 for (SmallPtrSet<Instruction *, 2>::const_iterator
3094 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3095 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3097 Instruction *RIP = *RI;
3098 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3099 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3101 NewReleases.push_back(NewRetainRelease);
3106 if (NewReleases.empty()) break;
3108 // Back the other way.
3109 for (SmallVectorImpl<Instruction *>::const_iterator
3110 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3111 Instruction *NewRelease = *NI;
3112 DenseMap<Value *, RRInfo>::const_iterator It =
3113 Releases.find(NewRelease);
3114 assert(It != Releases.end());
3115 const RRInfo &NewReleaseRRI = It->second;
3116 KnownSafeBU &= NewReleaseRRI.KnownSafe;
3117 for (SmallPtrSet<Instruction *, 2>::const_iterator
3118 LI = NewReleaseRRI.Calls.begin(),
3119 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3120 Instruction *NewReleaseRetain = *LI;
3121 MapVector<Value *, RRInfo>::const_iterator Jt =
3122 Retains.find(NewReleaseRetain);
3123 if (Jt == Retains.end())
3125 const RRInfo &NewReleaseRetainRRI = Jt->second;
3126 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3127 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3128 unsigned PathCount =
3129 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3130 OldDelta += PathCount;
3131 OldCount += PathCount;
3133 // Merge the IsRetainBlock values.
3135 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3136 FirstRetain = false;
3137 } else if (ReleasesToMove.IsRetainBlock !=
3138 NewReleaseRetainRRI.IsRetainBlock)
3139 // It's not possible to merge the sequences if one uses
3140 // objc_retain and the other uses objc_retainBlock.
3143 // Collect the optimal insertion points.
3145 for (SmallPtrSet<Instruction *, 2>::const_iterator
3146 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3147 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3149 Instruction *RIP = *RI;
3150 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3151 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3152 NewDelta += PathCount;
3153 NewCount += PathCount;
3156 NewRetains.push_back(NewReleaseRetain);
3160 NewReleases.clear();
3161 if (NewRetains.empty()) break;
3164 // If the pointer is known incremented or nested, we can safely delete the
3165 // pair regardless of what's between them.
3166 if (KnownSafeTD || KnownSafeBU) {
3167 RetainsToMove.ReverseInsertPts.clear();
3168 ReleasesToMove.ReverseInsertPts.clear();
3171 // Determine whether the new insertion points we computed preserve the
3172 // balance of retain and release calls through the program.
3173 // TODO: If the fully aggressive solution isn't valid, try to find a
3174 // less aggressive solution which is.
3179 // Determine whether the original call points are balanced in the retain and
3180 // release calls through the program. If not, conservatively don't touch
3182 // TODO: It's theoretically possible to do code motion in this case, as
3183 // long as the existing imbalances are maintained.
3187 // Ok, everything checks out and we're all set. Let's move some code!
3189 AnyPairsCompletelyEliminated = NewCount == 0;
3190 NumRRs += OldCount - NewCount;
3191 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3192 Retains, Releases, DeadInsts, M);
3195 NewReleases.clear();
3197 RetainsToMove.clear();
3198 ReleasesToMove.clear();
3201 // Now that we're done moving everything, we can delete the newly dead
3202 // instructions, as we no longer need them as insert points.
3203 while (!DeadInsts.empty())
3204 EraseInstruction(DeadInsts.pop_back_val());
3206 return AnyPairsCompletelyEliminated;
3209 /// OptimizeWeakCalls - Weak pointer optimizations.
3210 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3211 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3212 // itself because it uses AliasAnalysis and we need to do provenance
3214 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3215 Instruction *Inst = &*I++;
3216 InstructionClass Class = GetBasicInstructionClass(Inst);
3217 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3220 // Delete objc_loadWeak calls with no users.
3221 if (Class == IC_LoadWeak && Inst->use_empty()) {
3222 Inst->eraseFromParent();
3226 // TODO: For now, just look for an earlier available version of this value
3227 // within the same block. Theoretically, we could do memdep-style non-local
3228 // analysis too, but that would want caching. A better approach would be to
3229 // use the technique that EarlyCSE uses.
3230 inst_iterator Current = llvm::prior(I);
3231 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3232 for (BasicBlock::iterator B = CurrentBB->begin(),
3233 J = Current.getInstructionIterator();
3235 Instruction *EarlierInst = &*llvm::prior(J);
3236 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3237 switch (EarlierClass) {
3239 case IC_LoadWeakRetained: {
3240 // If this is loading from the same pointer, replace this load's value
3242 CallInst *Call = cast<CallInst>(Inst);
3243 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3244 Value *Arg = Call->getArgOperand(0);
3245 Value *EarlierArg = EarlierCall->getArgOperand(0);
3246 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3247 case AliasAnalysis::MustAlias:
3249 // If the load has a builtin retain, insert a plain retain for it.
3250 if (Class == IC_LoadWeakRetained) {
3252 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3256 // Zap the fully redundant load.
3257 Call->replaceAllUsesWith(EarlierCall);
3258 Call->eraseFromParent();
3260 case AliasAnalysis::MayAlias:
3261 case AliasAnalysis::PartialAlias:
3263 case AliasAnalysis::NoAlias:
3270 // If this is storing to the same pointer and has the same size etc.
3271 // replace this load's value with the stored value.
3272 CallInst *Call = cast<CallInst>(Inst);
3273 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3274 Value *Arg = Call->getArgOperand(0);
3275 Value *EarlierArg = EarlierCall->getArgOperand(0);
3276 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3277 case AliasAnalysis::MustAlias:
3279 // If the load has a builtin retain, insert a plain retain for it.
3280 if (Class == IC_LoadWeakRetained) {
3282 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3286 // Zap the fully redundant load.
3287 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3288 Call->eraseFromParent();
3290 case AliasAnalysis::MayAlias:
3291 case AliasAnalysis::PartialAlias:
3293 case AliasAnalysis::NoAlias:
3300 // TOOD: Grab the copied value.
3302 case IC_AutoreleasepoolPush:
3305 // Weak pointers are only modified through the weak entry points
3306 // (and arbitrary calls, which could call the weak entry points).
3309 // Anything else could modify the weak pointer.
3316 // Then, for each destroyWeak with an alloca operand, check to see if
3317 // the alloca and all its users can be zapped.
3318 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3319 Instruction *Inst = &*I++;
3320 InstructionClass Class = GetBasicInstructionClass(Inst);
3321 if (Class != IC_DestroyWeak)
3324 CallInst *Call = cast<CallInst>(Inst);
3325 Value *Arg = Call->getArgOperand(0);
3326 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3327 for (Value::use_iterator UI = Alloca->use_begin(),
3328 UE = Alloca->use_end(); UI != UE; ++UI) {
3329 Instruction *UserInst = cast<Instruction>(*UI);
3330 switch (GetBasicInstructionClass(UserInst)) {
3333 case IC_DestroyWeak:
3340 for (Value::use_iterator UI = Alloca->use_begin(),
3341 UE = Alloca->use_end(); UI != UE; ) {
3342 CallInst *UserInst = cast<CallInst>(*UI++);
3343 if (!UserInst->use_empty())
3344 UserInst->replaceAllUsesWith(UserInst->getArgOperand(0));
3345 UserInst->eraseFromParent();
3347 Alloca->eraseFromParent();
3353 /// OptimizeSequences - Identify program paths which execute sequences of
3354 /// retains and releases which can be eliminated.
3355 bool ObjCARCOpt::OptimizeSequences(Function &F) {
3356 /// Releases, Retains - These are used to store the results of the main flow
3357 /// analysis. These use Value* as the key instead of Instruction* so that the
3358 /// map stays valid when we get around to rewriting code and calls get
3359 /// replaced by arguments.
3360 DenseMap<Value *, RRInfo> Releases;
3361 MapVector<Value *, RRInfo> Retains;
3363 /// BBStates, This is used during the traversal of the function to track the
3364 /// states for each identified object at each block.
3365 DenseMap<const BasicBlock *, BBState> BBStates;
3367 // Analyze the CFG of the function, and all instructions.
3368 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3371 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3375 /// OptimizeReturns - Look for this pattern:
3377 /// %call = call i8* @something(...)
3378 /// %2 = call i8* @objc_retain(i8* %call)
3379 /// %3 = call i8* @objc_autorelease(i8* %2)
3382 /// And delete the retain and autorelease.
3384 /// Otherwise if it's just this:
3386 /// %3 = call i8* @objc_autorelease(i8* %2)
3389 /// convert the autorelease to autoreleaseRV.
3390 void ObjCARCOpt::OptimizeReturns(Function &F) {
3391 if (!F.getReturnType()->isPointerTy())
3394 SmallPtrSet<Instruction *, 4> DependingInstructions;
3395 SmallPtrSet<const BasicBlock *, 4> Visited;
3396 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3397 BasicBlock *BB = FI;
3398 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3401 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3402 FindDependencies(NeedsPositiveRetainCount, Arg,
3403 BB, Ret, DependingInstructions, Visited, PA);
3404 if (DependingInstructions.size() != 1)
3408 CallInst *Autorelease =
3409 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3412 InstructionClass AutoreleaseClass =
3413 GetBasicInstructionClass(Autorelease);
3414 if (!IsAutorelease(AutoreleaseClass))
3416 if (GetObjCArg(Autorelease) != Arg)
3419 DependingInstructions.clear();
3422 // Check that there is nothing that can affect the reference
3423 // count between the autorelease and the retain.
3424 FindDependencies(CanChangeRetainCount, Arg,
3425 BB, Autorelease, DependingInstructions, Visited, PA);
3426 if (DependingInstructions.size() != 1)
3431 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3433 // Check that we found a retain with the same argument.
3435 !IsRetain(GetBasicInstructionClass(Retain)) ||
3436 GetObjCArg(Retain) != Arg)
3439 DependingInstructions.clear();
3442 // Convert the autorelease to an autoreleaseRV, since it's
3443 // returning the value.
3444 if (AutoreleaseClass == IC_Autorelease) {
3445 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3446 AutoreleaseClass = IC_AutoreleaseRV;
3449 // Check that there is nothing that can affect the reference
3450 // count between the retain and the call.
3451 // Note that Retain need not be in BB.
3452 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3453 DependingInstructions, Visited, PA);
3454 if (DependingInstructions.size() != 1)
3459 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3461 // Check that the pointer is the return value of the call.
3462 if (!Call || Arg != Call)
3465 // Check that the call is a regular call.
3466 InstructionClass Class = GetBasicInstructionClass(Call);
3467 if (Class != IC_CallOrUser && Class != IC_Call)
3470 // If so, we can zap the retain and autorelease.
3473 EraseInstruction(Retain);
3474 EraseInstruction(Autorelease);
3480 DependingInstructions.clear();
3485 bool ObjCARCOpt::doInitialization(Module &M) {
3489 Run = ModuleHasARC(M);
3493 // Identify the imprecise release metadata kind.
3494 ImpreciseReleaseMDKind =
3495 M.getContext().getMDKindID("clang.imprecise_release");
3496 CopyOnEscapeMDKind =
3497 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3499 // Intuitively, objc_retain and others are nocapture, however in practice
3500 // they are not, because they return their argument value. And objc_release
3501 // calls finalizers.
3503 // These are initialized lazily.
3505 AutoreleaseRVCallee = 0;
3508 RetainBlockCallee = 0;
3509 AutoreleaseCallee = 0;
3514 bool ObjCARCOpt::runOnFunction(Function &F) {
3518 // If nothing in the Module uses ARC, don't do anything.
3524 PA.setAA(&getAnalysis<AliasAnalysis>());
3526 // This pass performs several distinct transformations. As a compile-time aid
3527 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3528 // library functions aren't declared.
3530 // Preliminary optimizations. This also computs UsedInThisFunction.
3531 OptimizeIndividualCalls(F);
3533 // Optimizations for weak pointers.
3534 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3535 (1 << IC_LoadWeakRetained) |
3536 (1 << IC_StoreWeak) |
3537 (1 << IC_InitWeak) |
3538 (1 << IC_CopyWeak) |
3539 (1 << IC_MoveWeak) |
3540 (1 << IC_DestroyWeak)))
3541 OptimizeWeakCalls(F);
3543 // Optimizations for retain+release pairs.
3544 if (UsedInThisFunction & ((1 << IC_Retain) |
3545 (1 << IC_RetainRV) |
3546 (1 << IC_RetainBlock)))
3547 if (UsedInThisFunction & (1 << IC_Release))
3548 // Run OptimizeSequences until it either stops making changes or
3549 // no retain+release pair nesting is detected.
3550 while (OptimizeSequences(F)) {}
3552 // Optimizations if objc_autorelease is used.
3553 if (UsedInThisFunction &
3554 ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
3560 void ObjCARCOpt::releaseMemory() {
3564 //===----------------------------------------------------------------------===//
3566 //===----------------------------------------------------------------------===//
3568 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
3569 // dominated by single calls.
3571 #include "llvm/Operator.h"
3572 #include "llvm/InlineAsm.h"
3573 #include "llvm/Analysis/Dominators.h"
3575 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3578 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3579 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3580 class ObjCARCContract : public FunctionPass {
3584 ProvenanceAnalysis PA;
3586 /// Run - A flag indicating whether this optimization pass should run.
3589 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3590 /// functions, for use in creating calls to them. These are initialized
3591 /// lazily to avoid cluttering up the Module with unused declarations.
3592 Constant *StoreStrongCallee,
3593 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3595 /// RetainRVMarker - The inline asm string to insert between calls and
3596 /// RetainRV calls to make the optimization work on targets which need it.
3597 const MDString *RetainRVMarker;
3599 Constant *getStoreStrongCallee(Module *M);
3600 Constant *getRetainAutoreleaseCallee(Module *M);
3601 Constant *getRetainAutoreleaseRVCallee(Module *M);
3603 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3604 InstructionClass Class,
3605 SmallPtrSet<Instruction *, 4>
3606 &DependingInstructions,
3607 SmallPtrSet<const BasicBlock *, 4>
3610 void ContractRelease(Instruction *Release,
3611 inst_iterator &Iter);
3613 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3614 virtual bool doInitialization(Module &M);
3615 virtual bool runOnFunction(Function &F);
3619 ObjCARCContract() : FunctionPass(ID) {
3620 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3625 char ObjCARCContract::ID = 0;
3626 INITIALIZE_PASS_BEGIN(ObjCARCContract,
3627 "objc-arc-contract", "ObjC ARC contraction", false, false)
3628 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3629 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3630 INITIALIZE_PASS_END(ObjCARCContract,
3631 "objc-arc-contract", "ObjC ARC contraction", false, false)
3633 Pass *llvm::createObjCARCContractPass() {
3634 return new ObjCARCContract();
3637 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3638 AU.addRequired<AliasAnalysis>();
3639 AU.addRequired<DominatorTree>();
3640 AU.setPreservesCFG();
3643 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3644 if (!StoreStrongCallee) {
3645 LLVMContext &C = M->getContext();
3646 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3647 Type *I8XX = PointerType::getUnqual(I8X);
3648 std::vector<Type *> Params;
3649 Params.push_back(I8XX);
3650 Params.push_back(I8X);
3652 AttrListPtr Attributes;
3653 Attributes.addAttr(~0u, Attribute::NoUnwind);
3654 Attributes.addAttr(1, Attribute::NoCapture);
3657 M->getOrInsertFunction(
3659 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3662 return StoreStrongCallee;
3665 Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3666 if (!RetainAutoreleaseCallee) {
3667 LLVMContext &C = M->getContext();
3668 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3669 std::vector<Type *> Params;
3670 Params.push_back(I8X);
3672 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3673 AttrListPtr Attributes;
3674 Attributes.addAttr(~0u, Attribute::NoUnwind);
3675 RetainAutoreleaseCallee =
3676 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3678 return RetainAutoreleaseCallee;
3681 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3682 if (!RetainAutoreleaseRVCallee) {
3683 LLVMContext &C = M->getContext();
3684 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3685 std::vector<Type *> Params;
3686 Params.push_back(I8X);
3688 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3689 AttrListPtr Attributes;
3690 Attributes.addAttr(~0u, Attribute::NoUnwind);
3691 RetainAutoreleaseRVCallee =
3692 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3695 return RetainAutoreleaseRVCallee;
3698 /// ContractAutorelease - Merge an autorelease with a retain into a fused
3701 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3702 InstructionClass Class,
3703 SmallPtrSet<Instruction *, 4>
3704 &DependingInstructions,
3705 SmallPtrSet<const BasicBlock *, 4>
3707 const Value *Arg = GetObjCArg(Autorelease);
3709 // Check that there are no instructions between the retain and the autorelease
3710 // (such as an autorelease_pop) which may change the count.
3711 CallInst *Retain = 0;
3712 if (Class == IC_AutoreleaseRV)
3713 FindDependencies(RetainAutoreleaseRVDep, Arg,
3714 Autorelease->getParent(), Autorelease,
3715 DependingInstructions, Visited, PA);
3717 FindDependencies(RetainAutoreleaseDep, Arg,
3718 Autorelease->getParent(), Autorelease,
3719 DependingInstructions, Visited, PA);
3722 if (DependingInstructions.size() != 1) {
3723 DependingInstructions.clear();
3727 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3728 DependingInstructions.clear();
3731 GetBasicInstructionClass(Retain) != IC_Retain ||
3732 GetObjCArg(Retain) != Arg)
3738 if (Class == IC_AutoreleaseRV)
3739 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3741 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3743 EraseInstruction(Autorelease);
3747 /// ContractRelease - Attempt to merge an objc_release with a store, load, and
3748 /// objc_retain to form an objc_storeStrong. This can be a little tricky because
3749 /// the instructions don't always appear in order, and there may be unrelated
3750 /// intervening instructions.
3751 void ObjCARCContract::ContractRelease(Instruction *Release,
3752 inst_iterator &Iter) {
3753 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
3754 if (!Load || !Load->isSimple()) return;
3756 // For now, require everything to be in one basic block.
3757 BasicBlock *BB = Release->getParent();
3758 if (Load->getParent() != BB) return;
3760 // Walk down to find the store.
3761 BasicBlock::iterator I = Load, End = BB->end();
3763 AliasAnalysis::Location Loc = AA->getLocation(Load);
3766 IsRetain(GetBasicInstructionClass(I)) ||
3767 !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
3769 StoreInst *Store = dyn_cast<StoreInst>(I);
3770 if (!Store || !Store->isSimple()) return;
3771 if (Store->getPointerOperand() != Loc.Ptr) return;
3773 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3775 // Walk up to find the retain.
3777 BasicBlock::iterator Begin = BB->begin();
3778 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3780 Instruction *Retain = I;
3781 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3782 if (GetObjCArg(Retain) != New) return;
3787 LLVMContext &C = Release->getContext();
3788 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3789 Type *I8XX = PointerType::getUnqual(I8X);
3791 Value *Args[] = { Load->getPointerOperand(), New };
3792 if (Args[0]->getType() != I8XX)
3793 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3794 if (Args[1]->getType() != I8X)
3795 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3796 CallInst *StoreStrong =
3797 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
3799 StoreStrong->setDoesNotThrow();
3800 StoreStrong->setDebugLoc(Store->getDebugLoc());
3802 if (&*Iter == Store) ++Iter;
3803 Store->eraseFromParent();
3804 Release->eraseFromParent();
3805 EraseInstruction(Retain);
3806 if (Load->use_empty())
3807 Load->eraseFromParent();
3810 bool ObjCARCContract::doInitialization(Module &M) {
3811 Run = ModuleHasARC(M);
3815 // These are initialized lazily.
3816 StoreStrongCallee = 0;
3817 RetainAutoreleaseCallee = 0;
3818 RetainAutoreleaseRVCallee = 0;
3820 // Initialize RetainRVMarker.
3822 if (NamedMDNode *NMD =
3823 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3824 if (NMD->getNumOperands() == 1) {
3825 const MDNode *N = NMD->getOperand(0);
3826 if (N->getNumOperands() == 1)
3827 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
3834 bool ObjCARCContract::runOnFunction(Function &F) {
3838 // If nothing in the Module uses ARC, don't do anything.
3843 AA = &getAnalysis<AliasAnalysis>();
3844 DT = &getAnalysis<DominatorTree>();
3846 PA.setAA(&getAnalysis<AliasAnalysis>());
3848 // For ObjC library calls which return their argument, replace uses of the
3849 // argument with uses of the call return value, if it dominates the use. This
3850 // reduces register pressure.
3851 SmallPtrSet<Instruction *, 4> DependingInstructions;
3852 SmallPtrSet<const BasicBlock *, 4> Visited;
3853 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3854 Instruction *Inst = &*I++;
3856 // Only these library routines return their argument. In particular,
3857 // objc_retainBlock does not necessarily return its argument.
3858 InstructionClass Class = GetBasicInstructionClass(Inst);
3861 case IC_FusedRetainAutorelease:
3862 case IC_FusedRetainAutoreleaseRV:
3864 case IC_Autorelease:
3865 case IC_AutoreleaseRV:
3866 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
3870 // If we're compiling for a target which needs a special inline-asm
3871 // marker to do the retainAutoreleasedReturnValue optimization,
3873 if (!RetainRVMarker)
3875 BasicBlock::iterator BBI = Inst;
3877 while (isNoopInstruction(BBI)) --BBI;
3878 if (&*BBI == GetObjCArg(Inst)) {
3880 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
3881 /*isVarArg=*/false),
3882 RetainRVMarker->getString(),
3883 /*Constraints=*/"", /*hasSideEffects=*/true);
3884 CallInst::Create(IA, "", Inst);
3889 // objc_initWeak(p, null) => *p = null
3890 CallInst *CI = cast<CallInst>(Inst);
3891 if (isNullOrUndef(CI->getArgOperand(1))) {
3893 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
3895 new StoreInst(Null, CI->getArgOperand(0), CI);
3896 CI->replaceAllUsesWith(Null);
3897 CI->eraseFromParent();
3902 ContractRelease(Inst, I);
3908 // Don't use GetObjCArg because we don't want to look through bitcasts
3909 // and such; to do the replacement, the argument must have type i8*.
3910 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
3912 // If we're compiling bugpointed code, don't get in trouble.
3913 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
3915 // Look through the uses of the pointer.
3916 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
3918 Use &U = UI.getUse();
3919 unsigned OperandNo = UI.getOperandNo();
3920 ++UI; // Increment UI now, because we may unlink its element.
3921 if (Instruction *UserInst = dyn_cast<Instruction>(U.getUser()))
3922 if (Inst != UserInst && DT->dominates(Inst, UserInst)) {
3924 Instruction *Replacement = Inst;
3925 Type *UseTy = U.get()->getType();
3926 if (PHINode *PHI = dyn_cast<PHINode>(UserInst)) {
3927 // For PHI nodes, insert the bitcast in the predecessor block.
3929 PHINode::getIncomingValueNumForOperand(OperandNo);
3931 PHI->getIncomingBlock(ValNo);
3932 if (Replacement->getType() != UseTy)
3933 Replacement = new BitCastInst(Replacement, UseTy, "",
3935 for (unsigned i = 0, e = PHI->getNumIncomingValues();
3937 if (PHI->getIncomingBlock(i) == BB) {
3938 // Keep the UI iterator valid.
3939 if (&PHI->getOperandUse(
3940 PHINode::getOperandNumForIncomingValue(i)) ==
3943 PHI->setIncomingValue(i, Replacement);
3946 if (Replacement->getType() != UseTy)
3947 Replacement = new BitCastInst(Replacement, UseTy, "", UserInst);
3953 // If Arg is a no-op casted pointer, strip one level of casts and
3955 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
3956 Arg = BI->getOperand(0);
3957 else if (isa<GEPOperator>(Arg) &&
3958 cast<GEPOperator>(Arg)->hasAllZeroIndices())
3959 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
3960 else if (isa<GlobalAlias>(Arg) &&
3961 !cast<GlobalAlias>(Arg)->mayBeOverridden())
3962 Arg = cast<GlobalAlias>(Arg)->getAliasee();