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, unsigned Depth = 0);
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, unsigned Depth) {
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 // This recursion depth limit is arbitrary. It's just great
935 // enough to cover known interesting testcases.
937 !JCS.onlyReadsMemory() &&
938 MayAutorelease(JCS, Depth + 1))
947 bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
948 bool Changed = false;
950 Instruction *Push = 0;
951 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
952 Instruction *Inst = I++;
953 switch (GetBasicInstructionClass(Inst)) {
954 case IC_AutoreleasepoolPush:
957 case IC_AutoreleasepoolPop:
958 // If this pop matches a push and nothing in between can autorelease,
960 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
962 Inst->eraseFromParent();
963 Push->eraseFromParent();
968 if (MayAutorelease(CallSite(Inst)))
979 bool ObjCARCAPElim::runOnModule(Module &M) {
983 // If nothing in the Module uses ARC, don't do anything.
984 if (!ModuleHasARC(M))
987 // Find the llvm.global_ctors variable, as the first step in
988 // identifying the global constructors.
989 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
993 assert(GV->hasDefinitiveInitializer() &&
994 "llvm.global_ctors is uncooperative!");
996 bool Changed = false;
998 // Dig the constructor functions out of GV's initializer.
999 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1000 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1003 // llvm.global_ctors is an array of pairs where the second members
1004 // are constructor functions.
1005 Function *F = cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1006 // Only look at function definitions.
1007 if (F->isDeclaration())
1009 // Only look at functions with one basic block.
1010 if (llvm::next(F->begin()) != F->end())
1012 // Ok, a single-block constructor function definition. Try to optimize it.
1013 Changed |= OptimizeBB(F->begin());
1019 //===----------------------------------------------------------------------===//
1020 // ARC optimization.
1021 //===----------------------------------------------------------------------===//
1023 // TODO: On code like this:
1026 // stuff_that_cannot_release()
1027 // objc_autorelease(%x)
1028 // stuff_that_cannot_release()
1030 // stuff_that_cannot_release()
1031 // objc_autorelease(%x)
1033 // The second retain and autorelease can be deleted.
1035 // TODO: It should be possible to delete
1036 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
1037 // pairs if nothing is actually autoreleased between them. Also, autorelease
1038 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1039 // after inlining) can be turned into plain release calls.
1041 // TODO: Critical-edge splitting. If the optimial insertion point is
1042 // a critical edge, the current algorithm has to fail, because it doesn't
1043 // know how to split edges. It should be possible to make the optimizer
1044 // think in terms of edges, rather than blocks, and then split critical
1047 // TODO: OptimizeSequences could generalized to be Interprocedural.
1049 // TODO: Recognize that a bunch of other objc runtime calls have
1050 // non-escaping arguments and non-releasing arguments, and may be
1051 // non-autoreleasing.
1053 // TODO: Sink autorelease calls as far as possible. Unfortunately we
1054 // usually can't sink them past other calls, which would be the main
1055 // case where it would be useful.
1057 // TODO: The pointer returned from objc_loadWeakRetained is retained.
1059 // TODO: Delete release+retain pairs (rare).
1061 #include "llvm/GlobalAlias.h"
1062 #include "llvm/Constants.h"
1063 #include "llvm/LLVMContext.h"
1064 #include "llvm/Support/ErrorHandling.h"
1065 #include "llvm/Support/CFG.h"
1066 #include "llvm/ADT/Statistic.h"
1067 #include "llvm/ADT/SmallPtrSet.h"
1068 #include "llvm/ADT/DenseSet.h"
1070 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1071 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1072 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1073 STATISTIC(NumRets, "Number of return value forwarding "
1074 "retain+autoreleaes eliminated");
1075 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1076 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1079 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1080 /// uses many of the same techniques, except it uses special ObjC-specific
1081 /// reasoning about pointer relationships.
1082 class ProvenanceAnalysis {
1085 typedef std::pair<const Value *, const Value *> ValuePairTy;
1086 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1087 CachedResultsTy CachedResults;
1089 bool relatedCheck(const Value *A, const Value *B);
1090 bool relatedSelect(const SelectInst *A, const Value *B);
1091 bool relatedPHI(const PHINode *A, const Value *B);
1093 // Do not implement.
1094 void operator=(const ProvenanceAnalysis &);
1095 ProvenanceAnalysis(const ProvenanceAnalysis &);
1098 ProvenanceAnalysis() {}
1100 void setAA(AliasAnalysis *aa) { AA = aa; }
1102 AliasAnalysis *getAA() const { return AA; }
1104 bool related(const Value *A, const Value *B);
1107 CachedResults.clear();
1112 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1113 // If the values are Selects with the same condition, we can do a more precise
1114 // check: just check for relations between the values on corresponding arms.
1115 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
1116 if (A->getCondition() == SB->getCondition()) {
1117 if (related(A->getTrueValue(), SB->getTrueValue()))
1119 if (related(A->getFalseValue(), SB->getFalseValue()))
1124 // Check both arms of the Select node individually.
1125 if (related(A->getTrueValue(), B))
1127 if (related(A->getFalseValue(), B))
1130 // The arms both checked out.
1134 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1135 // If the values are PHIs in the same block, we can do a more precise as well
1136 // as efficient check: just check for relations between the values on
1137 // corresponding edges.
1138 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1139 if (PNB->getParent() == A->getParent()) {
1140 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1141 if (related(A->getIncomingValue(i),
1142 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1147 // Check each unique source of the PHI node against B.
1148 SmallPtrSet<const Value *, 4> UniqueSrc;
1149 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1150 const Value *PV1 = A->getIncomingValue(i);
1151 if (UniqueSrc.insert(PV1) && related(PV1, B))
1155 // All of the arms checked out.
1159 /// isStoredObjCPointer - Test if the value of P, or any value covered by its
1160 /// provenance, is ever stored within the function (not counting callees).
1161 static bool isStoredObjCPointer(const Value *P) {
1162 SmallPtrSet<const Value *, 8> Visited;
1163 SmallVector<const Value *, 8> Worklist;
1164 Worklist.push_back(P);
1167 P = Worklist.pop_back_val();
1168 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1170 const User *Ur = *UI;
1171 if (isa<StoreInst>(Ur)) {
1172 if (UI.getOperandNo() == 0)
1173 // The pointer is stored.
1175 // The pointed is stored through.
1178 if (isa<CallInst>(Ur))
1179 // The pointer is passed as an argument, ignore this.
1181 if (isa<PtrToIntInst>(P))
1182 // Assume the worst.
1184 if (Visited.insert(Ur))
1185 Worklist.push_back(Ur);
1187 } while (!Worklist.empty());
1189 // Everything checked out.
1193 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1194 // Skip past provenance pass-throughs.
1195 A = GetUnderlyingObjCPtr(A);
1196 B = GetUnderlyingObjCPtr(B);
1202 // Ask regular AliasAnalysis, for a first approximation.
1203 switch (AA->alias(A, B)) {
1204 case AliasAnalysis::NoAlias:
1206 case AliasAnalysis::MustAlias:
1207 case AliasAnalysis::PartialAlias:
1209 case AliasAnalysis::MayAlias:
1213 bool AIsIdentified = IsObjCIdentifiedObject(A);
1214 bool BIsIdentified = IsObjCIdentifiedObject(B);
1216 // An ObjC-Identified object can't alias a load if it is never locally stored.
1217 if (AIsIdentified) {
1218 if (BIsIdentified) {
1219 // If both pointers have provenance, they can be directly compared.
1223 if (isa<LoadInst>(B))
1224 return isStoredObjCPointer(A);
1227 if (BIsIdentified && isa<LoadInst>(A))
1228 return isStoredObjCPointer(B);
1231 // Special handling for PHI and Select.
1232 if (const PHINode *PN = dyn_cast<PHINode>(A))
1233 return relatedPHI(PN, B);
1234 if (const PHINode *PN = dyn_cast<PHINode>(B))
1235 return relatedPHI(PN, A);
1236 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1237 return relatedSelect(S, B);
1238 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1239 return relatedSelect(S, A);
1245 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1246 // Begin by inserting a conservative value into the map. If the insertion
1247 // fails, we have the answer already. If it succeeds, leave it there until we
1248 // compute the real answer to guard against recursive queries.
1249 if (A > B) std::swap(A, B);
1250 std::pair<CachedResultsTy::iterator, bool> Pair =
1251 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1253 return Pair.first->second;
1255 bool Result = relatedCheck(A, B);
1256 CachedResults[ValuePairTy(A, B)] = Result;
1261 // Sequence - A sequence of states that a pointer may go through in which an
1262 // objc_retain and objc_release are actually needed.
1265 S_Retain, ///< objc_retain(x)
1266 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1267 S_Use, ///< any use of x
1268 S_Stop, ///< like S_Release, but code motion is stopped
1269 S_Release, ///< objc_release(x)
1270 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1274 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1278 if (A == S_None || B == S_None)
1281 if (A > B) std::swap(A, B);
1283 // Choose the side which is further along in the sequence.
1284 if ((A == S_Retain || A == S_CanRelease) &&
1285 (B == S_CanRelease || B == S_Use))
1288 // Choose the side which is further along in the sequence.
1289 if ((A == S_Use || A == S_CanRelease) &&
1290 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
1292 // If both sides are releases, choose the more conservative one.
1293 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1295 if (A == S_Release && B == S_MovableRelease)
1303 /// RRInfo - Unidirectional information about either a
1304 /// retain-decrement-use-release sequence or release-use-decrement-retain
1305 /// reverese sequence.
1307 /// KnownSafe - After an objc_retain, the reference count of the referenced
1308 /// object is known to be positive. Similarly, before an objc_release, the
1309 /// reference count of the referenced object is known to be positive. If
1310 /// there are retain-release pairs in code regions where the retain count
1311 /// is known to be positive, they can be eliminated, regardless of any side
1312 /// effects between them.
1314 /// Also, a retain+release pair nested within another retain+release
1315 /// pair all on the known same pointer value can be eliminated, regardless
1316 /// of any intervening side effects.
1318 /// KnownSafe is true when either of these conditions is satisfied.
1321 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1322 /// opposed to objc_retain calls).
1325 /// IsTailCallRelease - True of the objc_release calls are all marked
1326 /// with the "tail" keyword.
1327 bool IsTailCallRelease;
1329 /// Partial - True of we've seen an opportunity for partial RR elimination,
1330 /// such as pushing calls into a CFG triangle or into one side of a
1332 /// TODO: Consider moving this to PtrState.
1335 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1336 /// a clang.imprecise_release tag, this is the metadata tag.
1337 MDNode *ReleaseMetadata;
1339 /// Calls - For a top-down sequence, the set of objc_retains or
1340 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1341 SmallPtrSet<Instruction *, 2> Calls;
1343 /// ReverseInsertPts - The set of optimal insert positions for
1344 /// moving calls in the opposite sequence.
1345 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1348 KnownSafe(false), IsRetainBlock(false),
1349 IsTailCallRelease(false), Partial(false),
1350 ReleaseMetadata(0) {}
1356 void RRInfo::clear() {
1358 IsRetainBlock = false;
1359 IsTailCallRelease = false;
1361 ReleaseMetadata = 0;
1363 ReverseInsertPts.clear();
1367 /// PtrState - This class summarizes several per-pointer runtime properties
1368 /// which are propogated through the flow graph.
1370 /// RefCount - The known minimum number of reference count increments.
1373 /// NestCount - The known minimum level of retain+release nesting.
1376 /// Seq - The current position in the sequence.
1380 /// RRI - Unidirectional information about the current sequence.
1381 /// TODO: Encapsulate this better.
1384 PtrState() : RefCount(0), NestCount(0), Seq(S_None) {}
1386 void SetAtLeastOneRefCount() {
1387 if (RefCount == 0) RefCount = 1;
1390 void IncrementRefCount() {
1391 if (RefCount != UINT_MAX) ++RefCount;
1394 void DecrementRefCount() {
1395 if (RefCount != 0) --RefCount;
1398 bool IsKnownIncremented() const {
1399 return RefCount > 0;
1402 void IncrementNestCount() {
1403 if (NestCount != UINT_MAX) ++NestCount;
1406 void DecrementNestCount() {
1407 if (NestCount != 0) --NestCount;
1410 bool IsKnownNested() const {
1411 return NestCount > 0;
1414 void SetSeq(Sequence NewSeq) {
1418 Sequence GetSeq() const {
1422 void ClearSequenceProgress() {
1427 void Merge(const PtrState &Other, bool TopDown);
1432 PtrState::Merge(const PtrState &Other, bool TopDown) {
1433 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1434 RefCount = std::min(RefCount, Other.RefCount);
1435 NestCount = std::min(NestCount, Other.NestCount);
1437 // We can't merge a plain objc_retain with an objc_retainBlock.
1438 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1441 // If we're not in a sequence (anymore), drop all associated state.
1442 if (Seq == S_None) {
1444 } else if (RRI.Partial || Other.RRI.Partial) {
1445 // If we're doing a merge on a path that's previously seen a partial
1446 // merge, conservatively drop the sequence, to avoid doing partial
1447 // RR elimination. If the branch predicates for the two merge differ,
1448 // mixing them is unsafe.
1452 // Conservatively merge the ReleaseMetadata information.
1453 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1454 RRI.ReleaseMetadata = 0;
1456 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
1457 RRI.IsTailCallRelease = RRI.IsTailCallRelease && Other.RRI.IsTailCallRelease;
1458 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1460 // Merge the insert point sets. If there are any differences,
1461 // that makes this a partial merge.
1462 RRI.Partial = RRI.ReverseInsertPts.size() !=
1463 Other.RRI.ReverseInsertPts.size();
1464 for (SmallPtrSet<Instruction *, 2>::const_iterator
1465 I = Other.RRI.ReverseInsertPts.begin(),
1466 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1467 RRI.Partial |= RRI.ReverseInsertPts.insert(*I);
1472 /// BBState - Per-BasicBlock state.
1474 /// TopDownPathCount - The number of unique control paths from the entry
1475 /// which can reach this block.
1476 unsigned TopDownPathCount;
1478 /// BottomUpPathCount - The number of unique control paths to exits
1479 /// from this block.
1480 unsigned BottomUpPathCount;
1482 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1483 typedef MapVector<const Value *, PtrState> MapTy;
1485 /// PerPtrTopDown - The top-down traversal uses this to record information
1486 /// known about a pointer at the bottom of each block.
1487 MapTy PerPtrTopDown;
1489 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1490 /// known about a pointer at the top of each block.
1491 MapTy PerPtrBottomUp;
1494 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1496 typedef MapTy::iterator ptr_iterator;
1497 typedef MapTy::const_iterator ptr_const_iterator;
1499 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1500 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1501 ptr_const_iterator top_down_ptr_begin() const {
1502 return PerPtrTopDown.begin();
1504 ptr_const_iterator top_down_ptr_end() const {
1505 return PerPtrTopDown.end();
1508 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1509 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1510 ptr_const_iterator bottom_up_ptr_begin() const {
1511 return PerPtrBottomUp.begin();
1513 ptr_const_iterator bottom_up_ptr_end() const {
1514 return PerPtrBottomUp.end();
1517 /// SetAsEntry - Mark this block as being an entry block, which has one
1518 /// path from the entry by definition.
1519 void SetAsEntry() { TopDownPathCount = 1; }
1521 /// SetAsExit - Mark this block as being an exit block, which has one
1522 /// path to an exit by definition.
1523 void SetAsExit() { BottomUpPathCount = 1; }
1525 PtrState &getPtrTopDownState(const Value *Arg) {
1526 return PerPtrTopDown[Arg];
1529 PtrState &getPtrBottomUpState(const Value *Arg) {
1530 return PerPtrBottomUp[Arg];
1533 void clearBottomUpPointers() {
1534 PerPtrBottomUp.clear();
1537 void clearTopDownPointers() {
1538 PerPtrTopDown.clear();
1541 void InitFromPred(const BBState &Other);
1542 void InitFromSucc(const BBState &Other);
1543 void MergePred(const BBState &Other);
1544 void MergeSucc(const BBState &Other);
1546 /// GetAllPathCount - Return the number of possible unique paths from an
1547 /// entry to an exit which pass through this block. This is only valid
1548 /// after both the top-down and bottom-up traversals are complete.
1549 unsigned GetAllPathCount() const {
1550 return TopDownPathCount * BottomUpPathCount;
1553 /// IsVisitedTopDown - Test whether the block for this BBState has been
1554 /// visited by the top-down portion of the algorithm.
1555 bool isVisitedTopDown() const {
1556 return TopDownPathCount != 0;
1561 void BBState::InitFromPred(const BBState &Other) {
1562 PerPtrTopDown = Other.PerPtrTopDown;
1563 TopDownPathCount = Other.TopDownPathCount;
1566 void BBState::InitFromSucc(const BBState &Other) {
1567 PerPtrBottomUp = Other.PerPtrBottomUp;
1568 BottomUpPathCount = Other.BottomUpPathCount;
1571 /// MergePred - The top-down traversal uses this to merge information about
1572 /// predecessors to form the initial state for a new block.
1573 void BBState::MergePred(const BBState &Other) {
1574 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1575 // loop backedge. Loop backedges are special.
1576 TopDownPathCount += Other.TopDownPathCount;
1578 // For each entry in the other set, if our set has an entry with the same key,
1579 // merge the entries. Otherwise, copy the entry and merge it with an empty
1581 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1582 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1583 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1584 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1588 // For each entry in our set, if the other set doesn't have an entry with the
1589 // same key, force it to merge with an empty entry.
1590 for (ptr_iterator MI = top_down_ptr_begin(),
1591 ME = top_down_ptr_end(); MI != ME; ++MI)
1592 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1593 MI->second.Merge(PtrState(), /*TopDown=*/true);
1596 /// MergeSucc - The bottom-up traversal uses this to merge information about
1597 /// successors to form the initial state for a new block.
1598 void BBState::MergeSucc(const BBState &Other) {
1599 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1600 // loop backedge. Loop backedges are special.
1601 BottomUpPathCount += Other.BottomUpPathCount;
1603 // For each entry in the other set, if our set has an entry with the
1604 // same key, merge the entries. Otherwise, copy the entry and merge
1605 // it with an empty entry.
1606 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1607 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1608 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1609 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1613 // For each entry in our set, if the other set doesn't have an entry
1614 // with the same key, force it to merge with an empty entry.
1615 for (ptr_iterator MI = bottom_up_ptr_begin(),
1616 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1617 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1618 MI->second.Merge(PtrState(), /*TopDown=*/false);
1622 /// ObjCARCOpt - The main ARC optimization pass.
1623 class ObjCARCOpt : public FunctionPass {
1625 ProvenanceAnalysis PA;
1627 /// Run - A flag indicating whether this optimization pass should run.
1630 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1631 /// functions, for use in creating calls to them. These are initialized
1632 /// lazily to avoid cluttering up the Module with unused declarations.
1633 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
1634 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
1636 /// UsedInThisFunciton - Flags which determine whether each of the
1637 /// interesting runtine functions is in fact used in the current function.
1638 unsigned UsedInThisFunction;
1640 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1642 unsigned ImpreciseReleaseMDKind;
1644 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
1646 unsigned CopyOnEscapeMDKind;
1648 Constant *getRetainRVCallee(Module *M);
1649 Constant *getAutoreleaseRVCallee(Module *M);
1650 Constant *getReleaseCallee(Module *M);
1651 Constant *getRetainCallee(Module *M);
1652 Constant *getRetainBlockCallee(Module *M);
1653 Constant *getAutoreleaseCallee(Module *M);
1655 bool IsRetainBlockOptimizable(const Instruction *Inst);
1657 void OptimizeRetainCall(Function &F, Instruction *Retain);
1658 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1659 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1660 void OptimizeIndividualCalls(Function &F);
1662 void CheckForCFGHazards(const BasicBlock *BB,
1663 DenseMap<const BasicBlock *, BBState> &BBStates,
1664 BBState &MyStates) const;
1665 bool VisitBottomUp(BasicBlock *BB,
1666 DenseMap<const BasicBlock *, BBState> &BBStates,
1667 MapVector<Value *, RRInfo> &Retains);
1668 bool VisitTopDown(BasicBlock *BB,
1669 DenseMap<const BasicBlock *, BBState> &BBStates,
1670 DenseMap<Value *, RRInfo> &Releases);
1671 bool Visit(Function &F,
1672 DenseMap<const BasicBlock *, BBState> &BBStates,
1673 MapVector<Value *, RRInfo> &Retains,
1674 DenseMap<Value *, RRInfo> &Releases);
1676 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1677 MapVector<Value *, RRInfo> &Retains,
1678 DenseMap<Value *, RRInfo> &Releases,
1679 SmallVectorImpl<Instruction *> &DeadInsts,
1682 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1683 MapVector<Value *, RRInfo> &Retains,
1684 DenseMap<Value *, RRInfo> &Releases,
1687 void OptimizeWeakCalls(Function &F);
1689 bool OptimizeSequences(Function &F);
1691 void OptimizeReturns(Function &F);
1693 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1694 virtual bool doInitialization(Module &M);
1695 virtual bool runOnFunction(Function &F);
1696 virtual void releaseMemory();
1700 ObjCARCOpt() : FunctionPass(ID) {
1701 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1706 char ObjCARCOpt::ID = 0;
1707 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1708 "objc-arc", "ObjC ARC optimization", false, false)
1709 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1710 INITIALIZE_PASS_END(ObjCARCOpt,
1711 "objc-arc", "ObjC ARC optimization", false, false)
1713 Pass *llvm::createObjCARCOptPass() {
1714 return new ObjCARCOpt();
1717 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1718 AU.addRequired<ObjCARCAliasAnalysis>();
1719 AU.addRequired<AliasAnalysis>();
1720 // ARC optimization doesn't currently split critical edges.
1721 AU.setPreservesCFG();
1724 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1725 // Without the magic metadata tag, we have to assume this might be an
1726 // objc_retainBlock call inserted to convert a block pointer to an id,
1727 // in which case it really is needed.
1728 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1731 // If the pointer "escapes" (not including being used in a call),
1732 // the copy may be needed.
1733 if (DoesObjCBlockEscape(Inst))
1736 // Otherwise, it's not needed.
1740 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1741 if (!RetainRVCallee) {
1742 LLVMContext &C = M->getContext();
1743 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1744 std::vector<Type *> Params;
1745 Params.push_back(I8X);
1747 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1748 AttrListPtr Attributes;
1749 Attributes.addAttr(~0u, Attribute::NoUnwind);
1751 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1754 return RetainRVCallee;
1757 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1758 if (!AutoreleaseRVCallee) {
1759 LLVMContext &C = M->getContext();
1760 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1761 std::vector<Type *> Params;
1762 Params.push_back(I8X);
1764 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1765 AttrListPtr Attributes;
1766 Attributes.addAttr(~0u, Attribute::NoUnwind);
1767 AutoreleaseRVCallee =
1768 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1771 return AutoreleaseRVCallee;
1774 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1775 if (!ReleaseCallee) {
1776 LLVMContext &C = M->getContext();
1777 std::vector<Type *> Params;
1778 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1779 AttrListPtr Attributes;
1780 Attributes.addAttr(~0u, Attribute::NoUnwind);
1782 M->getOrInsertFunction(
1784 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1787 return ReleaseCallee;
1790 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1791 if (!RetainCallee) {
1792 LLVMContext &C = M->getContext();
1793 std::vector<Type *> Params;
1794 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1795 AttrListPtr Attributes;
1796 Attributes.addAttr(~0u, Attribute::NoUnwind);
1798 M->getOrInsertFunction(
1800 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1803 return RetainCallee;
1806 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1807 if (!RetainBlockCallee) {
1808 LLVMContext &C = M->getContext();
1809 std::vector<Type *> Params;
1810 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1811 AttrListPtr Attributes;
1812 // objc_retainBlock is not nounwind because it calls user copy constructors
1813 // which could theoretically throw.
1815 M->getOrInsertFunction(
1817 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1820 return RetainBlockCallee;
1823 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1824 if (!AutoreleaseCallee) {
1825 LLVMContext &C = M->getContext();
1826 std::vector<Type *> Params;
1827 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1828 AttrListPtr Attributes;
1829 Attributes.addAttr(~0u, Attribute::NoUnwind);
1831 M->getOrInsertFunction(
1833 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1836 return AutoreleaseCallee;
1839 /// CanAlterRefCount - Test whether the given instruction can result in a
1840 /// reference count modification (positive or negative) for the pointer's
1843 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1844 ProvenanceAnalysis &PA, InstructionClass Class) {
1846 case IC_Autorelease:
1847 case IC_AutoreleaseRV:
1849 // These operations never directly modify a reference count.
1854 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1855 assert(CS && "Only calls can alter reference counts!");
1857 // See if AliasAnalysis can help us with the call.
1858 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1859 if (AliasAnalysis::onlyReadsMemory(MRB))
1861 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1862 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1864 const Value *Op = *I;
1865 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1871 // Assume the worst.
1875 /// CanUse - Test whether the given instruction can "use" the given pointer's
1876 /// object in a way that requires the reference count to be positive.
1878 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1879 InstructionClass Class) {
1880 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1881 if (Class == IC_Call)
1884 // Consider various instructions which may have pointer arguments which are
1886 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1887 // Comparing a pointer with null, or any other constant, isn't really a use,
1888 // because we don't care what the pointer points to, or about the values
1889 // of any other dynamic reference-counted pointers.
1890 if (!IsPotentialUse(ICI->getOperand(1)))
1892 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1893 // For calls, just check the arguments (and not the callee operand).
1894 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1895 OE = CS.arg_end(); OI != OE; ++OI) {
1896 const Value *Op = *OI;
1897 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1901 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1902 // Special-case stores, because we don't care about the stored value, just
1903 // the store address.
1904 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1905 // If we can't tell what the underlying object was, assume there is a
1907 return IsPotentialUse(Op) && PA.related(Op, Ptr);
1910 // Check each operand for a match.
1911 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1913 const Value *Op = *OI;
1914 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1920 /// CanInterruptRV - Test whether the given instruction can autorelease
1921 /// any pointer or cause an autoreleasepool pop.
1923 CanInterruptRV(InstructionClass Class) {
1925 case IC_AutoreleasepoolPop:
1928 case IC_Autorelease:
1929 case IC_AutoreleaseRV:
1930 case IC_FusedRetainAutorelease:
1931 case IC_FusedRetainAutoreleaseRV:
1939 /// DependenceKind - There are several kinds of dependence-like concepts in
1941 enum DependenceKind {
1942 NeedsPositiveRetainCount,
1943 CanChangeRetainCount,
1944 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1945 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1946 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1950 /// Depends - Test if there can be dependencies on Inst through Arg. This
1951 /// function only tests dependencies relevant for removing pairs of calls.
1953 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1954 ProvenanceAnalysis &PA) {
1955 // If we've reached the definition of Arg, stop.
1960 case NeedsPositiveRetainCount: {
1961 InstructionClass Class = GetInstructionClass(Inst);
1963 case IC_AutoreleasepoolPop:
1964 case IC_AutoreleasepoolPush:
1968 return CanUse(Inst, Arg, PA, Class);
1972 case CanChangeRetainCount: {
1973 InstructionClass Class = GetInstructionClass(Inst);
1975 case IC_AutoreleasepoolPop:
1976 // Conservatively assume this can decrement any count.
1978 case IC_AutoreleasepoolPush:
1982 return CanAlterRefCount(Inst, Arg, PA, Class);
1986 case RetainAutoreleaseDep:
1987 switch (GetBasicInstructionClass(Inst)) {
1988 case IC_AutoreleasepoolPop:
1989 // Don't merge an objc_autorelease with an objc_retain inside a different
1990 // autoreleasepool scope.
1994 // Check for a retain of the same pointer for merging.
1995 return GetObjCArg(Inst) == Arg;
1997 // Nothing else matters for objc_retainAutorelease formation.
2002 case RetainAutoreleaseRVDep: {
2003 InstructionClass Class = GetBasicInstructionClass(Inst);
2007 // Check for a retain of the same pointer for merging.
2008 return GetObjCArg(Inst) == Arg;
2010 // Anything that can autorelease interrupts
2011 // retainAutoreleaseReturnValue formation.
2012 return CanInterruptRV(Class);
2018 return CanInterruptRV(GetBasicInstructionClass(Inst));
2021 llvm_unreachable("Invalid dependence flavor");
2024 /// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2025 /// find local and non-local dependencies on Arg.
2026 /// TODO: Cache results?
2028 FindDependencies(DependenceKind Flavor,
2030 BasicBlock *StartBB, Instruction *StartInst,
2031 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2032 SmallPtrSet<const BasicBlock *, 4> &Visited,
2033 ProvenanceAnalysis &PA) {
2034 BasicBlock::iterator StartPos = StartInst;
2036 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2037 Worklist.push_back(std::make_pair(StartBB, StartPos));
2039 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2040 Worklist.pop_back_val();
2041 BasicBlock *LocalStartBB = Pair.first;
2042 BasicBlock::iterator LocalStartPos = Pair.second;
2043 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2045 if (LocalStartPos == StartBBBegin) {
2046 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2048 // If we've reached the function entry, produce a null dependence.
2049 DependingInstructions.insert(0);
2051 // Add the predecessors to the worklist.
2053 BasicBlock *PredBB = *PI;
2054 if (Visited.insert(PredBB))
2055 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2056 } while (++PI != PE);
2060 Instruction *Inst = --LocalStartPos;
2061 if (Depends(Flavor, Inst, Arg, PA)) {
2062 DependingInstructions.insert(Inst);
2066 } while (!Worklist.empty());
2068 // Determine whether the original StartBB post-dominates all of the blocks we
2069 // visited. If not, insert a sentinal indicating that most optimizations are
2071 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2072 E = Visited.end(); I != E; ++I) {
2073 const BasicBlock *BB = *I;
2076 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2077 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2078 const BasicBlock *Succ = *SI;
2079 if (Succ != StartBB && !Visited.count(Succ)) {
2080 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2087 static bool isNullOrUndef(const Value *V) {
2088 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2091 static bool isNoopInstruction(const Instruction *I) {
2092 return isa<BitCastInst>(I) ||
2093 (isa<GetElementPtrInst>(I) &&
2094 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2097 /// OptimizeRetainCall - Turn objc_retain into
2098 /// objc_retainAutoreleasedReturnValue if the operand is a return value.
2100 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
2101 CallSite CS(GetObjCArg(Retain));
2102 Instruction *Call = CS.getInstruction();
2104 if (Call->getParent() != Retain->getParent()) return;
2106 // Check that the call is next to the retain.
2107 BasicBlock::iterator I = Call;
2109 while (isNoopInstruction(I)) ++I;
2113 // Turn it to an objc_retainAutoreleasedReturnValue..
2116 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2119 /// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
2120 /// objc_retain if the operand is not a return value. Or, if it can be
2121 /// paired with an objc_autoreleaseReturnValue, delete the pair and
2124 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
2125 // Check for the argument being from an immediately preceding call.
2126 Value *Arg = GetObjCArg(RetainRV);
2128 if (Instruction *Call = CS.getInstruction())
2129 if (Call->getParent() == RetainRV->getParent()) {
2130 BasicBlock::iterator I = Call;
2132 while (isNoopInstruction(I)) ++I;
2133 if (&*I == RetainRV)
2137 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2138 // pointer. In this case, we can delete the pair.
2139 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2141 do --I; while (I != Begin && isNoopInstruction(I));
2142 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2143 GetObjCArg(I) == Arg) {
2146 EraseInstruction(I);
2147 EraseInstruction(RetainRV);
2152 // Turn it to a plain objc_retain.
2155 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2159 /// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2160 /// objc_autorelease if the result is not used as a return value.
2162 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
2163 // Check for a return of the pointer value.
2164 const Value *Ptr = GetObjCArg(AutoreleaseRV);
2165 SmallVector<const Value *, 2> Users;
2166 Users.push_back(Ptr);
2168 Ptr = Users.pop_back_val();
2169 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2171 const User *I = *UI;
2172 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2174 if (isa<BitCastInst>(I))
2177 } while (!Users.empty());
2181 cast<CallInst>(AutoreleaseRV)->
2182 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2185 /// OptimizeIndividualCalls - Visit each call, one at a time, and make
2186 /// simplifications without doing any additional analysis.
2187 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2188 // Reset all the flags in preparation for recomputing them.
2189 UsedInThisFunction = 0;
2191 // Visit all objc_* calls in F.
2192 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2193 Instruction *Inst = &*I++;
2194 InstructionClass Class = GetBasicInstructionClass(Inst);
2199 // Delete no-op casts. These function calls have special semantics, but
2200 // the semantics are entirely implemented via lowering in the front-end,
2201 // so by the time they reach the optimizer, they are just no-op calls
2202 // which return their argument.
2204 // There are gray areas here, as the ability to cast reference-counted
2205 // pointers to raw void* and back allows code to break ARC assumptions,
2206 // however these are currently considered to be unimportant.
2210 EraseInstruction(Inst);
2213 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2216 case IC_LoadWeakRetained:
2218 case IC_DestroyWeak: {
2219 CallInst *CI = cast<CallInst>(Inst);
2220 if (isNullOrUndef(CI->getArgOperand(0))) {
2221 Type *Ty = CI->getArgOperand(0)->getType();
2222 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2223 Constant::getNullValue(Ty),
2225 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2226 CI->eraseFromParent();
2233 CallInst *CI = cast<CallInst>(Inst);
2234 if (isNullOrUndef(CI->getArgOperand(0)) ||
2235 isNullOrUndef(CI->getArgOperand(1))) {
2236 Type *Ty = CI->getArgOperand(0)->getType();
2237 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2238 Constant::getNullValue(Ty),
2240 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2241 CI->eraseFromParent();
2247 OptimizeRetainCall(F, Inst);
2250 if (OptimizeRetainRVCall(F, Inst))
2253 case IC_AutoreleaseRV:
2254 OptimizeAutoreleaseRVCall(F, Inst);
2258 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2259 if (IsAutorelease(Class) && Inst->use_empty()) {
2260 CallInst *Call = cast<CallInst>(Inst);
2261 const Value *Arg = Call->getArgOperand(0);
2262 Arg = FindSingleUseIdentifiedObject(Arg);
2267 // Create the declaration lazily.
2268 LLVMContext &C = Inst->getContext();
2270 CallInst::Create(getReleaseCallee(F.getParent()),
2271 Call->getArgOperand(0), "", Call);
2272 NewCall->setMetadata(ImpreciseReleaseMDKind,
2273 MDNode::get(C, ArrayRef<Value *>()));
2274 EraseInstruction(Call);
2280 // For functions which can never be passed stack arguments, add
2282 if (IsAlwaysTail(Class)) {
2284 cast<CallInst>(Inst)->setTailCall();
2287 // Set nounwind as needed.
2288 if (IsNoThrow(Class)) {
2290 cast<CallInst>(Inst)->setDoesNotThrow();
2293 if (!IsNoopOnNull(Class)) {
2294 UsedInThisFunction |= 1 << Class;
2298 const Value *Arg = GetObjCArg(Inst);
2300 // ARC calls with null are no-ops. Delete them.
2301 if (isNullOrUndef(Arg)) {
2304 EraseInstruction(Inst);
2308 // Keep track of which of retain, release, autorelease, and retain_block
2309 // are actually present in this function.
2310 UsedInThisFunction |= 1 << Class;
2312 // If Arg is a PHI, and one or more incoming values to the
2313 // PHI are null, and the call is control-equivalent to the PHI, and there
2314 // are no relevant side effects between the PHI and the call, the call
2315 // could be pushed up to just those paths with non-null incoming values.
2316 // For now, don't bother splitting critical edges for this.
2317 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2318 Worklist.push_back(std::make_pair(Inst, Arg));
2320 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2324 const PHINode *PN = dyn_cast<PHINode>(Arg);
2327 // Determine if the PHI has any null operands, or any incoming
2329 bool HasNull = false;
2330 bool HasCriticalEdges = false;
2331 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2333 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2334 if (isNullOrUndef(Incoming))
2336 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2337 .getNumSuccessors() != 1) {
2338 HasCriticalEdges = true;
2342 // If we have null operands and no critical edges, optimize.
2343 if (!HasCriticalEdges && HasNull) {
2344 SmallPtrSet<Instruction *, 4> DependingInstructions;
2345 SmallPtrSet<const BasicBlock *, 4> Visited;
2347 // Check that there is nothing that cares about the reference
2348 // count between the call and the phi.
2349 FindDependencies(NeedsPositiveRetainCount, Arg,
2350 Inst->getParent(), Inst,
2351 DependingInstructions, Visited, PA);
2352 if (DependingInstructions.size() == 1 &&
2353 *DependingInstructions.begin() == PN) {
2356 // Clone the call into each predecessor that has a non-null value.
2357 CallInst *CInst = cast<CallInst>(Inst);
2358 Type *ParamTy = CInst->getArgOperand(0)->getType();
2359 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2361 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2362 if (!isNullOrUndef(Incoming)) {
2363 CallInst *Clone = cast<CallInst>(CInst->clone());
2364 Value *Op = PN->getIncomingValue(i);
2365 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2366 if (Op->getType() != ParamTy)
2367 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2368 Clone->setArgOperand(0, Op);
2369 Clone->insertBefore(InsertPos);
2370 Worklist.push_back(std::make_pair(Clone, Incoming));
2373 // Erase the original call.
2374 EraseInstruction(CInst);
2378 } while (!Worklist.empty());
2382 /// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2383 /// control flow, or other CFG structures where moving code across the edge
2384 /// would result in it being executed more.
2386 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2387 DenseMap<const BasicBlock *, BBState> &BBStates,
2388 BBState &MyStates) const {
2389 // If any top-down local-use or possible-dec has a succ which is earlier in
2390 // the sequence, forget it.
2391 for (BBState::ptr_const_iterator I = MyStates.top_down_ptr_begin(),
2392 E = MyStates.top_down_ptr_end(); I != E; ++I)
2393 switch (I->second.GetSeq()) {
2396 const Value *Arg = I->first;
2397 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2398 bool SomeSuccHasSame = false;
2399 bool AllSuccsHaveSame = true;
2400 PtrState &S = MyStates.getPtrTopDownState(Arg);
2401 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2402 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2403 switch (SuccS.GetSeq()) {
2405 case S_CanRelease: {
2406 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2407 S.ClearSequenceProgress();
2411 SomeSuccHasSame = true;
2415 case S_MovableRelease:
2416 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2417 AllSuccsHaveSame = false;
2420 llvm_unreachable("bottom-up pointer in retain state!");
2423 // If the state at the other end of any of the successor edges
2424 // matches the current state, require all edges to match. This
2425 // guards against loops in the middle of a sequence.
2426 if (SomeSuccHasSame && !AllSuccsHaveSame)
2427 S.ClearSequenceProgress();
2430 case S_CanRelease: {
2431 const Value *Arg = I->first;
2432 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2433 bool SomeSuccHasSame = false;
2434 bool AllSuccsHaveSame = true;
2435 PtrState &S = MyStates.getPtrTopDownState(Arg);
2436 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2437 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2438 switch (SuccS.GetSeq()) {
2440 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2441 S.ClearSequenceProgress();
2445 SomeSuccHasSame = true;
2449 case S_MovableRelease:
2451 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2452 AllSuccsHaveSame = false;
2455 llvm_unreachable("bottom-up pointer in retain state!");
2458 // If the state at the other end of any of the successor edges
2459 // matches the current state, require all edges to match. This
2460 // guards against loops in the middle of a sequence.
2461 if (SomeSuccHasSame && !AllSuccsHaveSame)
2462 S.ClearSequenceProgress();
2469 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2470 DenseMap<const BasicBlock *, BBState> &BBStates,
2471 MapVector<Value *, RRInfo> &Retains) {
2472 bool NestingDetected = false;
2473 BBState &MyStates = BBStates[BB];
2475 // Merge the states from each successor to compute the initial state
2476 // for the current block.
2477 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2478 succ_const_iterator SI(TI), SE(TI, false);
2480 MyStates.SetAsExit();
2483 const BasicBlock *Succ = *SI++;
2486 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2487 // If we haven't seen this node yet, then we've found a CFG cycle.
2488 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2489 if (I == BBStates.end())
2491 MyStates.InitFromSucc(I->second);
2495 I = BBStates.find(Succ);
2496 if (I != BBStates.end())
2497 MyStates.MergeSucc(I->second);
2503 // Visit all the instructions, bottom-up.
2504 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2505 Instruction *Inst = llvm::prior(I);
2506 InstructionClass Class = GetInstructionClass(Inst);
2507 const Value *Arg = 0;
2511 Arg = GetObjCArg(Inst);
2513 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2515 // If we see two releases in a row on the same pointer. If so, make
2516 // a note, and we'll cicle back to revisit it after we've
2517 // hopefully eliminated the second release, which may allow us to
2518 // eliminate the first release too.
2519 // Theoretically we could implement removal of nested retain+release
2520 // pairs by making PtrState hold a stack of states, but this is
2521 // simple and avoids adding overhead for the non-nested case.
2522 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2523 NestingDetected = true;
2527 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2528 S.SetSeq(ReleaseMetadata ? S_MovableRelease : S_Release);
2529 S.RRI.ReleaseMetadata = ReleaseMetadata;
2530 S.RRI.KnownSafe = S.IsKnownNested() || S.IsKnownIncremented();
2531 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2532 S.RRI.Calls.insert(Inst);
2534 S.IncrementRefCount();
2535 S.IncrementNestCount();
2538 case IC_RetainBlock:
2539 // An objc_retainBlock call with just a use may need to be kept,
2540 // because it may be copying a block from the stack to the heap.
2541 if (!IsRetainBlockOptimizable(Inst))
2546 Arg = GetObjCArg(Inst);
2548 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2549 S.DecrementRefCount();
2550 S.SetAtLeastOneRefCount();
2551 S.DecrementNestCount();
2553 switch (S.GetSeq()) {
2556 case S_MovableRelease:
2558 S.RRI.ReverseInsertPts.clear();
2561 // Don't do retain+release tracking for IC_RetainRV, because it's
2562 // better to let it remain as the first instruction after a call.
2563 if (Class != IC_RetainRV) {
2564 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2565 Retains[Inst] = S.RRI;
2567 S.ClearSequenceProgress();
2572 llvm_unreachable("bottom-up pointer in retain state!");
2576 case IC_AutoreleasepoolPop:
2577 // Conservatively, clear MyStates for all known pointers.
2578 MyStates.clearBottomUpPointers();
2580 case IC_AutoreleasepoolPush:
2582 // These are irrelevant.
2588 // Consider any other possible effects of this instruction on each
2589 // pointer being tracked.
2590 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2591 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2592 const Value *Ptr = MI->first;
2594 continue; // Handled above.
2595 PtrState &S = MI->second;
2596 Sequence Seq = S.GetSeq();
2598 // Check for possible releases.
2599 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2600 S.DecrementRefCount();
2603 S.SetSeq(S_CanRelease);
2607 case S_MovableRelease:
2612 llvm_unreachable("bottom-up pointer in retain state!");
2616 // Check for possible direct uses.
2619 case S_MovableRelease:
2620 if (CanUse(Inst, Ptr, PA, Class)) {
2621 assert(S.RRI.ReverseInsertPts.empty());
2622 S.RRI.ReverseInsertPts.insert(Inst);
2624 } else if (Seq == S_Release &&
2625 (Class == IC_User || Class == IC_CallOrUser)) {
2626 // Non-movable releases depend on any possible objc pointer use.
2628 assert(S.RRI.ReverseInsertPts.empty());
2629 S.RRI.ReverseInsertPts.insert(Inst);
2633 if (CanUse(Inst, Ptr, PA, Class))
2641 llvm_unreachable("bottom-up pointer in retain state!");
2646 return NestingDetected;
2650 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2651 DenseMap<const BasicBlock *, BBState> &BBStates,
2652 DenseMap<Value *, RRInfo> &Releases) {
2653 bool NestingDetected = false;
2654 BBState &MyStates = BBStates[BB];
2656 // Merge the states from each predecessor to compute the initial state
2657 // for the current block.
2658 const_pred_iterator PI(BB), PE(BB, false);
2660 MyStates.SetAsEntry();
2663 const BasicBlock *Pred = *PI++;
2666 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2667 // If we haven't seen this node yet, then we've found a CFG cycle.
2668 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2669 if (I == BBStates.end() || !I->second.isVisitedTopDown())
2671 MyStates.InitFromPred(I->second);
2675 I = BBStates.find(Pred);
2676 if (I != BBStates.end() && I->second.isVisitedTopDown())
2677 MyStates.MergePred(I->second);
2683 // Visit all the instructions, top-down.
2684 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2685 Instruction *Inst = I;
2686 InstructionClass Class = GetInstructionClass(Inst);
2687 const Value *Arg = 0;
2690 case IC_RetainBlock:
2691 // An objc_retainBlock call with just a use may need to be kept,
2692 // because it may be copying a block from the stack to the heap.
2693 if (!IsRetainBlockOptimizable(Inst))
2698 Arg = GetObjCArg(Inst);
2700 PtrState &S = MyStates.getPtrTopDownState(Arg);
2702 // Don't do retain+release tracking for IC_RetainRV, because it's
2703 // better to let it remain as the first instruction after a call.
2704 if (Class != IC_RetainRV) {
2705 // If we see two retains in a row on the same pointer. If so, make
2706 // a note, and we'll cicle back to revisit it after we've
2707 // hopefully eliminated the second retain, which may allow us to
2708 // eliminate the first retain too.
2709 // Theoretically we could implement removal of nested retain+release
2710 // pairs by making PtrState hold a stack of states, but this is
2711 // simple and avoids adding overhead for the non-nested case.
2712 if (S.GetSeq() == S_Retain)
2713 NestingDetected = true;
2717 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2718 // Don't check S.IsKnownIncremented() here because it's not
2720 S.RRI.KnownSafe = S.IsKnownNested();
2721 S.RRI.Calls.insert(Inst);
2724 S.SetAtLeastOneRefCount();
2725 S.IncrementRefCount();
2726 S.IncrementNestCount();
2730 Arg = GetObjCArg(Inst);
2732 PtrState &S = MyStates.getPtrTopDownState(Arg);
2733 S.DecrementRefCount();
2734 S.DecrementNestCount();
2736 switch (S.GetSeq()) {
2739 S.RRI.ReverseInsertPts.clear();
2742 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2743 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2744 Releases[Inst] = S.RRI;
2745 S.ClearSequenceProgress();
2751 case S_MovableRelease:
2752 llvm_unreachable("top-down pointer in release state!");
2756 case IC_AutoreleasepoolPop:
2757 // Conservatively, clear MyStates for all known pointers.
2758 MyStates.clearTopDownPointers();
2760 case IC_AutoreleasepoolPush:
2762 // These are irrelevant.
2768 // Consider any other possible effects of this instruction on each
2769 // pointer being tracked.
2770 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2771 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2772 const Value *Ptr = MI->first;
2774 continue; // Handled above.
2775 PtrState &S = MI->second;
2776 Sequence Seq = S.GetSeq();
2778 // Check for possible releases.
2779 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2780 S.DecrementRefCount();
2783 S.SetSeq(S_CanRelease);
2784 assert(S.RRI.ReverseInsertPts.empty());
2785 S.RRI.ReverseInsertPts.insert(Inst);
2787 // One call can't cause a transition from S_Retain to S_CanRelease
2788 // and S_CanRelease to S_Use. If we've made the first transition,
2797 case S_MovableRelease:
2798 llvm_unreachable("top-down pointer in release state!");
2802 // Check for possible direct uses.
2805 if (CanUse(Inst, Ptr, PA, Class))
2814 case S_MovableRelease:
2815 llvm_unreachable("top-down pointer in release state!");
2820 CheckForCFGHazards(BB, BBStates, MyStates);
2821 return NestingDetected;
2825 ComputePostOrders(Function &F,
2826 SmallVectorImpl<BasicBlock *> &PostOrder,
2827 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder) {
2828 /// Backedges - Backedges detected in the DFS. These edges will be
2829 /// ignored in the reverse-CFG DFS, so that loops with multiple exits will be
2830 /// traversed in the desired order.
2831 DenseSet<std::pair<BasicBlock *, BasicBlock *> > Backedges;
2833 /// Visited - The visited set, for doing DFS walks.
2834 SmallPtrSet<BasicBlock *, 16> Visited;
2836 // Do DFS, computing the PostOrder.
2837 SmallPtrSet<BasicBlock *, 16> OnStack;
2838 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2839 BasicBlock *EntryBB = &F.getEntryBlock();
2840 SuccStack.push_back(std::make_pair(EntryBB, succ_begin(EntryBB)));
2841 Visited.insert(EntryBB);
2842 OnStack.insert(EntryBB);
2845 succ_iterator End = succ_end(SuccStack.back().first);
2846 while (SuccStack.back().second != End) {
2847 BasicBlock *BB = *SuccStack.back().second++;
2848 if (Visited.insert(BB)) {
2849 SuccStack.push_back(std::make_pair(BB, succ_begin(BB)));
2853 if (OnStack.count(BB))
2854 Backedges.insert(std::make_pair(SuccStack.back().first, BB));
2856 OnStack.erase(SuccStack.back().first);
2857 PostOrder.push_back(SuccStack.pop_back_val().first);
2858 } while (!SuccStack.empty());
2862 // Compute the exits, which are the starting points for reverse-CFG DFS.
2863 SmallVector<BasicBlock *, 4> Exits;
2864 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2866 if (BB->getTerminator()->getNumSuccessors() == 0)
2867 Exits.push_back(BB);
2870 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2871 SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> PredStack;
2872 for (SmallVectorImpl<BasicBlock *>::iterator I = Exits.begin(), E = Exits.end();
2874 BasicBlock *ExitBB = *I;
2875 PredStack.push_back(std::make_pair(ExitBB, pred_begin(ExitBB)));
2876 Visited.insert(ExitBB);
2877 while (!PredStack.empty()) {
2878 reverse_dfs_next_succ:
2879 pred_iterator End = pred_end(PredStack.back().first);
2880 while (PredStack.back().second != End) {
2881 BasicBlock *BB = *PredStack.back().second++;
2882 // Skip backedges detected in the forward-CFG DFS.
2883 if (Backedges.count(std::make_pair(BB, PredStack.back().first)))
2885 if (Visited.insert(BB)) {
2886 PredStack.push_back(std::make_pair(BB, pred_begin(BB)));
2887 goto reverse_dfs_next_succ;
2890 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2895 // Visit - Visit the function both top-down and bottom-up.
2897 ObjCARCOpt::Visit(Function &F,
2898 DenseMap<const BasicBlock *, BBState> &BBStates,
2899 MapVector<Value *, RRInfo> &Retains,
2900 DenseMap<Value *, RRInfo> &Releases) {
2902 // Use reverse-postorder traversals, because we magically know that loops
2903 // will be well behaved, i.e. they won't repeatedly call retain on a single
2904 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2905 // class here because we want the reverse-CFG postorder to consider each
2906 // function exit point, and we want to ignore selected cycle edges.
2907 SmallVector<BasicBlock *, 16> PostOrder;
2908 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2909 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder);
2911 // Use reverse-postorder on the reverse CFG for bottom-up.
2912 bool BottomUpNestingDetected = false;
2913 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2914 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2916 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
2918 // Use reverse-postorder for top-down.
2919 bool TopDownNestingDetected = false;
2920 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2921 PostOrder.rbegin(), E = PostOrder.rend();
2923 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
2925 return TopDownNestingDetected && BottomUpNestingDetected;
2928 /// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
2929 void ObjCARCOpt::MoveCalls(Value *Arg,
2930 RRInfo &RetainsToMove,
2931 RRInfo &ReleasesToMove,
2932 MapVector<Value *, RRInfo> &Retains,
2933 DenseMap<Value *, RRInfo> &Releases,
2934 SmallVectorImpl<Instruction *> &DeadInsts,
2936 Type *ArgTy = Arg->getType();
2937 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2939 // Insert the new retain and release calls.
2940 for (SmallPtrSet<Instruction *, 2>::const_iterator
2941 PI = ReleasesToMove.ReverseInsertPts.begin(),
2942 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2943 Instruction *InsertPt = *PI;
2944 Value *MyArg = ArgTy == ParamTy ? Arg :
2945 new BitCastInst(Arg, ParamTy, "", InsertPt);
2947 CallInst::Create(RetainsToMove.IsRetainBlock ?
2948 getRetainBlockCallee(M) : getRetainCallee(M),
2949 MyArg, "", InsertPt);
2950 Call->setDoesNotThrow();
2951 if (RetainsToMove.IsRetainBlock)
2952 Call->setMetadata(CopyOnEscapeMDKind,
2953 MDNode::get(M->getContext(), ArrayRef<Value *>()));
2955 Call->setTailCall();
2957 for (SmallPtrSet<Instruction *, 2>::const_iterator
2958 PI = RetainsToMove.ReverseInsertPts.begin(),
2959 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2960 Instruction *LastUse = *PI;
2961 Instruction *InsertPts[] = { 0, 0, 0 };
2962 if (InvokeInst *II = dyn_cast<InvokeInst>(LastUse)) {
2963 // We can't insert code immediately after an invoke instruction, so
2964 // insert code at the beginning of both successor blocks instead.
2965 // The invoke's return value isn't available in the unwind block,
2966 // but our releases will never depend on it, because they must be
2967 // paired with retains from before the invoke.
2968 InsertPts[0] = II->getNormalDest()->getFirstInsertionPt();
2969 InsertPts[1] = II->getUnwindDest()->getFirstInsertionPt();
2971 // Insert code immediately after the last use.
2972 InsertPts[0] = llvm::next(BasicBlock::iterator(LastUse));
2975 for (Instruction **I = InsertPts; *I; ++I) {
2976 Instruction *InsertPt = *I;
2977 Value *MyArg = ArgTy == ParamTy ? Arg :
2978 new BitCastInst(Arg, ParamTy, "", InsertPt);
2979 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2981 // Attach a clang.imprecise_release metadata tag, if appropriate.
2982 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2983 Call->setMetadata(ImpreciseReleaseMDKind, M);
2984 Call->setDoesNotThrow();
2985 if (ReleasesToMove.IsTailCallRelease)
2986 Call->setTailCall();
2990 // Delete the original retain and release calls.
2991 for (SmallPtrSet<Instruction *, 2>::const_iterator
2992 AI = RetainsToMove.Calls.begin(),
2993 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2994 Instruction *OrigRetain = *AI;
2995 Retains.blot(OrigRetain);
2996 DeadInsts.push_back(OrigRetain);
2998 for (SmallPtrSet<Instruction *, 2>::const_iterator
2999 AI = ReleasesToMove.Calls.begin(),
3000 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3001 Instruction *OrigRelease = *AI;
3002 Releases.erase(OrigRelease);
3003 DeadInsts.push_back(OrigRelease);
3008 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3010 MapVector<Value *, RRInfo> &Retains,
3011 DenseMap<Value *, RRInfo> &Releases,
3013 bool AnyPairsCompletelyEliminated = false;
3014 RRInfo RetainsToMove;
3015 RRInfo ReleasesToMove;
3016 SmallVector<Instruction *, 4> NewRetains;
3017 SmallVector<Instruction *, 4> NewReleases;
3018 SmallVector<Instruction *, 8> DeadInsts;
3020 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
3021 E = Retains.end(); I != E; ++I) {
3022 Value *V = I->first;
3023 if (!V) continue; // blotted
3025 Instruction *Retain = cast<Instruction>(V);
3026 Value *Arg = GetObjCArg(Retain);
3028 // If the object being released is in static or stack storage, we know it's
3029 // not being managed by ObjC reference counting, so we can delete pairs
3030 // regardless of what possible decrements or uses lie between them.
3031 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
3033 // A constant pointer can't be pointing to an object on the heap. It may
3034 // be reference-counted, but it won't be deleted.
3035 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3036 if (const GlobalVariable *GV =
3037 dyn_cast<GlobalVariable>(
3038 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3039 if (GV->isConstant())
3042 // If a pair happens in a region where it is known that the reference count
3043 // is already incremented, we can similarly ignore possible decrements.
3044 bool KnownSafeTD = true, KnownSafeBU = true;
3046 // Connect the dots between the top-down-collected RetainsToMove and
3047 // bottom-up-collected ReleasesToMove to form sets of related calls.
3048 // This is an iterative process so that we connect multiple releases
3049 // to multiple retains if needed.
3050 unsigned OldDelta = 0;
3051 unsigned NewDelta = 0;
3052 unsigned OldCount = 0;
3053 unsigned NewCount = 0;
3054 bool FirstRelease = true;
3055 bool FirstRetain = true;
3056 NewRetains.push_back(Retain);
3058 for (SmallVectorImpl<Instruction *>::const_iterator
3059 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3060 Instruction *NewRetain = *NI;
3061 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3062 assert(It != Retains.end());
3063 const RRInfo &NewRetainRRI = It->second;
3064 KnownSafeTD &= NewRetainRRI.KnownSafe;
3065 for (SmallPtrSet<Instruction *, 2>::const_iterator
3066 LI = NewRetainRRI.Calls.begin(),
3067 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3068 Instruction *NewRetainRelease = *LI;
3069 DenseMap<Value *, RRInfo>::const_iterator Jt =
3070 Releases.find(NewRetainRelease);
3071 if (Jt == Releases.end())
3073 const RRInfo &NewRetainReleaseRRI = Jt->second;
3074 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3075 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3077 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3079 // Merge the ReleaseMetadata and IsTailCallRelease values.
3081 ReleasesToMove.ReleaseMetadata =
3082 NewRetainReleaseRRI.ReleaseMetadata;
3083 ReleasesToMove.IsTailCallRelease =
3084 NewRetainReleaseRRI.IsTailCallRelease;
3085 FirstRelease = false;
3087 if (ReleasesToMove.ReleaseMetadata !=
3088 NewRetainReleaseRRI.ReleaseMetadata)
3089 ReleasesToMove.ReleaseMetadata = 0;
3090 if (ReleasesToMove.IsTailCallRelease !=
3091 NewRetainReleaseRRI.IsTailCallRelease)
3092 ReleasesToMove.IsTailCallRelease = false;
3095 // Collect the optimal insertion points.
3097 for (SmallPtrSet<Instruction *, 2>::const_iterator
3098 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3099 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3101 Instruction *RIP = *RI;
3102 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3103 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3105 NewReleases.push_back(NewRetainRelease);
3110 if (NewReleases.empty()) break;
3112 // Back the other way.
3113 for (SmallVectorImpl<Instruction *>::const_iterator
3114 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3115 Instruction *NewRelease = *NI;
3116 DenseMap<Value *, RRInfo>::const_iterator It =
3117 Releases.find(NewRelease);
3118 assert(It != Releases.end());
3119 const RRInfo &NewReleaseRRI = It->second;
3120 KnownSafeBU &= NewReleaseRRI.KnownSafe;
3121 for (SmallPtrSet<Instruction *, 2>::const_iterator
3122 LI = NewReleaseRRI.Calls.begin(),
3123 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3124 Instruction *NewReleaseRetain = *LI;
3125 MapVector<Value *, RRInfo>::const_iterator Jt =
3126 Retains.find(NewReleaseRetain);
3127 if (Jt == Retains.end())
3129 const RRInfo &NewReleaseRetainRRI = Jt->second;
3130 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3131 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3132 unsigned PathCount =
3133 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3134 OldDelta += PathCount;
3135 OldCount += PathCount;
3137 // Merge the IsRetainBlock values.
3139 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3140 FirstRetain = false;
3141 } else if (ReleasesToMove.IsRetainBlock !=
3142 NewReleaseRetainRRI.IsRetainBlock)
3143 // It's not possible to merge the sequences if one uses
3144 // objc_retain and the other uses objc_retainBlock.
3147 // Collect the optimal insertion points.
3149 for (SmallPtrSet<Instruction *, 2>::const_iterator
3150 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3151 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3153 Instruction *RIP = *RI;
3154 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3155 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3156 NewDelta += PathCount;
3157 NewCount += PathCount;
3160 NewRetains.push_back(NewReleaseRetain);
3164 NewReleases.clear();
3165 if (NewRetains.empty()) break;
3168 // If the pointer is known incremented or nested, we can safely delete the
3169 // pair regardless of what's between them.
3170 if (KnownSafeTD || KnownSafeBU) {
3171 RetainsToMove.ReverseInsertPts.clear();
3172 ReleasesToMove.ReverseInsertPts.clear();
3175 // Determine whether the new insertion points we computed preserve the
3176 // balance of retain and release calls through the program.
3177 // TODO: If the fully aggressive solution isn't valid, try to find a
3178 // less aggressive solution which is.
3183 // Determine whether the original call points are balanced in the retain and
3184 // release calls through the program. If not, conservatively don't touch
3186 // TODO: It's theoretically possible to do code motion in this case, as
3187 // long as the existing imbalances are maintained.
3191 // Ok, everything checks out and we're all set. Let's move some code!
3193 AnyPairsCompletelyEliminated = NewCount == 0;
3194 NumRRs += OldCount - NewCount;
3195 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3196 Retains, Releases, DeadInsts, M);
3199 NewReleases.clear();
3201 RetainsToMove.clear();
3202 ReleasesToMove.clear();
3205 // Now that we're done moving everything, we can delete the newly dead
3206 // instructions, as we no longer need them as insert points.
3207 while (!DeadInsts.empty())
3208 EraseInstruction(DeadInsts.pop_back_val());
3210 return AnyPairsCompletelyEliminated;
3213 /// OptimizeWeakCalls - Weak pointer optimizations.
3214 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3215 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3216 // itself because it uses AliasAnalysis and we need to do provenance
3218 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3219 Instruction *Inst = &*I++;
3220 InstructionClass Class = GetBasicInstructionClass(Inst);
3221 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3224 // Delete objc_loadWeak calls with no users.
3225 if (Class == IC_LoadWeak && Inst->use_empty()) {
3226 Inst->eraseFromParent();
3230 // TODO: For now, just look for an earlier available version of this value
3231 // within the same block. Theoretically, we could do memdep-style non-local
3232 // analysis too, but that would want caching. A better approach would be to
3233 // use the technique that EarlyCSE uses.
3234 inst_iterator Current = llvm::prior(I);
3235 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3236 for (BasicBlock::iterator B = CurrentBB->begin(),
3237 J = Current.getInstructionIterator();
3239 Instruction *EarlierInst = &*llvm::prior(J);
3240 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3241 switch (EarlierClass) {
3243 case IC_LoadWeakRetained: {
3244 // If this is loading from the same pointer, replace this load's value
3246 CallInst *Call = cast<CallInst>(Inst);
3247 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3248 Value *Arg = Call->getArgOperand(0);
3249 Value *EarlierArg = EarlierCall->getArgOperand(0);
3250 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3251 case AliasAnalysis::MustAlias:
3253 // If the load has a builtin retain, insert a plain retain for it.
3254 if (Class == IC_LoadWeakRetained) {
3256 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3260 // Zap the fully redundant load.
3261 Call->replaceAllUsesWith(EarlierCall);
3262 Call->eraseFromParent();
3264 case AliasAnalysis::MayAlias:
3265 case AliasAnalysis::PartialAlias:
3267 case AliasAnalysis::NoAlias:
3274 // If this is storing to the same pointer and has the same size etc.
3275 // replace this load's value with the stored value.
3276 CallInst *Call = cast<CallInst>(Inst);
3277 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3278 Value *Arg = Call->getArgOperand(0);
3279 Value *EarlierArg = EarlierCall->getArgOperand(0);
3280 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3281 case AliasAnalysis::MustAlias:
3283 // If the load has a builtin retain, insert a plain retain for it.
3284 if (Class == IC_LoadWeakRetained) {
3286 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3290 // Zap the fully redundant load.
3291 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3292 Call->eraseFromParent();
3294 case AliasAnalysis::MayAlias:
3295 case AliasAnalysis::PartialAlias:
3297 case AliasAnalysis::NoAlias:
3304 // TOOD: Grab the copied value.
3306 case IC_AutoreleasepoolPush:
3309 // Weak pointers are only modified through the weak entry points
3310 // (and arbitrary calls, which could call the weak entry points).
3313 // Anything else could modify the weak pointer.
3320 // Then, for each destroyWeak with an alloca operand, check to see if
3321 // the alloca and all its users can be zapped.
3322 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3323 Instruction *Inst = &*I++;
3324 InstructionClass Class = GetBasicInstructionClass(Inst);
3325 if (Class != IC_DestroyWeak)
3328 CallInst *Call = cast<CallInst>(Inst);
3329 Value *Arg = Call->getArgOperand(0);
3330 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3331 for (Value::use_iterator UI = Alloca->use_begin(),
3332 UE = Alloca->use_end(); UI != UE; ++UI) {
3333 Instruction *UserInst = cast<Instruction>(*UI);
3334 switch (GetBasicInstructionClass(UserInst)) {
3337 case IC_DestroyWeak:
3344 for (Value::use_iterator UI = Alloca->use_begin(),
3345 UE = Alloca->use_end(); UI != UE; ) {
3346 CallInst *UserInst = cast<CallInst>(*UI++);
3347 if (!UserInst->use_empty())
3348 UserInst->replaceAllUsesWith(UserInst->getArgOperand(0));
3349 UserInst->eraseFromParent();
3351 Alloca->eraseFromParent();
3357 /// OptimizeSequences - Identify program paths which execute sequences of
3358 /// retains and releases which can be eliminated.
3359 bool ObjCARCOpt::OptimizeSequences(Function &F) {
3360 /// Releases, Retains - These are used to store the results of the main flow
3361 /// analysis. These use Value* as the key instead of Instruction* so that the
3362 /// map stays valid when we get around to rewriting code and calls get
3363 /// replaced by arguments.
3364 DenseMap<Value *, RRInfo> Releases;
3365 MapVector<Value *, RRInfo> Retains;
3367 /// BBStates, This is used during the traversal of the function to track the
3368 /// states for each identified object at each block.
3369 DenseMap<const BasicBlock *, BBState> BBStates;
3371 // Analyze the CFG of the function, and all instructions.
3372 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3375 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3379 /// OptimizeReturns - Look for this pattern:
3381 /// %call = call i8* @something(...)
3382 /// %2 = call i8* @objc_retain(i8* %call)
3383 /// %3 = call i8* @objc_autorelease(i8* %2)
3386 /// And delete the retain and autorelease.
3388 /// Otherwise if it's just this:
3390 /// %3 = call i8* @objc_autorelease(i8* %2)
3393 /// convert the autorelease to autoreleaseRV.
3394 void ObjCARCOpt::OptimizeReturns(Function &F) {
3395 if (!F.getReturnType()->isPointerTy())
3398 SmallPtrSet<Instruction *, 4> DependingInstructions;
3399 SmallPtrSet<const BasicBlock *, 4> Visited;
3400 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3401 BasicBlock *BB = FI;
3402 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3405 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3406 FindDependencies(NeedsPositiveRetainCount, Arg,
3407 BB, Ret, DependingInstructions, Visited, PA);
3408 if (DependingInstructions.size() != 1)
3412 CallInst *Autorelease =
3413 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3416 InstructionClass AutoreleaseClass =
3417 GetBasicInstructionClass(Autorelease);
3418 if (!IsAutorelease(AutoreleaseClass))
3420 if (GetObjCArg(Autorelease) != Arg)
3423 DependingInstructions.clear();
3426 // Check that there is nothing that can affect the reference
3427 // count between the autorelease and the retain.
3428 FindDependencies(CanChangeRetainCount, Arg,
3429 BB, Autorelease, DependingInstructions, Visited, PA);
3430 if (DependingInstructions.size() != 1)
3435 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3437 // Check that we found a retain with the same argument.
3439 !IsRetain(GetBasicInstructionClass(Retain)) ||
3440 GetObjCArg(Retain) != Arg)
3443 DependingInstructions.clear();
3446 // Convert the autorelease to an autoreleaseRV, since it's
3447 // returning the value.
3448 if (AutoreleaseClass == IC_Autorelease) {
3449 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3450 AutoreleaseClass = IC_AutoreleaseRV;
3453 // Check that there is nothing that can affect the reference
3454 // count between the retain and the call.
3455 // Note that Retain need not be in BB.
3456 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3457 DependingInstructions, Visited, PA);
3458 if (DependingInstructions.size() != 1)
3463 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3465 // Check that the pointer is the return value of the call.
3466 if (!Call || Arg != Call)
3469 // Check that the call is a regular call.
3470 InstructionClass Class = GetBasicInstructionClass(Call);
3471 if (Class != IC_CallOrUser && Class != IC_Call)
3474 // If so, we can zap the retain and autorelease.
3477 EraseInstruction(Retain);
3478 EraseInstruction(Autorelease);
3484 DependingInstructions.clear();
3489 bool ObjCARCOpt::doInitialization(Module &M) {
3493 Run = ModuleHasARC(M);
3497 // Identify the imprecise release metadata kind.
3498 ImpreciseReleaseMDKind =
3499 M.getContext().getMDKindID("clang.imprecise_release");
3500 CopyOnEscapeMDKind =
3501 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3503 // Intuitively, objc_retain and others are nocapture, however in practice
3504 // they are not, because they return their argument value. And objc_release
3505 // calls finalizers.
3507 // These are initialized lazily.
3509 AutoreleaseRVCallee = 0;
3512 RetainBlockCallee = 0;
3513 AutoreleaseCallee = 0;
3518 bool ObjCARCOpt::runOnFunction(Function &F) {
3522 // If nothing in the Module uses ARC, don't do anything.
3528 PA.setAA(&getAnalysis<AliasAnalysis>());
3530 // This pass performs several distinct transformations. As a compile-time aid
3531 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3532 // library functions aren't declared.
3534 // Preliminary optimizations. This also computs UsedInThisFunction.
3535 OptimizeIndividualCalls(F);
3537 // Optimizations for weak pointers.
3538 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3539 (1 << IC_LoadWeakRetained) |
3540 (1 << IC_StoreWeak) |
3541 (1 << IC_InitWeak) |
3542 (1 << IC_CopyWeak) |
3543 (1 << IC_MoveWeak) |
3544 (1 << IC_DestroyWeak)))
3545 OptimizeWeakCalls(F);
3547 // Optimizations for retain+release pairs.
3548 if (UsedInThisFunction & ((1 << IC_Retain) |
3549 (1 << IC_RetainRV) |
3550 (1 << IC_RetainBlock)))
3551 if (UsedInThisFunction & (1 << IC_Release))
3552 // Run OptimizeSequences until it either stops making changes or
3553 // no retain+release pair nesting is detected.
3554 while (OptimizeSequences(F)) {}
3556 // Optimizations if objc_autorelease is used.
3557 if (UsedInThisFunction &
3558 ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
3564 void ObjCARCOpt::releaseMemory() {
3568 //===----------------------------------------------------------------------===//
3570 //===----------------------------------------------------------------------===//
3572 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
3573 // dominated by single calls.
3575 #include "llvm/Operator.h"
3576 #include "llvm/InlineAsm.h"
3577 #include "llvm/Analysis/Dominators.h"
3579 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3582 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3583 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3584 class ObjCARCContract : public FunctionPass {
3588 ProvenanceAnalysis PA;
3590 /// Run - A flag indicating whether this optimization pass should run.
3593 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3594 /// functions, for use in creating calls to them. These are initialized
3595 /// lazily to avoid cluttering up the Module with unused declarations.
3596 Constant *StoreStrongCallee,
3597 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3599 /// RetainRVMarker - The inline asm string to insert between calls and
3600 /// RetainRV calls to make the optimization work on targets which need it.
3601 const MDString *RetainRVMarker;
3603 Constant *getStoreStrongCallee(Module *M);
3604 Constant *getRetainAutoreleaseCallee(Module *M);
3605 Constant *getRetainAutoreleaseRVCallee(Module *M);
3607 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3608 InstructionClass Class,
3609 SmallPtrSet<Instruction *, 4>
3610 &DependingInstructions,
3611 SmallPtrSet<const BasicBlock *, 4>
3614 void ContractRelease(Instruction *Release,
3615 inst_iterator &Iter);
3617 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3618 virtual bool doInitialization(Module &M);
3619 virtual bool runOnFunction(Function &F);
3623 ObjCARCContract() : FunctionPass(ID) {
3624 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3629 char ObjCARCContract::ID = 0;
3630 INITIALIZE_PASS_BEGIN(ObjCARCContract,
3631 "objc-arc-contract", "ObjC ARC contraction", false, false)
3632 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3633 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3634 INITIALIZE_PASS_END(ObjCARCContract,
3635 "objc-arc-contract", "ObjC ARC contraction", false, false)
3637 Pass *llvm::createObjCARCContractPass() {
3638 return new ObjCARCContract();
3641 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3642 AU.addRequired<AliasAnalysis>();
3643 AU.addRequired<DominatorTree>();
3644 AU.setPreservesCFG();
3647 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3648 if (!StoreStrongCallee) {
3649 LLVMContext &C = M->getContext();
3650 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3651 Type *I8XX = PointerType::getUnqual(I8X);
3652 std::vector<Type *> Params;
3653 Params.push_back(I8XX);
3654 Params.push_back(I8X);
3656 AttrListPtr Attributes;
3657 Attributes.addAttr(~0u, Attribute::NoUnwind);
3658 Attributes.addAttr(1, Attribute::NoCapture);
3661 M->getOrInsertFunction(
3663 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3666 return StoreStrongCallee;
3669 Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3670 if (!RetainAutoreleaseCallee) {
3671 LLVMContext &C = M->getContext();
3672 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3673 std::vector<Type *> Params;
3674 Params.push_back(I8X);
3676 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3677 AttrListPtr Attributes;
3678 Attributes.addAttr(~0u, Attribute::NoUnwind);
3679 RetainAutoreleaseCallee =
3680 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3682 return RetainAutoreleaseCallee;
3685 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3686 if (!RetainAutoreleaseRVCallee) {
3687 LLVMContext &C = M->getContext();
3688 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3689 std::vector<Type *> Params;
3690 Params.push_back(I8X);
3692 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3693 AttrListPtr Attributes;
3694 Attributes.addAttr(~0u, Attribute::NoUnwind);
3695 RetainAutoreleaseRVCallee =
3696 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3699 return RetainAutoreleaseRVCallee;
3702 /// ContractAutorelease - Merge an autorelease with a retain into a fused
3705 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3706 InstructionClass Class,
3707 SmallPtrSet<Instruction *, 4>
3708 &DependingInstructions,
3709 SmallPtrSet<const BasicBlock *, 4>
3711 const Value *Arg = GetObjCArg(Autorelease);
3713 // Check that there are no instructions between the retain and the autorelease
3714 // (such as an autorelease_pop) which may change the count.
3715 CallInst *Retain = 0;
3716 if (Class == IC_AutoreleaseRV)
3717 FindDependencies(RetainAutoreleaseRVDep, Arg,
3718 Autorelease->getParent(), Autorelease,
3719 DependingInstructions, Visited, PA);
3721 FindDependencies(RetainAutoreleaseDep, Arg,
3722 Autorelease->getParent(), Autorelease,
3723 DependingInstructions, Visited, PA);
3726 if (DependingInstructions.size() != 1) {
3727 DependingInstructions.clear();
3731 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3732 DependingInstructions.clear();
3735 GetBasicInstructionClass(Retain) != IC_Retain ||
3736 GetObjCArg(Retain) != Arg)
3742 if (Class == IC_AutoreleaseRV)
3743 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3745 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3747 EraseInstruction(Autorelease);
3751 /// ContractRelease - Attempt to merge an objc_release with a store, load, and
3752 /// objc_retain to form an objc_storeStrong. This can be a little tricky because
3753 /// the instructions don't always appear in order, and there may be unrelated
3754 /// intervening instructions.
3755 void ObjCARCContract::ContractRelease(Instruction *Release,
3756 inst_iterator &Iter) {
3757 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
3758 if (!Load || !Load->isSimple()) return;
3760 // For now, require everything to be in one basic block.
3761 BasicBlock *BB = Release->getParent();
3762 if (Load->getParent() != BB) return;
3764 // Walk down to find the store.
3765 BasicBlock::iterator I = Load, End = BB->end();
3767 AliasAnalysis::Location Loc = AA->getLocation(Load);
3770 IsRetain(GetBasicInstructionClass(I)) ||
3771 !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
3773 StoreInst *Store = dyn_cast<StoreInst>(I);
3774 if (!Store || !Store->isSimple()) return;
3775 if (Store->getPointerOperand() != Loc.Ptr) return;
3777 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3779 // Walk up to find the retain.
3781 BasicBlock::iterator Begin = BB->begin();
3782 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3784 Instruction *Retain = I;
3785 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3786 if (GetObjCArg(Retain) != New) return;
3791 LLVMContext &C = Release->getContext();
3792 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3793 Type *I8XX = PointerType::getUnqual(I8X);
3795 Value *Args[] = { Load->getPointerOperand(), New };
3796 if (Args[0]->getType() != I8XX)
3797 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3798 if (Args[1]->getType() != I8X)
3799 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3800 CallInst *StoreStrong =
3801 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
3803 StoreStrong->setDoesNotThrow();
3804 StoreStrong->setDebugLoc(Store->getDebugLoc());
3806 if (&*Iter == Store) ++Iter;
3807 Store->eraseFromParent();
3808 Release->eraseFromParent();
3809 EraseInstruction(Retain);
3810 if (Load->use_empty())
3811 Load->eraseFromParent();
3814 bool ObjCARCContract::doInitialization(Module &M) {
3815 Run = ModuleHasARC(M);
3819 // These are initialized lazily.
3820 StoreStrongCallee = 0;
3821 RetainAutoreleaseCallee = 0;
3822 RetainAutoreleaseRVCallee = 0;
3824 // Initialize RetainRVMarker.
3826 if (NamedMDNode *NMD =
3827 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3828 if (NMD->getNumOperands() == 1) {
3829 const MDNode *N = NMD->getOperand(0);
3830 if (N->getNumOperands() == 1)
3831 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
3838 bool ObjCARCContract::runOnFunction(Function &F) {
3842 // If nothing in the Module uses ARC, don't do anything.
3847 AA = &getAnalysis<AliasAnalysis>();
3848 DT = &getAnalysis<DominatorTree>();
3850 PA.setAA(&getAnalysis<AliasAnalysis>());
3852 // For ObjC library calls which return their argument, replace uses of the
3853 // argument with uses of the call return value, if it dominates the use. This
3854 // reduces register pressure.
3855 SmallPtrSet<Instruction *, 4> DependingInstructions;
3856 SmallPtrSet<const BasicBlock *, 4> Visited;
3857 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3858 Instruction *Inst = &*I++;
3860 // Only these library routines return their argument. In particular,
3861 // objc_retainBlock does not necessarily return its argument.
3862 InstructionClass Class = GetBasicInstructionClass(Inst);
3865 case IC_FusedRetainAutorelease:
3866 case IC_FusedRetainAutoreleaseRV:
3868 case IC_Autorelease:
3869 case IC_AutoreleaseRV:
3870 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
3874 // If we're compiling for a target which needs a special inline-asm
3875 // marker to do the retainAutoreleasedReturnValue optimization,
3877 if (!RetainRVMarker)
3879 BasicBlock::iterator BBI = Inst;
3881 while (isNoopInstruction(BBI)) --BBI;
3882 if (&*BBI == GetObjCArg(Inst)) {
3884 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
3885 /*isVarArg=*/false),
3886 RetainRVMarker->getString(),
3887 /*Constraints=*/"", /*hasSideEffects=*/true);
3888 CallInst::Create(IA, "", Inst);
3893 // objc_initWeak(p, null) => *p = null
3894 CallInst *CI = cast<CallInst>(Inst);
3895 if (isNullOrUndef(CI->getArgOperand(1))) {
3897 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
3899 new StoreInst(Null, CI->getArgOperand(0), CI);
3900 CI->replaceAllUsesWith(Null);
3901 CI->eraseFromParent();
3906 ContractRelease(Inst, I);
3912 // Don't use GetObjCArg because we don't want to look through bitcasts
3913 // and such; to do the replacement, the argument must have type i8*.
3914 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
3916 // If we're compiling bugpointed code, don't get in trouble.
3917 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
3919 // Look through the uses of the pointer.
3920 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
3922 Use &U = UI.getUse();
3923 unsigned OperandNo = UI.getOperandNo();
3924 ++UI; // Increment UI now, because we may unlink its element.
3925 if (Instruction *UserInst = dyn_cast<Instruction>(U.getUser()))
3926 if (Inst != UserInst && DT->dominates(Inst, UserInst)) {
3928 Instruction *Replacement = Inst;
3929 Type *UseTy = U.get()->getType();
3930 if (PHINode *PHI = dyn_cast<PHINode>(UserInst)) {
3931 // For PHI nodes, insert the bitcast in the predecessor block.
3933 PHINode::getIncomingValueNumForOperand(OperandNo);
3935 PHI->getIncomingBlock(ValNo);
3936 if (Replacement->getType() != UseTy)
3937 Replacement = new BitCastInst(Replacement, UseTy, "",
3939 for (unsigned i = 0, e = PHI->getNumIncomingValues();
3941 if (PHI->getIncomingBlock(i) == BB) {
3942 // Keep the UI iterator valid.
3943 if (&PHI->getOperandUse(
3944 PHINode::getOperandNumForIncomingValue(i)) ==
3947 PHI->setIncomingValue(i, Replacement);
3950 if (Replacement->getType() != UseTy)
3951 Replacement = new BitCastInst(Replacement, UseTy, "", UserInst);
3957 // If Arg is a no-op casted pointer, strip one level of casts and
3959 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
3960 Arg = BI->getOperand(0);
3961 else if (isa<GEPOperator>(Arg) &&
3962 cast<GEPOperator>(Arg)->hasAllZeroIndices())
3963 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
3964 else if (isa<GlobalAlias>(Arg) &&
3965 !cast<GlobalAlias>(Arg)->mayBeOverridden())
3966 Arg = cast<GlobalAlias>(Arg)->getAliasee();