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 //===----------------------------------------------------------------------===//
891 /// ObjCARCAPElim - Autorelease pool elimination.
892 class ObjCARCAPElim : public ModulePass {
893 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
894 virtual bool runOnModule(Module &M);
896 bool MayAutorelease(CallSite CS);
897 bool OptimizeBB(BasicBlock *BB);
901 ObjCARCAPElim() : ModulePass(ID) {
902 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
907 char ObjCARCAPElim::ID = 0;
908 INITIALIZE_PASS(ObjCARCAPElim,
910 "ObjC ARC autorelease pool elimination",
913 Pass *llvm::createObjCARCAPElimPass() {
914 return new ObjCARCAPElim();
917 void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
918 AU.setPreservesCFG();
921 /// MayAutorelease - Interprocedurally determine if calls made by the
922 /// given call site can possibly produce autoreleases.
923 bool ObjCARCAPElim::MayAutorelease(CallSite CS) {
924 if (Function *Callee = CS.getCalledFunction()) {
925 if (Callee->isDeclaration() || Callee->mayBeOverridden())
927 for (Function::iterator I = Callee->begin(), E = Callee->end();
930 for (BasicBlock::iterator J = BB->begin(), F = BB->end(); J != F; ++J)
931 if (CallSite JCS = CallSite(J))
932 if (!JCS.onlyReadsMemory() && MayAutorelease(JCS))
941 bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
942 bool Changed = false;
944 Instruction *Push = 0;
945 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
946 Instruction *Inst = I++;
947 switch (GetBasicInstructionClass(Inst)) {
948 case IC_AutoreleasepoolPush:
951 case IC_AutoreleasepoolPop:
952 // If this pop matches a push and nothing in between can autorelease,
954 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
956 Inst->eraseFromParent();
957 Push->eraseFromParent();
962 if (MayAutorelease(CallSite(Inst)))
973 bool ObjCARCAPElim::runOnModule(Module &M) {
977 // If nothing in the Module uses ARC, don't do anything.
978 if (!ModuleHasARC(M))
981 bool Changed = false;
983 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
985 // Only look at function definitions.
986 if (F->isDeclaration())
988 // Only look at global constructor functions. Unfortunately,
989 // the name is the most convenient way to recognize them.
990 if (!F->getName().startswith("_GLOBAL__I_"))
992 // Only look at functions with one basic block.
993 if (llvm::next(F->begin()) != F->end())
995 // Ok, a single-block constructor function definition. Try to optimize it.
996 Changed |= OptimizeBB(F->begin());
1002 //===----------------------------------------------------------------------===//
1003 // ARC optimization.
1004 //===----------------------------------------------------------------------===//
1006 // TODO: On code like this:
1009 // stuff_that_cannot_release()
1010 // objc_autorelease(%x)
1011 // stuff_that_cannot_release()
1013 // stuff_that_cannot_release()
1014 // objc_autorelease(%x)
1016 // The second retain and autorelease can be deleted.
1018 // TODO: It should be possible to delete
1019 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
1020 // pairs if nothing is actually autoreleased between them. Also, autorelease
1021 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1022 // after inlining) can be turned into plain release calls.
1024 // TODO: Critical-edge splitting. If the optimial insertion point is
1025 // a critical edge, the current algorithm has to fail, because it doesn't
1026 // know how to split edges. It should be possible to make the optimizer
1027 // think in terms of edges, rather than blocks, and then split critical
1030 // TODO: OptimizeSequences could generalized to be Interprocedural.
1032 // TODO: Recognize that a bunch of other objc runtime calls have
1033 // non-escaping arguments and non-releasing arguments, and may be
1034 // non-autoreleasing.
1036 // TODO: Sink autorelease calls as far as possible. Unfortunately we
1037 // usually can't sink them past other calls, which would be the main
1038 // case where it would be useful.
1040 // TODO: The pointer returned from objc_loadWeakRetained is retained.
1042 // TODO: Delete release+retain pairs (rare).
1044 #include "llvm/GlobalAlias.h"
1045 #include "llvm/Constants.h"
1046 #include "llvm/LLVMContext.h"
1047 #include "llvm/Support/ErrorHandling.h"
1048 #include "llvm/Support/CFG.h"
1049 #include "llvm/ADT/Statistic.h"
1050 #include "llvm/ADT/SmallPtrSet.h"
1051 #include "llvm/ADT/DenseSet.h"
1053 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1054 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1055 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1056 STATISTIC(NumRets, "Number of return value forwarding "
1057 "retain+autoreleaes eliminated");
1058 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1059 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1062 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1063 /// uses many of the same techniques, except it uses special ObjC-specific
1064 /// reasoning about pointer relationships.
1065 class ProvenanceAnalysis {
1068 typedef std::pair<const Value *, const Value *> ValuePairTy;
1069 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1070 CachedResultsTy CachedResults;
1072 bool relatedCheck(const Value *A, const Value *B);
1073 bool relatedSelect(const SelectInst *A, const Value *B);
1074 bool relatedPHI(const PHINode *A, const Value *B);
1076 // Do not implement.
1077 void operator=(const ProvenanceAnalysis &);
1078 ProvenanceAnalysis(const ProvenanceAnalysis &);
1081 ProvenanceAnalysis() {}
1083 void setAA(AliasAnalysis *aa) { AA = aa; }
1085 AliasAnalysis *getAA() const { return AA; }
1087 bool related(const Value *A, const Value *B);
1090 CachedResults.clear();
1095 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1096 // If the values are Selects with the same condition, we can do a more precise
1097 // check: just check for relations between the values on corresponding arms.
1098 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
1099 if (A->getCondition() == SB->getCondition()) {
1100 if (related(A->getTrueValue(), SB->getTrueValue()))
1102 if (related(A->getFalseValue(), SB->getFalseValue()))
1107 // Check both arms of the Select node individually.
1108 if (related(A->getTrueValue(), B))
1110 if (related(A->getFalseValue(), B))
1113 // The arms both checked out.
1117 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1118 // If the values are PHIs in the same block, we can do a more precise as well
1119 // as efficient check: just check for relations between the values on
1120 // corresponding edges.
1121 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1122 if (PNB->getParent() == A->getParent()) {
1123 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1124 if (related(A->getIncomingValue(i),
1125 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1130 // Check each unique source of the PHI node against B.
1131 SmallPtrSet<const Value *, 4> UniqueSrc;
1132 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1133 const Value *PV1 = A->getIncomingValue(i);
1134 if (UniqueSrc.insert(PV1) && related(PV1, B))
1138 // All of the arms checked out.
1142 /// isStoredObjCPointer - Test if the value of P, or any value covered by its
1143 /// provenance, is ever stored within the function (not counting callees).
1144 static bool isStoredObjCPointer(const Value *P) {
1145 SmallPtrSet<const Value *, 8> Visited;
1146 SmallVector<const Value *, 8> Worklist;
1147 Worklist.push_back(P);
1150 P = Worklist.pop_back_val();
1151 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1153 const User *Ur = *UI;
1154 if (isa<StoreInst>(Ur)) {
1155 if (UI.getOperandNo() == 0)
1156 // The pointer is stored.
1158 // The pointed is stored through.
1161 if (isa<CallInst>(Ur))
1162 // The pointer is passed as an argument, ignore this.
1164 if (isa<PtrToIntInst>(P))
1165 // Assume the worst.
1167 if (Visited.insert(Ur))
1168 Worklist.push_back(Ur);
1170 } while (!Worklist.empty());
1172 // Everything checked out.
1176 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1177 // Skip past provenance pass-throughs.
1178 A = GetUnderlyingObjCPtr(A);
1179 B = GetUnderlyingObjCPtr(B);
1185 // Ask regular AliasAnalysis, for a first approximation.
1186 switch (AA->alias(A, B)) {
1187 case AliasAnalysis::NoAlias:
1189 case AliasAnalysis::MustAlias:
1190 case AliasAnalysis::PartialAlias:
1192 case AliasAnalysis::MayAlias:
1196 bool AIsIdentified = IsObjCIdentifiedObject(A);
1197 bool BIsIdentified = IsObjCIdentifiedObject(B);
1199 // An ObjC-Identified object can't alias a load if it is never locally stored.
1200 if (AIsIdentified) {
1201 if (BIsIdentified) {
1202 // If both pointers have provenance, they can be directly compared.
1206 if (isa<LoadInst>(B))
1207 return isStoredObjCPointer(A);
1210 if (BIsIdentified && isa<LoadInst>(A))
1211 return isStoredObjCPointer(B);
1214 // Special handling for PHI and Select.
1215 if (const PHINode *PN = dyn_cast<PHINode>(A))
1216 return relatedPHI(PN, B);
1217 if (const PHINode *PN = dyn_cast<PHINode>(B))
1218 return relatedPHI(PN, A);
1219 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1220 return relatedSelect(S, B);
1221 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1222 return relatedSelect(S, A);
1228 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1229 // Begin by inserting a conservative value into the map. If the insertion
1230 // fails, we have the answer already. If it succeeds, leave it there until we
1231 // compute the real answer to guard against recursive queries.
1232 if (A > B) std::swap(A, B);
1233 std::pair<CachedResultsTy::iterator, bool> Pair =
1234 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1236 return Pair.first->second;
1238 bool Result = relatedCheck(A, B);
1239 CachedResults[ValuePairTy(A, B)] = Result;
1244 // Sequence - A sequence of states that a pointer may go through in which an
1245 // objc_retain and objc_release are actually needed.
1248 S_Retain, ///< objc_retain(x)
1249 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1250 S_Use, ///< any use of x
1251 S_Stop, ///< like S_Release, but code motion is stopped
1252 S_Release, ///< objc_release(x)
1253 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1257 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1261 if (A == S_None || B == S_None)
1264 if (A > B) std::swap(A, B);
1266 // Choose the side which is further along in the sequence.
1267 if ((A == S_Retain || A == S_CanRelease) &&
1268 (B == S_CanRelease || B == S_Use))
1271 // Choose the side which is further along in the sequence.
1272 if ((A == S_Use || A == S_CanRelease) &&
1273 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
1275 // If both sides are releases, choose the more conservative one.
1276 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1278 if (A == S_Release && B == S_MovableRelease)
1286 /// RRInfo - Unidirectional information about either a
1287 /// retain-decrement-use-release sequence or release-use-decrement-retain
1288 /// reverese sequence.
1290 /// KnownSafe - After an objc_retain, the reference count of the referenced
1291 /// object is known to be positive. Similarly, before an objc_release, the
1292 /// reference count of the referenced object is known to be positive. If
1293 /// there are retain-release pairs in code regions where the retain count
1294 /// is known to be positive, they can be eliminated, regardless of any side
1295 /// effects between them.
1297 /// Also, a retain+release pair nested within another retain+release
1298 /// pair all on the known same pointer value can be eliminated, regardless
1299 /// of any intervening side effects.
1301 /// KnownSafe is true when either of these conditions is satisfied.
1304 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1305 /// opposed to objc_retain calls).
1308 /// IsTailCallRelease - True of the objc_release calls are all marked
1309 /// with the "tail" keyword.
1310 bool IsTailCallRelease;
1312 /// Partial - True of we've seen an opportunity for partial RR elimination,
1313 /// such as pushing calls into a CFG triangle or into one side of a
1315 /// TODO: Consider moving this to PtrState.
1318 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1319 /// a clang.imprecise_release tag, this is the metadata tag.
1320 MDNode *ReleaseMetadata;
1322 /// Calls - For a top-down sequence, the set of objc_retains or
1323 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1324 SmallPtrSet<Instruction *, 2> Calls;
1326 /// ReverseInsertPts - The set of optimal insert positions for
1327 /// moving calls in the opposite sequence.
1328 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1331 KnownSafe(false), IsRetainBlock(false),
1332 IsTailCallRelease(false), Partial(false),
1333 ReleaseMetadata(0) {}
1339 void RRInfo::clear() {
1341 IsRetainBlock = false;
1342 IsTailCallRelease = false;
1344 ReleaseMetadata = 0;
1346 ReverseInsertPts.clear();
1350 /// PtrState - This class summarizes several per-pointer runtime properties
1351 /// which are propogated through the flow graph.
1353 /// RefCount - The known minimum number of reference count increments.
1356 /// NestCount - The known minimum level of retain+release nesting.
1359 /// Seq - The current position in the sequence.
1363 /// RRI - Unidirectional information about the current sequence.
1364 /// TODO: Encapsulate this better.
1367 PtrState() : RefCount(0), NestCount(0), Seq(S_None) {}
1369 void SetAtLeastOneRefCount() {
1370 if (RefCount == 0) RefCount = 1;
1373 void IncrementRefCount() {
1374 if (RefCount != UINT_MAX) ++RefCount;
1377 void DecrementRefCount() {
1378 if (RefCount != 0) --RefCount;
1381 bool IsKnownIncremented() const {
1382 return RefCount > 0;
1385 void IncrementNestCount() {
1386 if (NestCount != UINT_MAX) ++NestCount;
1389 void DecrementNestCount() {
1390 if (NestCount != 0) --NestCount;
1393 bool IsKnownNested() const {
1394 return NestCount > 0;
1397 void SetSeq(Sequence NewSeq) {
1401 Sequence GetSeq() const {
1405 void ClearSequenceProgress() {
1410 void Merge(const PtrState &Other, bool TopDown);
1415 PtrState::Merge(const PtrState &Other, bool TopDown) {
1416 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1417 RefCount = std::min(RefCount, Other.RefCount);
1418 NestCount = std::min(NestCount, Other.NestCount);
1420 // We can't merge a plain objc_retain with an objc_retainBlock.
1421 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1424 // If we're not in a sequence (anymore), drop all associated state.
1425 if (Seq == S_None) {
1427 } else if (RRI.Partial || Other.RRI.Partial) {
1428 // If we're doing a merge on a path that's previously seen a partial
1429 // merge, conservatively drop the sequence, to avoid doing partial
1430 // RR elimination. If the branch predicates for the two merge differ,
1431 // mixing them is unsafe.
1435 // Conservatively merge the ReleaseMetadata information.
1436 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1437 RRI.ReleaseMetadata = 0;
1439 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
1440 RRI.IsTailCallRelease = RRI.IsTailCallRelease && Other.RRI.IsTailCallRelease;
1441 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1443 // Merge the insert point sets. If there are any differences,
1444 // that makes this a partial merge.
1445 RRI.Partial = RRI.ReverseInsertPts.size() !=
1446 Other.RRI.ReverseInsertPts.size();
1447 for (SmallPtrSet<Instruction *, 2>::const_iterator
1448 I = Other.RRI.ReverseInsertPts.begin(),
1449 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1450 RRI.Partial |= RRI.ReverseInsertPts.insert(*I);
1455 /// BBState - Per-BasicBlock state.
1457 /// TopDownPathCount - The number of unique control paths from the entry
1458 /// which can reach this block.
1459 unsigned TopDownPathCount;
1461 /// BottomUpPathCount - The number of unique control paths to exits
1462 /// from this block.
1463 unsigned BottomUpPathCount;
1465 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1466 typedef MapVector<const Value *, PtrState> MapTy;
1468 /// PerPtrTopDown - The top-down traversal uses this to record information
1469 /// known about a pointer at the bottom of each block.
1470 MapTy PerPtrTopDown;
1472 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1473 /// known about a pointer at the top of each block.
1474 MapTy PerPtrBottomUp;
1477 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1479 typedef MapTy::iterator ptr_iterator;
1480 typedef MapTy::const_iterator ptr_const_iterator;
1482 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1483 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1484 ptr_const_iterator top_down_ptr_begin() const {
1485 return PerPtrTopDown.begin();
1487 ptr_const_iterator top_down_ptr_end() const {
1488 return PerPtrTopDown.end();
1491 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1492 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1493 ptr_const_iterator bottom_up_ptr_begin() const {
1494 return PerPtrBottomUp.begin();
1496 ptr_const_iterator bottom_up_ptr_end() const {
1497 return PerPtrBottomUp.end();
1500 /// SetAsEntry - Mark this block as being an entry block, which has one
1501 /// path from the entry by definition.
1502 void SetAsEntry() { TopDownPathCount = 1; }
1504 /// SetAsExit - Mark this block as being an exit block, which has one
1505 /// path to an exit by definition.
1506 void SetAsExit() { BottomUpPathCount = 1; }
1508 PtrState &getPtrTopDownState(const Value *Arg) {
1509 return PerPtrTopDown[Arg];
1512 PtrState &getPtrBottomUpState(const Value *Arg) {
1513 return PerPtrBottomUp[Arg];
1516 void clearBottomUpPointers() {
1517 PerPtrBottomUp.clear();
1520 void clearTopDownPointers() {
1521 PerPtrTopDown.clear();
1524 void InitFromPred(const BBState &Other);
1525 void InitFromSucc(const BBState &Other);
1526 void MergePred(const BBState &Other);
1527 void MergeSucc(const BBState &Other);
1529 /// GetAllPathCount - Return the number of possible unique paths from an
1530 /// entry to an exit which pass through this block. This is only valid
1531 /// after both the top-down and bottom-up traversals are complete.
1532 unsigned GetAllPathCount() const {
1533 return TopDownPathCount * BottomUpPathCount;
1536 /// IsVisitedTopDown - Test whether the block for this BBState has been
1537 /// visited by the top-down portion of the algorithm.
1538 bool isVisitedTopDown() const {
1539 return TopDownPathCount != 0;
1544 void BBState::InitFromPred(const BBState &Other) {
1545 PerPtrTopDown = Other.PerPtrTopDown;
1546 TopDownPathCount = Other.TopDownPathCount;
1549 void BBState::InitFromSucc(const BBState &Other) {
1550 PerPtrBottomUp = Other.PerPtrBottomUp;
1551 BottomUpPathCount = Other.BottomUpPathCount;
1554 /// MergePred - The top-down traversal uses this to merge information about
1555 /// predecessors to form the initial state for a new block.
1556 void BBState::MergePred(const BBState &Other) {
1557 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1558 // loop backedge. Loop backedges are special.
1559 TopDownPathCount += Other.TopDownPathCount;
1561 // For each entry in the other set, if our set has an entry with the same key,
1562 // merge the entries. Otherwise, copy the entry and merge it with an empty
1564 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1565 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1566 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1567 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1571 // For each entry in our set, if the other set doesn't have an entry with the
1572 // same key, force it to merge with an empty entry.
1573 for (ptr_iterator MI = top_down_ptr_begin(),
1574 ME = top_down_ptr_end(); MI != ME; ++MI)
1575 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1576 MI->second.Merge(PtrState(), /*TopDown=*/true);
1579 /// MergeSucc - The bottom-up traversal uses this to merge information about
1580 /// successors to form the initial state for a new block.
1581 void BBState::MergeSucc(const BBState &Other) {
1582 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1583 // loop backedge. Loop backedges are special.
1584 BottomUpPathCount += Other.BottomUpPathCount;
1586 // For each entry in the other set, if our set has an entry with the
1587 // same key, merge the entries. Otherwise, copy the entry and merge
1588 // it with an empty entry.
1589 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1590 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1591 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1592 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1596 // For each entry in our set, if the other set doesn't have an entry
1597 // with the same key, force it to merge with an empty entry.
1598 for (ptr_iterator MI = bottom_up_ptr_begin(),
1599 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1600 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1601 MI->second.Merge(PtrState(), /*TopDown=*/false);
1605 /// ObjCARCOpt - The main ARC optimization pass.
1606 class ObjCARCOpt : public FunctionPass {
1608 ProvenanceAnalysis PA;
1610 /// Run - A flag indicating whether this optimization pass should run.
1613 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1614 /// functions, for use in creating calls to them. These are initialized
1615 /// lazily to avoid cluttering up the Module with unused declarations.
1616 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
1617 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
1619 /// UsedInThisFunciton - Flags which determine whether each of the
1620 /// interesting runtine functions is in fact used in the current function.
1621 unsigned UsedInThisFunction;
1623 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1625 unsigned ImpreciseReleaseMDKind;
1627 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
1629 unsigned CopyOnEscapeMDKind;
1631 Constant *getRetainRVCallee(Module *M);
1632 Constant *getAutoreleaseRVCallee(Module *M);
1633 Constant *getReleaseCallee(Module *M);
1634 Constant *getRetainCallee(Module *M);
1635 Constant *getRetainBlockCallee(Module *M);
1636 Constant *getAutoreleaseCallee(Module *M);
1638 bool IsRetainBlockOptimizable(const Instruction *Inst);
1640 void OptimizeRetainCall(Function &F, Instruction *Retain);
1641 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1642 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1643 void OptimizeIndividualCalls(Function &F);
1645 void CheckForCFGHazards(const BasicBlock *BB,
1646 DenseMap<const BasicBlock *, BBState> &BBStates,
1647 BBState &MyStates) const;
1648 bool VisitBottomUp(BasicBlock *BB,
1649 DenseMap<const BasicBlock *, BBState> &BBStates,
1650 MapVector<Value *, RRInfo> &Retains);
1651 bool VisitTopDown(BasicBlock *BB,
1652 DenseMap<const BasicBlock *, BBState> &BBStates,
1653 DenseMap<Value *, RRInfo> &Releases);
1654 bool Visit(Function &F,
1655 DenseMap<const BasicBlock *, BBState> &BBStates,
1656 MapVector<Value *, RRInfo> &Retains,
1657 DenseMap<Value *, RRInfo> &Releases);
1659 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1660 MapVector<Value *, RRInfo> &Retains,
1661 DenseMap<Value *, RRInfo> &Releases,
1662 SmallVectorImpl<Instruction *> &DeadInsts,
1665 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1666 MapVector<Value *, RRInfo> &Retains,
1667 DenseMap<Value *, RRInfo> &Releases,
1670 void OptimizeWeakCalls(Function &F);
1672 bool OptimizeSequences(Function &F);
1674 void OptimizeReturns(Function &F);
1676 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1677 virtual bool doInitialization(Module &M);
1678 virtual bool runOnFunction(Function &F);
1679 virtual void releaseMemory();
1683 ObjCARCOpt() : FunctionPass(ID) {
1684 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1689 char ObjCARCOpt::ID = 0;
1690 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1691 "objc-arc", "ObjC ARC optimization", false, false)
1692 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1693 INITIALIZE_PASS_END(ObjCARCOpt,
1694 "objc-arc", "ObjC ARC optimization", false, false)
1696 Pass *llvm::createObjCARCOptPass() {
1697 return new ObjCARCOpt();
1700 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1701 AU.addRequired<ObjCARCAliasAnalysis>();
1702 AU.addRequired<AliasAnalysis>();
1703 // ARC optimization doesn't currently split critical edges.
1704 AU.setPreservesCFG();
1707 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1708 // Without the magic metadata tag, we have to assume this might be an
1709 // objc_retainBlock call inserted to convert a block pointer to an id,
1710 // in which case it really is needed.
1711 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1714 // If the pointer "escapes" (not including being used in a call),
1715 // the copy may be needed.
1716 if (DoesObjCBlockEscape(Inst))
1719 // Otherwise, it's not needed.
1723 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1724 if (!RetainRVCallee) {
1725 LLVMContext &C = M->getContext();
1726 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1727 std::vector<Type *> Params;
1728 Params.push_back(I8X);
1730 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1731 AttrListPtr Attributes;
1732 Attributes.addAttr(~0u, Attribute::NoUnwind);
1734 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1737 return RetainRVCallee;
1740 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1741 if (!AutoreleaseRVCallee) {
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);
1750 AutoreleaseRVCallee =
1751 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1754 return AutoreleaseRVCallee;
1757 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1758 if (!ReleaseCallee) {
1759 LLVMContext &C = M->getContext();
1760 std::vector<Type *> Params;
1761 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1762 AttrListPtr Attributes;
1763 Attributes.addAttr(~0u, Attribute::NoUnwind);
1765 M->getOrInsertFunction(
1767 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1770 return ReleaseCallee;
1773 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1774 if (!RetainCallee) {
1775 LLVMContext &C = M->getContext();
1776 std::vector<Type *> Params;
1777 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1778 AttrListPtr Attributes;
1779 Attributes.addAttr(~0u, Attribute::NoUnwind);
1781 M->getOrInsertFunction(
1783 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1786 return RetainCallee;
1789 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1790 if (!RetainBlockCallee) {
1791 LLVMContext &C = M->getContext();
1792 std::vector<Type *> Params;
1793 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1794 AttrListPtr Attributes;
1795 // objc_retainBlock is not nounwind because it calls user copy constructors
1796 // which could theoretically throw.
1798 M->getOrInsertFunction(
1800 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1803 return RetainBlockCallee;
1806 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1807 if (!AutoreleaseCallee) {
1808 LLVMContext &C = M->getContext();
1809 std::vector<Type *> Params;
1810 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1811 AttrListPtr Attributes;
1812 Attributes.addAttr(~0u, Attribute::NoUnwind);
1814 M->getOrInsertFunction(
1816 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1819 return AutoreleaseCallee;
1822 /// CanAlterRefCount - Test whether the given instruction can result in a
1823 /// reference count modification (positive or negative) for the pointer's
1826 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1827 ProvenanceAnalysis &PA, InstructionClass Class) {
1829 case IC_Autorelease:
1830 case IC_AutoreleaseRV:
1832 // These operations never directly modify a reference count.
1837 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1838 assert(CS && "Only calls can alter reference counts!");
1840 // See if AliasAnalysis can help us with the call.
1841 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1842 if (AliasAnalysis::onlyReadsMemory(MRB))
1844 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1845 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1847 const Value *Op = *I;
1848 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1854 // Assume the worst.
1858 /// CanUse - Test whether the given instruction can "use" the given pointer's
1859 /// object in a way that requires the reference count to be positive.
1861 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1862 InstructionClass Class) {
1863 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1864 if (Class == IC_Call)
1867 // Consider various instructions which may have pointer arguments which are
1869 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1870 // Comparing a pointer with null, or any other constant, isn't really a use,
1871 // because we don't care what the pointer points to, or about the values
1872 // of any other dynamic reference-counted pointers.
1873 if (!IsPotentialUse(ICI->getOperand(1)))
1875 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1876 // For calls, just check the arguments (and not the callee operand).
1877 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1878 OE = CS.arg_end(); OI != OE; ++OI) {
1879 const Value *Op = *OI;
1880 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1884 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1885 // Special-case stores, because we don't care about the stored value, just
1886 // the store address.
1887 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1888 // If we can't tell what the underlying object was, assume there is a
1890 return IsPotentialUse(Op) && PA.related(Op, Ptr);
1893 // Check each operand for a match.
1894 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1896 const Value *Op = *OI;
1897 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1903 /// CanInterruptRV - Test whether the given instruction can autorelease
1904 /// any pointer or cause an autoreleasepool pop.
1906 CanInterruptRV(InstructionClass Class) {
1908 case IC_AutoreleasepoolPop:
1911 case IC_Autorelease:
1912 case IC_AutoreleaseRV:
1913 case IC_FusedRetainAutorelease:
1914 case IC_FusedRetainAutoreleaseRV:
1922 /// DependenceKind - There are several kinds of dependence-like concepts in
1924 enum DependenceKind {
1925 NeedsPositiveRetainCount,
1926 CanChangeRetainCount,
1927 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1928 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1929 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1933 /// Depends - Test if there can be dependencies on Inst through Arg. This
1934 /// function only tests dependencies relevant for removing pairs of calls.
1936 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1937 ProvenanceAnalysis &PA) {
1938 // If we've reached the definition of Arg, stop.
1943 case NeedsPositiveRetainCount: {
1944 InstructionClass Class = GetInstructionClass(Inst);
1946 case IC_AutoreleasepoolPop:
1947 case IC_AutoreleasepoolPush:
1951 return CanUse(Inst, Arg, PA, Class);
1955 case CanChangeRetainCount: {
1956 InstructionClass Class = GetInstructionClass(Inst);
1958 case IC_AutoreleasepoolPop:
1959 // Conservatively assume this can decrement any count.
1961 case IC_AutoreleasepoolPush:
1965 return CanAlterRefCount(Inst, Arg, PA, Class);
1969 case RetainAutoreleaseDep:
1970 switch (GetBasicInstructionClass(Inst)) {
1971 case IC_AutoreleasepoolPop:
1972 // Don't merge an objc_autorelease with an objc_retain inside a different
1973 // autoreleasepool scope.
1977 // Check for a retain of the same pointer for merging.
1978 return GetObjCArg(Inst) == Arg;
1980 // Nothing else matters for objc_retainAutorelease formation.
1985 case RetainAutoreleaseRVDep: {
1986 InstructionClass Class = GetBasicInstructionClass(Inst);
1990 // Check for a retain of the same pointer for merging.
1991 return GetObjCArg(Inst) == Arg;
1993 // Anything that can autorelease interrupts
1994 // retainAutoreleaseReturnValue formation.
1995 return CanInterruptRV(Class);
2001 return CanInterruptRV(GetBasicInstructionClass(Inst));
2004 llvm_unreachable("Invalid dependence flavor");
2007 /// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2008 /// find local and non-local dependencies on Arg.
2009 /// TODO: Cache results?
2011 FindDependencies(DependenceKind Flavor,
2013 BasicBlock *StartBB, Instruction *StartInst,
2014 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2015 SmallPtrSet<const BasicBlock *, 4> &Visited,
2016 ProvenanceAnalysis &PA) {
2017 BasicBlock::iterator StartPos = StartInst;
2019 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2020 Worklist.push_back(std::make_pair(StartBB, StartPos));
2022 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2023 Worklist.pop_back_val();
2024 BasicBlock *LocalStartBB = Pair.first;
2025 BasicBlock::iterator LocalStartPos = Pair.second;
2026 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2028 if (LocalStartPos == StartBBBegin) {
2029 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2031 // If we've reached the function entry, produce a null dependence.
2032 DependingInstructions.insert(0);
2034 // Add the predecessors to the worklist.
2036 BasicBlock *PredBB = *PI;
2037 if (Visited.insert(PredBB))
2038 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2039 } while (++PI != PE);
2043 Instruction *Inst = --LocalStartPos;
2044 if (Depends(Flavor, Inst, Arg, PA)) {
2045 DependingInstructions.insert(Inst);
2049 } while (!Worklist.empty());
2051 // Determine whether the original StartBB post-dominates all of the blocks we
2052 // visited. If not, insert a sentinal indicating that most optimizations are
2054 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2055 E = Visited.end(); I != E; ++I) {
2056 const BasicBlock *BB = *I;
2059 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2060 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2061 const BasicBlock *Succ = *SI;
2062 if (Succ != StartBB && !Visited.count(Succ)) {
2063 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2070 static bool isNullOrUndef(const Value *V) {
2071 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2074 static bool isNoopInstruction(const Instruction *I) {
2075 return isa<BitCastInst>(I) ||
2076 (isa<GetElementPtrInst>(I) &&
2077 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2080 /// OptimizeRetainCall - Turn objc_retain into
2081 /// objc_retainAutoreleasedReturnValue if the operand is a return value.
2083 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
2084 CallSite CS(GetObjCArg(Retain));
2085 Instruction *Call = CS.getInstruction();
2087 if (Call->getParent() != Retain->getParent()) return;
2089 // Check that the call is next to the retain.
2090 BasicBlock::iterator I = Call;
2092 while (isNoopInstruction(I)) ++I;
2096 // Turn it to an objc_retainAutoreleasedReturnValue..
2099 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2102 /// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
2103 /// objc_retain if the operand is not a return value. Or, if it can be
2104 /// paired with an objc_autoreleaseReturnValue, delete the pair and
2107 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
2108 // Check for the argument being from an immediately preceding call.
2109 Value *Arg = GetObjCArg(RetainRV);
2111 if (Instruction *Call = CS.getInstruction())
2112 if (Call->getParent() == RetainRV->getParent()) {
2113 BasicBlock::iterator I = Call;
2115 while (isNoopInstruction(I)) ++I;
2116 if (&*I == RetainRV)
2120 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2121 // pointer. In this case, we can delete the pair.
2122 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2124 do --I; while (I != Begin && isNoopInstruction(I));
2125 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2126 GetObjCArg(I) == Arg) {
2129 EraseInstruction(I);
2130 EraseInstruction(RetainRV);
2135 // Turn it to a plain objc_retain.
2138 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2142 /// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2143 /// objc_autorelease if the result is not used as a return value.
2145 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
2146 // Check for a return of the pointer value.
2147 const Value *Ptr = GetObjCArg(AutoreleaseRV);
2148 SmallVector<const Value *, 2> Users;
2149 Users.push_back(Ptr);
2151 Ptr = Users.pop_back_val();
2152 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2154 const User *I = *UI;
2155 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2157 if (isa<BitCastInst>(I))
2160 } while (!Users.empty());
2164 cast<CallInst>(AutoreleaseRV)->
2165 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2168 /// OptimizeIndividualCalls - Visit each call, one at a time, and make
2169 /// simplifications without doing any additional analysis.
2170 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2171 // Reset all the flags in preparation for recomputing them.
2172 UsedInThisFunction = 0;
2174 // Visit all objc_* calls in F.
2175 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2176 Instruction *Inst = &*I++;
2177 InstructionClass Class = GetBasicInstructionClass(Inst);
2182 // Delete no-op casts. These function calls have special semantics, but
2183 // the semantics are entirely implemented via lowering in the front-end,
2184 // so by the time they reach the optimizer, they are just no-op calls
2185 // which return their argument.
2187 // There are gray areas here, as the ability to cast reference-counted
2188 // pointers to raw void* and back allows code to break ARC assumptions,
2189 // however these are currently considered to be unimportant.
2193 EraseInstruction(Inst);
2196 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2199 case IC_LoadWeakRetained:
2201 case IC_DestroyWeak: {
2202 CallInst *CI = cast<CallInst>(Inst);
2203 if (isNullOrUndef(CI->getArgOperand(0))) {
2204 Type *Ty = CI->getArgOperand(0)->getType();
2205 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2206 Constant::getNullValue(Ty),
2208 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2209 CI->eraseFromParent();
2216 CallInst *CI = cast<CallInst>(Inst);
2217 if (isNullOrUndef(CI->getArgOperand(0)) ||
2218 isNullOrUndef(CI->getArgOperand(1))) {
2219 Type *Ty = CI->getArgOperand(0)->getType();
2220 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2221 Constant::getNullValue(Ty),
2223 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2224 CI->eraseFromParent();
2230 OptimizeRetainCall(F, Inst);
2233 if (OptimizeRetainRVCall(F, Inst))
2236 case IC_AutoreleaseRV:
2237 OptimizeAutoreleaseRVCall(F, Inst);
2241 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2242 if (IsAutorelease(Class) && Inst->use_empty()) {
2243 CallInst *Call = cast<CallInst>(Inst);
2244 const Value *Arg = Call->getArgOperand(0);
2245 Arg = FindSingleUseIdentifiedObject(Arg);
2250 // Create the declaration lazily.
2251 LLVMContext &C = Inst->getContext();
2253 CallInst::Create(getReleaseCallee(F.getParent()),
2254 Call->getArgOperand(0), "", Call);
2255 NewCall->setMetadata(ImpreciseReleaseMDKind,
2256 MDNode::get(C, ArrayRef<Value *>()));
2257 EraseInstruction(Call);
2263 // For functions which can never be passed stack arguments, add
2265 if (IsAlwaysTail(Class)) {
2267 cast<CallInst>(Inst)->setTailCall();
2270 // Set nounwind as needed.
2271 if (IsNoThrow(Class)) {
2273 cast<CallInst>(Inst)->setDoesNotThrow();
2276 if (!IsNoopOnNull(Class)) {
2277 UsedInThisFunction |= 1 << Class;
2281 const Value *Arg = GetObjCArg(Inst);
2283 // ARC calls with null are no-ops. Delete them.
2284 if (isNullOrUndef(Arg)) {
2287 EraseInstruction(Inst);
2291 // Keep track of which of retain, release, autorelease, and retain_block
2292 // are actually present in this function.
2293 UsedInThisFunction |= 1 << Class;
2295 // If Arg is a PHI, and one or more incoming values to the
2296 // PHI are null, and the call is control-equivalent to the PHI, and there
2297 // are no relevant side effects between the PHI and the call, the call
2298 // could be pushed up to just those paths with non-null incoming values.
2299 // For now, don't bother splitting critical edges for this.
2300 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2301 Worklist.push_back(std::make_pair(Inst, Arg));
2303 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2307 const PHINode *PN = dyn_cast<PHINode>(Arg);
2310 // Determine if the PHI has any null operands, or any incoming
2312 bool HasNull = false;
2313 bool HasCriticalEdges = false;
2314 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2316 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2317 if (isNullOrUndef(Incoming))
2319 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2320 .getNumSuccessors() != 1) {
2321 HasCriticalEdges = true;
2325 // If we have null operands and no critical edges, optimize.
2326 if (!HasCriticalEdges && HasNull) {
2327 SmallPtrSet<Instruction *, 4> DependingInstructions;
2328 SmallPtrSet<const BasicBlock *, 4> Visited;
2330 // Check that there is nothing that cares about the reference
2331 // count between the call and the phi.
2332 FindDependencies(NeedsPositiveRetainCount, Arg,
2333 Inst->getParent(), Inst,
2334 DependingInstructions, Visited, PA);
2335 if (DependingInstructions.size() == 1 &&
2336 *DependingInstructions.begin() == PN) {
2339 // Clone the call into each predecessor that has a non-null value.
2340 CallInst *CInst = cast<CallInst>(Inst);
2341 Type *ParamTy = CInst->getArgOperand(0)->getType();
2342 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2344 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2345 if (!isNullOrUndef(Incoming)) {
2346 CallInst *Clone = cast<CallInst>(CInst->clone());
2347 Value *Op = PN->getIncomingValue(i);
2348 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2349 if (Op->getType() != ParamTy)
2350 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2351 Clone->setArgOperand(0, Op);
2352 Clone->insertBefore(InsertPos);
2353 Worklist.push_back(std::make_pair(Clone, Incoming));
2356 // Erase the original call.
2357 EraseInstruction(CInst);
2361 } while (!Worklist.empty());
2365 /// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2366 /// control flow, or other CFG structures where moving code across the edge
2367 /// would result in it being executed more.
2369 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2370 DenseMap<const BasicBlock *, BBState> &BBStates,
2371 BBState &MyStates) const {
2372 // If any top-down local-use or possible-dec has a succ which is earlier in
2373 // the sequence, forget it.
2374 for (BBState::ptr_const_iterator I = MyStates.top_down_ptr_begin(),
2375 E = MyStates.top_down_ptr_end(); I != E; ++I)
2376 switch (I->second.GetSeq()) {
2379 const Value *Arg = I->first;
2380 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2381 bool SomeSuccHasSame = false;
2382 bool AllSuccsHaveSame = true;
2383 PtrState &S = MyStates.getPtrTopDownState(Arg);
2384 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2385 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2386 switch (SuccS.GetSeq()) {
2388 case S_CanRelease: {
2389 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2390 S.ClearSequenceProgress();
2394 SomeSuccHasSame = true;
2398 case S_MovableRelease:
2399 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2400 AllSuccsHaveSame = false;
2403 llvm_unreachable("bottom-up pointer in retain state!");
2406 // If the state at the other end of any of the successor edges
2407 // matches the current state, require all edges to match. This
2408 // guards against loops in the middle of a sequence.
2409 if (SomeSuccHasSame && !AllSuccsHaveSame)
2410 S.ClearSequenceProgress();
2413 case S_CanRelease: {
2414 const Value *Arg = I->first;
2415 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2416 bool SomeSuccHasSame = false;
2417 bool AllSuccsHaveSame = true;
2418 PtrState &S = MyStates.getPtrTopDownState(Arg);
2419 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2420 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2421 switch (SuccS.GetSeq()) {
2423 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2424 S.ClearSequenceProgress();
2428 SomeSuccHasSame = true;
2432 case S_MovableRelease:
2434 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2435 AllSuccsHaveSame = false;
2438 llvm_unreachable("bottom-up pointer in retain state!");
2441 // If the state at the other end of any of the successor edges
2442 // matches the current state, require all edges to match. This
2443 // guards against loops in the middle of a sequence.
2444 if (SomeSuccHasSame && !AllSuccsHaveSame)
2445 S.ClearSequenceProgress();
2452 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2453 DenseMap<const BasicBlock *, BBState> &BBStates,
2454 MapVector<Value *, RRInfo> &Retains) {
2455 bool NestingDetected = false;
2456 BBState &MyStates = BBStates[BB];
2458 // Merge the states from each successor to compute the initial state
2459 // for the current block.
2460 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2461 succ_const_iterator SI(TI), SE(TI, false);
2463 MyStates.SetAsExit();
2466 const BasicBlock *Succ = *SI++;
2469 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2470 // If we haven't seen this node yet, then we've found a CFG cycle.
2471 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2472 if (I == BBStates.end())
2474 MyStates.InitFromSucc(I->second);
2478 I = BBStates.find(Succ);
2479 if (I != BBStates.end())
2480 MyStates.MergeSucc(I->second);
2486 // Visit all the instructions, bottom-up.
2487 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2488 Instruction *Inst = llvm::prior(I);
2489 InstructionClass Class = GetInstructionClass(Inst);
2490 const Value *Arg = 0;
2494 Arg = GetObjCArg(Inst);
2496 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2498 // If we see two releases in a row on the same pointer. If so, make
2499 // a note, and we'll cicle back to revisit it after we've
2500 // hopefully eliminated the second release, which may allow us to
2501 // eliminate the first release too.
2502 // Theoretically we could implement removal of nested retain+release
2503 // pairs by making PtrState hold a stack of states, but this is
2504 // simple and avoids adding overhead for the non-nested case.
2505 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2506 NestingDetected = true;
2510 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2511 S.SetSeq(ReleaseMetadata ? S_MovableRelease : S_Release);
2512 S.RRI.ReleaseMetadata = ReleaseMetadata;
2513 S.RRI.KnownSafe = S.IsKnownNested() || S.IsKnownIncremented();
2514 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2515 S.RRI.Calls.insert(Inst);
2517 S.IncrementRefCount();
2518 S.IncrementNestCount();
2521 case IC_RetainBlock:
2522 // An objc_retainBlock call with just a use may need to be kept,
2523 // because it may be copying a block from the stack to the heap.
2524 if (!IsRetainBlockOptimizable(Inst))
2529 Arg = GetObjCArg(Inst);
2531 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2532 S.DecrementRefCount();
2533 S.SetAtLeastOneRefCount();
2534 S.DecrementNestCount();
2536 switch (S.GetSeq()) {
2539 case S_MovableRelease:
2541 S.RRI.ReverseInsertPts.clear();
2544 // Don't do retain+release tracking for IC_RetainRV, because it's
2545 // better to let it remain as the first instruction after a call.
2546 if (Class != IC_RetainRV) {
2547 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2548 Retains[Inst] = S.RRI;
2550 S.ClearSequenceProgress();
2555 llvm_unreachable("bottom-up pointer in retain state!");
2559 case IC_AutoreleasepoolPop:
2560 // Conservatively, clear MyStates for all known pointers.
2561 MyStates.clearBottomUpPointers();
2563 case IC_AutoreleasepoolPush:
2565 // These are irrelevant.
2571 // Consider any other possible effects of this instruction on each
2572 // pointer being tracked.
2573 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2574 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2575 const Value *Ptr = MI->first;
2577 continue; // Handled above.
2578 PtrState &S = MI->second;
2579 Sequence Seq = S.GetSeq();
2581 // Check for possible releases.
2582 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2583 S.DecrementRefCount();
2586 S.SetSeq(S_CanRelease);
2590 case S_MovableRelease:
2595 llvm_unreachable("bottom-up pointer in retain state!");
2599 // Check for possible direct uses.
2602 case S_MovableRelease:
2603 if (CanUse(Inst, Ptr, PA, Class)) {
2604 assert(S.RRI.ReverseInsertPts.empty());
2605 S.RRI.ReverseInsertPts.insert(Inst);
2607 } else if (Seq == S_Release &&
2608 (Class == IC_User || Class == IC_CallOrUser)) {
2609 // Non-movable releases depend on any possible objc pointer use.
2611 assert(S.RRI.ReverseInsertPts.empty());
2612 S.RRI.ReverseInsertPts.insert(Inst);
2616 if (CanUse(Inst, Ptr, PA, Class))
2624 llvm_unreachable("bottom-up pointer in retain state!");
2629 return NestingDetected;
2633 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2634 DenseMap<const BasicBlock *, BBState> &BBStates,
2635 DenseMap<Value *, RRInfo> &Releases) {
2636 bool NestingDetected = false;
2637 BBState &MyStates = BBStates[BB];
2639 // Merge the states from each predecessor to compute the initial state
2640 // for the current block.
2641 const_pred_iterator PI(BB), PE(BB, false);
2643 MyStates.SetAsEntry();
2646 const BasicBlock *Pred = *PI++;
2649 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2650 // If we haven't seen this node yet, then we've found a CFG cycle.
2651 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2652 if (I == BBStates.end() || !I->second.isVisitedTopDown())
2654 MyStates.InitFromPred(I->second);
2658 I = BBStates.find(Pred);
2659 if (I != BBStates.end() && I->second.isVisitedTopDown())
2660 MyStates.MergePred(I->second);
2666 // Visit all the instructions, top-down.
2667 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2668 Instruction *Inst = I;
2669 InstructionClass Class = GetInstructionClass(Inst);
2670 const Value *Arg = 0;
2673 case IC_RetainBlock:
2674 // An objc_retainBlock call with just a use may need to be kept,
2675 // because it may be copying a block from the stack to the heap.
2676 if (!IsRetainBlockOptimizable(Inst))
2681 Arg = GetObjCArg(Inst);
2683 PtrState &S = MyStates.getPtrTopDownState(Arg);
2685 // Don't do retain+release tracking for IC_RetainRV, because it's
2686 // better to let it remain as the first instruction after a call.
2687 if (Class != IC_RetainRV) {
2688 // If we see two retains in a row on the same pointer. If so, make
2689 // a note, and we'll cicle back to revisit it after we've
2690 // hopefully eliminated the second retain, which may allow us to
2691 // eliminate the first retain too.
2692 // Theoretically we could implement removal of nested retain+release
2693 // pairs by making PtrState hold a stack of states, but this is
2694 // simple and avoids adding overhead for the non-nested case.
2695 if (S.GetSeq() == S_Retain)
2696 NestingDetected = true;
2700 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2701 // Don't check S.IsKnownIncremented() here because it's not
2703 S.RRI.KnownSafe = S.IsKnownNested();
2704 S.RRI.Calls.insert(Inst);
2707 S.SetAtLeastOneRefCount();
2708 S.IncrementRefCount();
2709 S.IncrementNestCount();
2713 Arg = GetObjCArg(Inst);
2715 PtrState &S = MyStates.getPtrTopDownState(Arg);
2716 S.DecrementRefCount();
2717 S.DecrementNestCount();
2719 switch (S.GetSeq()) {
2722 S.RRI.ReverseInsertPts.clear();
2725 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2726 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2727 Releases[Inst] = S.RRI;
2728 S.ClearSequenceProgress();
2734 case S_MovableRelease:
2735 llvm_unreachable("top-down pointer in release state!");
2739 case IC_AutoreleasepoolPop:
2740 // Conservatively, clear MyStates for all known pointers.
2741 MyStates.clearTopDownPointers();
2743 case IC_AutoreleasepoolPush:
2745 // These are irrelevant.
2751 // Consider any other possible effects of this instruction on each
2752 // pointer being tracked.
2753 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2754 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2755 const Value *Ptr = MI->first;
2757 continue; // Handled above.
2758 PtrState &S = MI->second;
2759 Sequence Seq = S.GetSeq();
2761 // Check for possible releases.
2762 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2763 S.DecrementRefCount();
2766 S.SetSeq(S_CanRelease);
2767 assert(S.RRI.ReverseInsertPts.empty());
2768 S.RRI.ReverseInsertPts.insert(Inst);
2770 // One call can't cause a transition from S_Retain to S_CanRelease
2771 // and S_CanRelease to S_Use. If we've made the first transition,
2780 case S_MovableRelease:
2781 llvm_unreachable("top-down pointer in release state!");
2785 // Check for possible direct uses.
2788 if (CanUse(Inst, Ptr, PA, Class))
2797 case S_MovableRelease:
2798 llvm_unreachable("top-down pointer in release state!");
2803 CheckForCFGHazards(BB, BBStates, MyStates);
2804 return NestingDetected;
2808 ComputePostOrders(Function &F,
2809 SmallVectorImpl<BasicBlock *> &PostOrder,
2810 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder) {
2811 /// Backedges - Backedges detected in the DFS. These edges will be
2812 /// ignored in the reverse-CFG DFS, so that loops with multiple exits will be
2813 /// traversed in the desired order.
2814 DenseSet<std::pair<BasicBlock *, BasicBlock *> > Backedges;
2816 /// Visited - The visited set, for doing DFS walks.
2817 SmallPtrSet<BasicBlock *, 16> Visited;
2819 // Do DFS, computing the PostOrder.
2820 SmallPtrSet<BasicBlock *, 16> OnStack;
2821 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2822 BasicBlock *EntryBB = &F.getEntryBlock();
2823 SuccStack.push_back(std::make_pair(EntryBB, succ_begin(EntryBB)));
2824 Visited.insert(EntryBB);
2825 OnStack.insert(EntryBB);
2828 succ_iterator End = succ_end(SuccStack.back().first);
2829 while (SuccStack.back().second != End) {
2830 BasicBlock *BB = *SuccStack.back().second++;
2831 if (Visited.insert(BB)) {
2832 SuccStack.push_back(std::make_pair(BB, succ_begin(BB)));
2836 if (OnStack.count(BB))
2837 Backedges.insert(std::make_pair(SuccStack.back().first, BB));
2839 OnStack.erase(SuccStack.back().first);
2840 PostOrder.push_back(SuccStack.pop_back_val().first);
2841 } while (!SuccStack.empty());
2845 // Compute the exits, which are the starting points for reverse-CFG DFS.
2846 SmallVector<BasicBlock *, 4> Exits;
2847 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2849 if (BB->getTerminator()->getNumSuccessors() == 0)
2850 Exits.push_back(BB);
2853 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2854 SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> PredStack;
2855 for (SmallVectorImpl<BasicBlock *>::iterator I = Exits.begin(), E = Exits.end();
2857 BasicBlock *ExitBB = *I;
2858 PredStack.push_back(std::make_pair(ExitBB, pred_begin(ExitBB)));
2859 Visited.insert(ExitBB);
2860 while (!PredStack.empty()) {
2861 reverse_dfs_next_succ:
2862 pred_iterator End = pred_end(PredStack.back().first);
2863 while (PredStack.back().second != End) {
2864 BasicBlock *BB = *PredStack.back().second++;
2865 // Skip backedges detected in the forward-CFG DFS.
2866 if (Backedges.count(std::make_pair(BB, PredStack.back().first)))
2868 if (Visited.insert(BB)) {
2869 PredStack.push_back(std::make_pair(BB, pred_begin(BB)));
2870 goto reverse_dfs_next_succ;
2873 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2878 // Visit - Visit the function both top-down and bottom-up.
2880 ObjCARCOpt::Visit(Function &F,
2881 DenseMap<const BasicBlock *, BBState> &BBStates,
2882 MapVector<Value *, RRInfo> &Retains,
2883 DenseMap<Value *, RRInfo> &Releases) {
2885 // Use reverse-postorder traversals, because we magically know that loops
2886 // will be well behaved, i.e. they won't repeatedly call retain on a single
2887 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2888 // class here because we want the reverse-CFG postorder to consider each
2889 // function exit point, and we want to ignore selected cycle edges.
2890 SmallVector<BasicBlock *, 16> PostOrder;
2891 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2892 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder);
2894 // Use reverse-postorder on the reverse CFG for bottom-up.
2895 bool BottomUpNestingDetected = false;
2896 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2897 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2899 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
2901 // Use reverse-postorder for top-down.
2902 bool TopDownNestingDetected = false;
2903 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2904 PostOrder.rbegin(), E = PostOrder.rend();
2906 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
2908 return TopDownNestingDetected && BottomUpNestingDetected;
2911 /// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
2912 void ObjCARCOpt::MoveCalls(Value *Arg,
2913 RRInfo &RetainsToMove,
2914 RRInfo &ReleasesToMove,
2915 MapVector<Value *, RRInfo> &Retains,
2916 DenseMap<Value *, RRInfo> &Releases,
2917 SmallVectorImpl<Instruction *> &DeadInsts,
2919 Type *ArgTy = Arg->getType();
2920 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2922 // Insert the new retain and release calls.
2923 for (SmallPtrSet<Instruction *, 2>::const_iterator
2924 PI = ReleasesToMove.ReverseInsertPts.begin(),
2925 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2926 Instruction *InsertPt = *PI;
2927 Value *MyArg = ArgTy == ParamTy ? Arg :
2928 new BitCastInst(Arg, ParamTy, "", InsertPt);
2930 CallInst::Create(RetainsToMove.IsRetainBlock ?
2931 getRetainBlockCallee(M) : getRetainCallee(M),
2932 MyArg, "", InsertPt);
2933 Call->setDoesNotThrow();
2934 if (RetainsToMove.IsRetainBlock)
2935 Call->setMetadata(CopyOnEscapeMDKind,
2936 MDNode::get(M->getContext(), ArrayRef<Value *>()));
2938 Call->setTailCall();
2940 for (SmallPtrSet<Instruction *, 2>::const_iterator
2941 PI = RetainsToMove.ReverseInsertPts.begin(),
2942 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2943 Instruction *LastUse = *PI;
2944 Instruction *InsertPts[] = { 0, 0, 0 };
2945 if (InvokeInst *II = dyn_cast<InvokeInst>(LastUse)) {
2946 // We can't insert code immediately after an invoke instruction, so
2947 // insert code at the beginning of both successor blocks instead.
2948 // The invoke's return value isn't available in the unwind block,
2949 // but our releases will never depend on it, because they must be
2950 // paired with retains from before the invoke.
2951 InsertPts[0] = II->getNormalDest()->getFirstInsertionPt();
2952 InsertPts[1] = II->getUnwindDest()->getFirstInsertionPt();
2954 // Insert code immediately after the last use.
2955 InsertPts[0] = llvm::next(BasicBlock::iterator(LastUse));
2958 for (Instruction **I = InsertPts; *I; ++I) {
2959 Instruction *InsertPt = *I;
2960 Value *MyArg = ArgTy == ParamTy ? Arg :
2961 new BitCastInst(Arg, ParamTy, "", InsertPt);
2962 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2964 // Attach a clang.imprecise_release metadata tag, if appropriate.
2965 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2966 Call->setMetadata(ImpreciseReleaseMDKind, M);
2967 Call->setDoesNotThrow();
2968 if (ReleasesToMove.IsTailCallRelease)
2969 Call->setTailCall();
2973 // Delete the original retain and release calls.
2974 for (SmallPtrSet<Instruction *, 2>::const_iterator
2975 AI = RetainsToMove.Calls.begin(),
2976 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2977 Instruction *OrigRetain = *AI;
2978 Retains.blot(OrigRetain);
2979 DeadInsts.push_back(OrigRetain);
2981 for (SmallPtrSet<Instruction *, 2>::const_iterator
2982 AI = ReleasesToMove.Calls.begin(),
2983 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2984 Instruction *OrigRelease = *AI;
2985 Releases.erase(OrigRelease);
2986 DeadInsts.push_back(OrigRelease);
2991 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2993 MapVector<Value *, RRInfo> &Retains,
2994 DenseMap<Value *, RRInfo> &Releases,
2996 bool AnyPairsCompletelyEliminated = false;
2997 RRInfo RetainsToMove;
2998 RRInfo ReleasesToMove;
2999 SmallVector<Instruction *, 4> NewRetains;
3000 SmallVector<Instruction *, 4> NewReleases;
3001 SmallVector<Instruction *, 8> DeadInsts;
3003 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
3004 E = Retains.end(); I != E; ++I) {
3005 Value *V = I->first;
3006 if (!V) continue; // blotted
3008 Instruction *Retain = cast<Instruction>(V);
3009 Value *Arg = GetObjCArg(Retain);
3011 // If the object being released is in static or stack storage, we know it's
3012 // not being managed by ObjC reference counting, so we can delete pairs
3013 // regardless of what possible decrements or uses lie between them.
3014 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
3016 // A constant pointer can't be pointing to an object on the heap. It may
3017 // be reference-counted, but it won't be deleted.
3018 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3019 if (const GlobalVariable *GV =
3020 dyn_cast<GlobalVariable>(
3021 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3022 if (GV->isConstant())
3025 // If a pair happens in a region where it is known that the reference count
3026 // is already incremented, we can similarly ignore possible decrements.
3027 bool KnownSafeTD = true, KnownSafeBU = true;
3029 // Connect the dots between the top-down-collected RetainsToMove and
3030 // bottom-up-collected ReleasesToMove to form sets of related calls.
3031 // This is an iterative process so that we connect multiple releases
3032 // to multiple retains if needed.
3033 unsigned OldDelta = 0;
3034 unsigned NewDelta = 0;
3035 unsigned OldCount = 0;
3036 unsigned NewCount = 0;
3037 bool FirstRelease = true;
3038 bool FirstRetain = true;
3039 NewRetains.push_back(Retain);
3041 for (SmallVectorImpl<Instruction *>::const_iterator
3042 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3043 Instruction *NewRetain = *NI;
3044 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3045 assert(It != Retains.end());
3046 const RRInfo &NewRetainRRI = It->second;
3047 KnownSafeTD &= NewRetainRRI.KnownSafe;
3048 for (SmallPtrSet<Instruction *, 2>::const_iterator
3049 LI = NewRetainRRI.Calls.begin(),
3050 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3051 Instruction *NewRetainRelease = *LI;
3052 DenseMap<Value *, RRInfo>::const_iterator Jt =
3053 Releases.find(NewRetainRelease);
3054 if (Jt == Releases.end())
3056 const RRInfo &NewRetainReleaseRRI = Jt->second;
3057 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3058 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3060 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3062 // Merge the ReleaseMetadata and IsTailCallRelease values.
3064 ReleasesToMove.ReleaseMetadata =
3065 NewRetainReleaseRRI.ReleaseMetadata;
3066 ReleasesToMove.IsTailCallRelease =
3067 NewRetainReleaseRRI.IsTailCallRelease;
3068 FirstRelease = false;
3070 if (ReleasesToMove.ReleaseMetadata !=
3071 NewRetainReleaseRRI.ReleaseMetadata)
3072 ReleasesToMove.ReleaseMetadata = 0;
3073 if (ReleasesToMove.IsTailCallRelease !=
3074 NewRetainReleaseRRI.IsTailCallRelease)
3075 ReleasesToMove.IsTailCallRelease = false;
3078 // Collect the optimal insertion points.
3080 for (SmallPtrSet<Instruction *, 2>::const_iterator
3081 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3082 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3084 Instruction *RIP = *RI;
3085 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3086 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3088 NewReleases.push_back(NewRetainRelease);
3093 if (NewReleases.empty()) break;
3095 // Back the other way.
3096 for (SmallVectorImpl<Instruction *>::const_iterator
3097 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3098 Instruction *NewRelease = *NI;
3099 DenseMap<Value *, RRInfo>::const_iterator It =
3100 Releases.find(NewRelease);
3101 assert(It != Releases.end());
3102 const RRInfo &NewReleaseRRI = It->second;
3103 KnownSafeBU &= NewReleaseRRI.KnownSafe;
3104 for (SmallPtrSet<Instruction *, 2>::const_iterator
3105 LI = NewReleaseRRI.Calls.begin(),
3106 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3107 Instruction *NewReleaseRetain = *LI;
3108 MapVector<Value *, RRInfo>::const_iterator Jt =
3109 Retains.find(NewReleaseRetain);
3110 if (Jt == Retains.end())
3112 const RRInfo &NewReleaseRetainRRI = Jt->second;
3113 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3114 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3115 unsigned PathCount =
3116 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3117 OldDelta += PathCount;
3118 OldCount += PathCount;
3120 // Merge the IsRetainBlock values.
3122 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3123 FirstRetain = false;
3124 } else if (ReleasesToMove.IsRetainBlock !=
3125 NewReleaseRetainRRI.IsRetainBlock)
3126 // It's not possible to merge the sequences if one uses
3127 // objc_retain and the other uses objc_retainBlock.
3130 // Collect the optimal insertion points.
3132 for (SmallPtrSet<Instruction *, 2>::const_iterator
3133 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3134 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3136 Instruction *RIP = *RI;
3137 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3138 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3139 NewDelta += PathCount;
3140 NewCount += PathCount;
3143 NewRetains.push_back(NewReleaseRetain);
3147 NewReleases.clear();
3148 if (NewRetains.empty()) break;
3151 // If the pointer is known incremented or nested, we can safely delete the
3152 // pair regardless of what's between them.
3153 if (KnownSafeTD || KnownSafeBU) {
3154 RetainsToMove.ReverseInsertPts.clear();
3155 ReleasesToMove.ReverseInsertPts.clear();
3158 // Determine whether the new insertion points we computed preserve the
3159 // balance of retain and release calls through the program.
3160 // TODO: If the fully aggressive solution isn't valid, try to find a
3161 // less aggressive solution which is.
3166 // Determine whether the original call points are balanced in the retain and
3167 // release calls through the program. If not, conservatively don't touch
3169 // TODO: It's theoretically possible to do code motion in this case, as
3170 // long as the existing imbalances are maintained.
3174 // Ok, everything checks out and we're all set. Let's move some code!
3176 AnyPairsCompletelyEliminated = NewCount == 0;
3177 NumRRs += OldCount - NewCount;
3178 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3179 Retains, Releases, DeadInsts, M);
3182 NewReleases.clear();
3184 RetainsToMove.clear();
3185 ReleasesToMove.clear();
3188 // Now that we're done moving everything, we can delete the newly dead
3189 // instructions, as we no longer need them as insert points.
3190 while (!DeadInsts.empty())
3191 EraseInstruction(DeadInsts.pop_back_val());
3193 return AnyPairsCompletelyEliminated;
3196 /// OptimizeWeakCalls - Weak pointer optimizations.
3197 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3198 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3199 // itself because it uses AliasAnalysis and we need to do provenance
3201 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3202 Instruction *Inst = &*I++;
3203 InstructionClass Class = GetBasicInstructionClass(Inst);
3204 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3207 // Delete objc_loadWeak calls with no users.
3208 if (Class == IC_LoadWeak && Inst->use_empty()) {
3209 Inst->eraseFromParent();
3213 // TODO: For now, just look for an earlier available version of this value
3214 // within the same block. Theoretically, we could do memdep-style non-local
3215 // analysis too, but that would want caching. A better approach would be to
3216 // use the technique that EarlyCSE uses.
3217 inst_iterator Current = llvm::prior(I);
3218 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3219 for (BasicBlock::iterator B = CurrentBB->begin(),
3220 J = Current.getInstructionIterator();
3222 Instruction *EarlierInst = &*llvm::prior(J);
3223 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3224 switch (EarlierClass) {
3226 case IC_LoadWeakRetained: {
3227 // If this is loading from the same pointer, replace this load's value
3229 CallInst *Call = cast<CallInst>(Inst);
3230 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3231 Value *Arg = Call->getArgOperand(0);
3232 Value *EarlierArg = EarlierCall->getArgOperand(0);
3233 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3234 case AliasAnalysis::MustAlias:
3236 // If the load has a builtin retain, insert a plain retain for it.
3237 if (Class == IC_LoadWeakRetained) {
3239 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3243 // Zap the fully redundant load.
3244 Call->replaceAllUsesWith(EarlierCall);
3245 Call->eraseFromParent();
3247 case AliasAnalysis::MayAlias:
3248 case AliasAnalysis::PartialAlias:
3250 case AliasAnalysis::NoAlias:
3257 // If this is storing to the same pointer and has the same size etc.
3258 // replace this load's value with the stored value.
3259 CallInst *Call = cast<CallInst>(Inst);
3260 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3261 Value *Arg = Call->getArgOperand(0);
3262 Value *EarlierArg = EarlierCall->getArgOperand(0);
3263 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3264 case AliasAnalysis::MustAlias:
3266 // If the load has a builtin retain, insert a plain retain for it.
3267 if (Class == IC_LoadWeakRetained) {
3269 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3273 // Zap the fully redundant load.
3274 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3275 Call->eraseFromParent();
3277 case AliasAnalysis::MayAlias:
3278 case AliasAnalysis::PartialAlias:
3280 case AliasAnalysis::NoAlias:
3287 // TOOD: Grab the copied value.
3289 case IC_AutoreleasepoolPush:
3292 // Weak pointers are only modified through the weak entry points
3293 // (and arbitrary calls, which could call the weak entry points).
3296 // Anything else could modify the weak pointer.
3303 // Then, for each destroyWeak with an alloca operand, check to see if
3304 // the alloca and all its users can be zapped.
3305 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3306 Instruction *Inst = &*I++;
3307 InstructionClass Class = GetBasicInstructionClass(Inst);
3308 if (Class != IC_DestroyWeak)
3311 CallInst *Call = cast<CallInst>(Inst);
3312 Value *Arg = Call->getArgOperand(0);
3313 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3314 for (Value::use_iterator UI = Alloca->use_begin(),
3315 UE = Alloca->use_end(); UI != UE; ++UI) {
3316 Instruction *UserInst = cast<Instruction>(*UI);
3317 switch (GetBasicInstructionClass(UserInst)) {
3320 case IC_DestroyWeak:
3327 for (Value::use_iterator UI = Alloca->use_begin(),
3328 UE = Alloca->use_end(); UI != UE; ) {
3329 CallInst *UserInst = cast<CallInst>(*UI++);
3330 if (!UserInst->use_empty())
3331 UserInst->replaceAllUsesWith(UserInst->getArgOperand(0));
3332 UserInst->eraseFromParent();
3334 Alloca->eraseFromParent();
3340 /// OptimizeSequences - Identify program paths which execute sequences of
3341 /// retains and releases which can be eliminated.
3342 bool ObjCARCOpt::OptimizeSequences(Function &F) {
3343 /// Releases, Retains - These are used to store the results of the main flow
3344 /// analysis. These use Value* as the key instead of Instruction* so that the
3345 /// map stays valid when we get around to rewriting code and calls get
3346 /// replaced by arguments.
3347 DenseMap<Value *, RRInfo> Releases;
3348 MapVector<Value *, RRInfo> Retains;
3350 /// BBStates, This is used during the traversal of the function to track the
3351 /// states for each identified object at each block.
3352 DenseMap<const BasicBlock *, BBState> BBStates;
3354 // Analyze the CFG of the function, and all instructions.
3355 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3358 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3362 /// OptimizeReturns - Look for this pattern:
3364 /// %call = call i8* @something(...)
3365 /// %2 = call i8* @objc_retain(i8* %call)
3366 /// %3 = call i8* @objc_autorelease(i8* %2)
3369 /// And delete the retain and autorelease.
3371 /// Otherwise if it's just this:
3373 /// %3 = call i8* @objc_autorelease(i8* %2)
3376 /// convert the autorelease to autoreleaseRV.
3377 void ObjCARCOpt::OptimizeReturns(Function &F) {
3378 if (!F.getReturnType()->isPointerTy())
3381 SmallPtrSet<Instruction *, 4> DependingInstructions;
3382 SmallPtrSet<const BasicBlock *, 4> Visited;
3383 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3384 BasicBlock *BB = FI;
3385 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3388 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3389 FindDependencies(NeedsPositiveRetainCount, Arg,
3390 BB, Ret, DependingInstructions, Visited, PA);
3391 if (DependingInstructions.size() != 1)
3395 CallInst *Autorelease =
3396 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3399 InstructionClass AutoreleaseClass =
3400 GetBasicInstructionClass(Autorelease);
3401 if (!IsAutorelease(AutoreleaseClass))
3403 if (GetObjCArg(Autorelease) != Arg)
3406 DependingInstructions.clear();
3409 // Check that there is nothing that can affect the reference
3410 // count between the autorelease and the retain.
3411 FindDependencies(CanChangeRetainCount, Arg,
3412 BB, Autorelease, DependingInstructions, Visited, PA);
3413 if (DependingInstructions.size() != 1)
3418 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3420 // Check that we found a retain with the same argument.
3422 !IsRetain(GetBasicInstructionClass(Retain)) ||
3423 GetObjCArg(Retain) != Arg)
3426 DependingInstructions.clear();
3429 // Convert the autorelease to an autoreleaseRV, since it's
3430 // returning the value.
3431 if (AutoreleaseClass == IC_Autorelease) {
3432 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3433 AutoreleaseClass = IC_AutoreleaseRV;
3436 // Check that there is nothing that can affect the reference
3437 // count between the retain and the call.
3438 // Note that Retain need not be in BB.
3439 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3440 DependingInstructions, Visited, PA);
3441 if (DependingInstructions.size() != 1)
3446 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3448 // Check that the pointer is the return value of the call.
3449 if (!Call || Arg != Call)
3452 // Check that the call is a regular call.
3453 InstructionClass Class = GetBasicInstructionClass(Call);
3454 if (Class != IC_CallOrUser && Class != IC_Call)
3457 // If so, we can zap the retain and autorelease.
3460 EraseInstruction(Retain);
3461 EraseInstruction(Autorelease);
3467 DependingInstructions.clear();
3472 bool ObjCARCOpt::doInitialization(Module &M) {
3476 Run = ModuleHasARC(M);
3480 // Identify the imprecise release metadata kind.
3481 ImpreciseReleaseMDKind =
3482 M.getContext().getMDKindID("clang.imprecise_release");
3483 CopyOnEscapeMDKind =
3484 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3486 // Intuitively, objc_retain and others are nocapture, however in practice
3487 // they are not, because they return their argument value. And objc_release
3488 // calls finalizers.
3490 // These are initialized lazily.
3492 AutoreleaseRVCallee = 0;
3495 RetainBlockCallee = 0;
3496 AutoreleaseCallee = 0;
3501 bool ObjCARCOpt::runOnFunction(Function &F) {
3505 // If nothing in the Module uses ARC, don't do anything.
3511 PA.setAA(&getAnalysis<AliasAnalysis>());
3513 // This pass performs several distinct transformations. As a compile-time aid
3514 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3515 // library functions aren't declared.
3517 // Preliminary optimizations. This also computs UsedInThisFunction.
3518 OptimizeIndividualCalls(F);
3520 // Optimizations for weak pointers.
3521 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3522 (1 << IC_LoadWeakRetained) |
3523 (1 << IC_StoreWeak) |
3524 (1 << IC_InitWeak) |
3525 (1 << IC_CopyWeak) |
3526 (1 << IC_MoveWeak) |
3527 (1 << IC_DestroyWeak)))
3528 OptimizeWeakCalls(F);
3530 // Optimizations for retain+release pairs.
3531 if (UsedInThisFunction & ((1 << IC_Retain) |
3532 (1 << IC_RetainRV) |
3533 (1 << IC_RetainBlock)))
3534 if (UsedInThisFunction & (1 << IC_Release))
3535 // Run OptimizeSequences until it either stops making changes or
3536 // no retain+release pair nesting is detected.
3537 while (OptimizeSequences(F)) {}
3539 // Optimizations if objc_autorelease is used.
3540 if (UsedInThisFunction &
3541 ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
3547 void ObjCARCOpt::releaseMemory() {
3551 //===----------------------------------------------------------------------===//
3553 //===----------------------------------------------------------------------===//
3555 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
3556 // dominated by single calls.
3558 #include "llvm/Operator.h"
3559 #include "llvm/InlineAsm.h"
3560 #include "llvm/Analysis/Dominators.h"
3562 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3565 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3566 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3567 class ObjCARCContract : public FunctionPass {
3571 ProvenanceAnalysis PA;
3573 /// Run - A flag indicating whether this optimization pass should run.
3576 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3577 /// functions, for use in creating calls to them. These are initialized
3578 /// lazily to avoid cluttering up the Module with unused declarations.
3579 Constant *StoreStrongCallee,
3580 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3582 /// RetainRVMarker - The inline asm string to insert between calls and
3583 /// RetainRV calls to make the optimization work on targets which need it.
3584 const MDString *RetainRVMarker;
3586 Constant *getStoreStrongCallee(Module *M);
3587 Constant *getRetainAutoreleaseCallee(Module *M);
3588 Constant *getRetainAutoreleaseRVCallee(Module *M);
3590 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3591 InstructionClass Class,
3592 SmallPtrSet<Instruction *, 4>
3593 &DependingInstructions,
3594 SmallPtrSet<const BasicBlock *, 4>
3597 void ContractRelease(Instruction *Release,
3598 inst_iterator &Iter);
3600 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3601 virtual bool doInitialization(Module &M);
3602 virtual bool runOnFunction(Function &F);
3606 ObjCARCContract() : FunctionPass(ID) {
3607 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3612 char ObjCARCContract::ID = 0;
3613 INITIALIZE_PASS_BEGIN(ObjCARCContract,
3614 "objc-arc-contract", "ObjC ARC contraction", false, false)
3615 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3616 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3617 INITIALIZE_PASS_END(ObjCARCContract,
3618 "objc-arc-contract", "ObjC ARC contraction", false, false)
3620 Pass *llvm::createObjCARCContractPass() {
3621 return new ObjCARCContract();
3624 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3625 AU.addRequired<AliasAnalysis>();
3626 AU.addRequired<DominatorTree>();
3627 AU.setPreservesCFG();
3630 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3631 if (!StoreStrongCallee) {
3632 LLVMContext &C = M->getContext();
3633 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3634 Type *I8XX = PointerType::getUnqual(I8X);
3635 std::vector<Type *> Params;
3636 Params.push_back(I8XX);
3637 Params.push_back(I8X);
3639 AttrListPtr Attributes;
3640 Attributes.addAttr(~0u, Attribute::NoUnwind);
3641 Attributes.addAttr(1, Attribute::NoCapture);
3644 M->getOrInsertFunction(
3646 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3649 return StoreStrongCallee;
3652 Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3653 if (!RetainAutoreleaseCallee) {
3654 LLVMContext &C = M->getContext();
3655 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3656 std::vector<Type *> Params;
3657 Params.push_back(I8X);
3659 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3660 AttrListPtr Attributes;
3661 Attributes.addAttr(~0u, Attribute::NoUnwind);
3662 RetainAutoreleaseCallee =
3663 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3665 return RetainAutoreleaseCallee;
3668 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3669 if (!RetainAutoreleaseRVCallee) {
3670 LLVMContext &C = M->getContext();
3671 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3672 std::vector<Type *> Params;
3673 Params.push_back(I8X);
3675 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3676 AttrListPtr Attributes;
3677 Attributes.addAttr(~0u, Attribute::NoUnwind);
3678 RetainAutoreleaseRVCallee =
3679 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3682 return RetainAutoreleaseRVCallee;
3685 /// ContractAutorelease - Merge an autorelease with a retain into a fused
3688 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3689 InstructionClass Class,
3690 SmallPtrSet<Instruction *, 4>
3691 &DependingInstructions,
3692 SmallPtrSet<const BasicBlock *, 4>
3694 const Value *Arg = GetObjCArg(Autorelease);
3696 // Check that there are no instructions between the retain and the autorelease
3697 // (such as an autorelease_pop) which may change the count.
3698 CallInst *Retain = 0;
3699 if (Class == IC_AutoreleaseRV)
3700 FindDependencies(RetainAutoreleaseRVDep, Arg,
3701 Autorelease->getParent(), Autorelease,
3702 DependingInstructions, Visited, PA);
3704 FindDependencies(RetainAutoreleaseDep, Arg,
3705 Autorelease->getParent(), Autorelease,
3706 DependingInstructions, Visited, PA);
3709 if (DependingInstructions.size() != 1) {
3710 DependingInstructions.clear();
3714 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3715 DependingInstructions.clear();
3718 GetBasicInstructionClass(Retain) != IC_Retain ||
3719 GetObjCArg(Retain) != Arg)
3725 if (Class == IC_AutoreleaseRV)
3726 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3728 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3730 EraseInstruction(Autorelease);
3734 /// ContractRelease - Attempt to merge an objc_release with a store, load, and
3735 /// objc_retain to form an objc_storeStrong. This can be a little tricky because
3736 /// the instructions don't always appear in order, and there may be unrelated
3737 /// intervening instructions.
3738 void ObjCARCContract::ContractRelease(Instruction *Release,
3739 inst_iterator &Iter) {
3740 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
3741 if (!Load || !Load->isSimple()) return;
3743 // For now, require everything to be in one basic block.
3744 BasicBlock *BB = Release->getParent();
3745 if (Load->getParent() != BB) return;
3747 // Walk down to find the store.
3748 BasicBlock::iterator I = Load, End = BB->end();
3750 AliasAnalysis::Location Loc = AA->getLocation(Load);
3753 IsRetain(GetBasicInstructionClass(I)) ||
3754 !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
3756 StoreInst *Store = dyn_cast<StoreInst>(I);
3757 if (!Store || !Store->isSimple()) return;
3758 if (Store->getPointerOperand() != Loc.Ptr) return;
3760 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3762 // Walk up to find the retain.
3764 BasicBlock::iterator Begin = BB->begin();
3765 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3767 Instruction *Retain = I;
3768 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3769 if (GetObjCArg(Retain) != New) return;
3774 LLVMContext &C = Release->getContext();
3775 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3776 Type *I8XX = PointerType::getUnqual(I8X);
3778 Value *Args[] = { Load->getPointerOperand(), New };
3779 if (Args[0]->getType() != I8XX)
3780 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3781 if (Args[1]->getType() != I8X)
3782 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3783 CallInst *StoreStrong =
3784 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
3786 StoreStrong->setDoesNotThrow();
3787 StoreStrong->setDebugLoc(Store->getDebugLoc());
3789 if (&*Iter == Store) ++Iter;
3790 Store->eraseFromParent();
3791 Release->eraseFromParent();
3792 EraseInstruction(Retain);
3793 if (Load->use_empty())
3794 Load->eraseFromParent();
3797 bool ObjCARCContract::doInitialization(Module &M) {
3798 Run = ModuleHasARC(M);
3802 // These are initialized lazily.
3803 StoreStrongCallee = 0;
3804 RetainAutoreleaseCallee = 0;
3805 RetainAutoreleaseRVCallee = 0;
3807 // Initialize RetainRVMarker.
3809 if (NamedMDNode *NMD =
3810 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3811 if (NMD->getNumOperands() == 1) {
3812 const MDNode *N = NMD->getOperand(0);
3813 if (N->getNumOperands() == 1)
3814 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
3821 bool ObjCARCContract::runOnFunction(Function &F) {
3825 // If nothing in the Module uses ARC, don't do anything.
3830 AA = &getAnalysis<AliasAnalysis>();
3831 DT = &getAnalysis<DominatorTree>();
3833 PA.setAA(&getAnalysis<AliasAnalysis>());
3835 // For ObjC library calls which return their argument, replace uses of the
3836 // argument with uses of the call return value, if it dominates the use. This
3837 // reduces register pressure.
3838 SmallPtrSet<Instruction *, 4> DependingInstructions;
3839 SmallPtrSet<const BasicBlock *, 4> Visited;
3840 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3841 Instruction *Inst = &*I++;
3843 // Only these library routines return their argument. In particular,
3844 // objc_retainBlock does not necessarily return its argument.
3845 InstructionClass Class = GetBasicInstructionClass(Inst);
3848 case IC_FusedRetainAutorelease:
3849 case IC_FusedRetainAutoreleaseRV:
3851 case IC_Autorelease:
3852 case IC_AutoreleaseRV:
3853 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
3857 // If we're compiling for a target which needs a special inline-asm
3858 // marker to do the retainAutoreleasedReturnValue optimization,
3860 if (!RetainRVMarker)
3862 BasicBlock::iterator BBI = Inst;
3864 while (isNoopInstruction(BBI)) --BBI;
3865 if (&*BBI == GetObjCArg(Inst)) {
3867 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
3868 /*isVarArg=*/false),
3869 RetainRVMarker->getString(),
3870 /*Constraints=*/"", /*hasSideEffects=*/true);
3871 CallInst::Create(IA, "", Inst);
3876 // objc_initWeak(p, null) => *p = null
3877 CallInst *CI = cast<CallInst>(Inst);
3878 if (isNullOrUndef(CI->getArgOperand(1))) {
3880 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
3882 new StoreInst(Null, CI->getArgOperand(0), CI);
3883 CI->replaceAllUsesWith(Null);
3884 CI->eraseFromParent();
3889 ContractRelease(Inst, I);
3895 // Don't use GetObjCArg because we don't want to look through bitcasts
3896 // and such; to do the replacement, the argument must have type i8*.
3897 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
3899 // If we're compiling bugpointed code, don't get in trouble.
3900 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
3902 // Look through the uses of the pointer.
3903 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
3905 Use &U = UI.getUse();
3906 unsigned OperandNo = UI.getOperandNo();
3907 ++UI; // Increment UI now, because we may unlink its element.
3908 if (Instruction *UserInst = dyn_cast<Instruction>(U.getUser()))
3909 if (Inst != UserInst && DT->dominates(Inst, UserInst)) {
3911 Instruction *Replacement = Inst;
3912 Type *UseTy = U.get()->getType();
3913 if (PHINode *PHI = dyn_cast<PHINode>(UserInst)) {
3914 // For PHI nodes, insert the bitcast in the predecessor block.
3916 PHINode::getIncomingValueNumForOperand(OperandNo);
3918 PHI->getIncomingBlock(ValNo);
3919 if (Replacement->getType() != UseTy)
3920 Replacement = new BitCastInst(Replacement, UseTy, "",
3922 for (unsigned i = 0, e = PHI->getNumIncomingValues();
3924 if (PHI->getIncomingBlock(i) == BB) {
3925 // Keep the UI iterator valid.
3926 if (&PHI->getOperandUse(
3927 PHINode::getOperandNumForIncomingValue(i)) ==
3930 PHI->setIncomingValue(i, Replacement);
3933 if (Replacement->getType() != UseTy)
3934 Replacement = new BitCastInst(Replacement, UseTy, "", UserInst);
3940 // If Arg is a no-op casted pointer, strip one level of casts and
3942 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
3943 Arg = BI->getOperand(0);
3944 else if (isa<GEPOperator>(Arg) &&
3945 cast<GEPOperator>(Arg)->hasAllZeroIndices())
3946 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
3947 else if (isa<GlobalAlias>(Arg) &&
3948 !cast<GlobalAlias>(Arg)->mayBeOverridden())
3949 Arg = cast<GlobalAlias>(Arg)->getAliasee();