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.
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 (ImmutableCallSite CS = cast<Value>(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 //===----------------------------------------------------------------------===//
888 //===----------------------------------------------------------------------===//
890 // TODO: On code like this:
893 // stuff_that_cannot_release()
894 // objc_autorelease(%x)
895 // stuff_that_cannot_release()
897 // stuff_that_cannot_release()
898 // objc_autorelease(%x)
900 // The second retain and autorelease can be deleted.
902 // TODO: It should be possible to delete
903 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
904 // pairs if nothing is actually autoreleased between them. Also, autorelease
905 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
906 // after inlining) can be turned into plain release calls.
908 // TODO: Critical-edge splitting. If the optimial insertion point is
909 // a critical edge, the current algorithm has to fail, because it doesn't
910 // know how to split edges. It should be possible to make the optimizer
911 // think in terms of edges, rather than blocks, and then split critical
914 // TODO: OptimizeSequences could generalized to be Interprocedural.
916 // TODO: Recognize that a bunch of other objc runtime calls have
917 // non-escaping arguments and non-releasing arguments, and may be
918 // non-autoreleasing.
920 // TODO: Sink autorelease calls as far as possible. Unfortunately we
921 // usually can't sink them past other calls, which would be the main
922 // case where it would be useful.
924 // TODO: The pointer returned from objc_loadWeakRetained is retained.
926 // TODO: Delete release+retain pairs (rare).
928 #include "llvm/GlobalAlias.h"
929 #include "llvm/Constants.h"
930 #include "llvm/LLVMContext.h"
931 #include "llvm/Support/ErrorHandling.h"
932 #include "llvm/Support/CFG.h"
933 #include "llvm/ADT/Statistic.h"
934 #include "llvm/ADT/SmallPtrSet.h"
935 #include "llvm/ADT/DenseSet.h"
937 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
938 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
939 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
940 STATISTIC(NumRets, "Number of return value forwarding "
941 "retain+autoreleaes eliminated");
942 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
943 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
946 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
947 /// uses many of the same techniques, except it uses special ObjC-specific
948 /// reasoning about pointer relationships.
949 class ProvenanceAnalysis {
952 typedef std::pair<const Value *, const Value *> ValuePairTy;
953 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
954 CachedResultsTy CachedResults;
956 bool relatedCheck(const Value *A, const Value *B);
957 bool relatedSelect(const SelectInst *A, const Value *B);
958 bool relatedPHI(const PHINode *A, const Value *B);
961 void operator=(const ProvenanceAnalysis &);
962 ProvenanceAnalysis(const ProvenanceAnalysis &);
965 ProvenanceAnalysis() {}
967 void setAA(AliasAnalysis *aa) { AA = aa; }
969 AliasAnalysis *getAA() const { return AA; }
971 bool related(const Value *A, const Value *B);
974 CachedResults.clear();
979 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
980 // If the values are Selects with the same condition, we can do a more precise
981 // check: just check for relations between the values on corresponding arms.
982 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
983 if (A->getCondition() == SB->getCondition()) {
984 if (related(A->getTrueValue(), SB->getTrueValue()))
986 if (related(A->getFalseValue(), SB->getFalseValue()))
991 // Check both arms of the Select node individually.
992 if (related(A->getTrueValue(), B))
994 if (related(A->getFalseValue(), B))
997 // The arms both checked out.
1001 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1002 // If the values are PHIs in the same block, we can do a more precise as well
1003 // as efficient check: just check for relations between the values on
1004 // corresponding edges.
1005 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1006 if (PNB->getParent() == A->getParent()) {
1007 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1008 if (related(A->getIncomingValue(i),
1009 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1014 // Check each unique source of the PHI node against B.
1015 SmallPtrSet<const Value *, 4> UniqueSrc;
1016 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1017 const Value *PV1 = A->getIncomingValue(i);
1018 if (UniqueSrc.insert(PV1) && related(PV1, B))
1022 // All of the arms checked out.
1026 /// isStoredObjCPointer - Test if the value of P, or any value covered by its
1027 /// provenance, is ever stored within the function (not counting callees).
1028 static bool isStoredObjCPointer(const Value *P) {
1029 SmallPtrSet<const Value *, 8> Visited;
1030 SmallVector<const Value *, 8> Worklist;
1031 Worklist.push_back(P);
1034 P = Worklist.pop_back_val();
1035 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1037 const User *Ur = *UI;
1038 if (isa<StoreInst>(Ur)) {
1039 if (UI.getOperandNo() == 0)
1040 // The pointer is stored.
1042 // The pointed is stored through.
1045 if (isa<CallInst>(Ur))
1046 // The pointer is passed as an argument, ignore this.
1048 if (isa<PtrToIntInst>(P))
1049 // Assume the worst.
1051 if (Visited.insert(Ur))
1052 Worklist.push_back(Ur);
1054 } while (!Worklist.empty());
1056 // Everything checked out.
1060 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1061 // Skip past provenance pass-throughs.
1062 A = GetUnderlyingObjCPtr(A);
1063 B = GetUnderlyingObjCPtr(B);
1069 // Ask regular AliasAnalysis, for a first approximation.
1070 switch (AA->alias(A, B)) {
1071 case AliasAnalysis::NoAlias:
1073 case AliasAnalysis::MustAlias:
1074 case AliasAnalysis::PartialAlias:
1076 case AliasAnalysis::MayAlias:
1080 bool AIsIdentified = IsObjCIdentifiedObject(A);
1081 bool BIsIdentified = IsObjCIdentifiedObject(B);
1083 // An ObjC-Identified object can't alias a load if it is never locally stored.
1084 if (AIsIdentified) {
1085 if (BIsIdentified) {
1086 // If both pointers have provenance, they can be directly compared.
1090 if (isa<LoadInst>(B))
1091 return isStoredObjCPointer(A);
1094 if (BIsIdentified && isa<LoadInst>(A))
1095 return isStoredObjCPointer(B);
1098 // Special handling for PHI and Select.
1099 if (const PHINode *PN = dyn_cast<PHINode>(A))
1100 return relatedPHI(PN, B);
1101 if (const PHINode *PN = dyn_cast<PHINode>(B))
1102 return relatedPHI(PN, A);
1103 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1104 return relatedSelect(S, B);
1105 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1106 return relatedSelect(S, A);
1112 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1113 // Begin by inserting a conservative value into the map. If the insertion
1114 // fails, we have the answer already. If it succeeds, leave it there until we
1115 // compute the real answer to guard against recursive queries.
1116 if (A > B) std::swap(A, B);
1117 std::pair<CachedResultsTy::iterator, bool> Pair =
1118 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1120 return Pair.first->second;
1122 bool Result = relatedCheck(A, B);
1123 CachedResults[ValuePairTy(A, B)] = Result;
1128 // Sequence - A sequence of states that a pointer may go through in which an
1129 // objc_retain and objc_release are actually needed.
1132 S_Retain, ///< objc_retain(x)
1133 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1134 S_Use, ///< any use of x
1135 S_Stop, ///< like S_Release, but code motion is stopped
1136 S_Release, ///< objc_release(x)
1137 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1141 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1145 if (A == S_None || B == S_None)
1148 if (A > B) std::swap(A, B);
1150 // Choose the side which is further along in the sequence.
1151 if ((A == S_Retain || A == S_CanRelease) &&
1152 (B == S_CanRelease || B == S_Use))
1155 // Choose the side which is further along in the sequence.
1156 if ((A == S_Use || A == S_CanRelease) &&
1157 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
1159 // If both sides are releases, choose the more conservative one.
1160 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1162 if (A == S_Release && B == S_MovableRelease)
1170 /// RRInfo - Unidirectional information about either a
1171 /// retain-decrement-use-release sequence or release-use-decrement-retain
1172 /// reverese sequence.
1174 /// KnownSafe - After an objc_retain, the reference count of the referenced
1175 /// object is known to be positive. Similarly, before an objc_release, the
1176 /// reference count of the referenced object is known to be positive. If
1177 /// there are retain-release pairs in code regions where the retain count
1178 /// is known to be positive, they can be eliminated, regardless of any side
1179 /// effects between them.
1181 /// Also, a retain+release pair nested within another retain+release
1182 /// pair all on the known same pointer value can be eliminated, regardless
1183 /// of any intervening side effects.
1185 /// KnownSafe is true when either of these conditions is satisfied.
1188 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1189 /// opposed to objc_retain calls).
1192 /// IsTailCallRelease - True of the objc_release calls are all marked
1193 /// with the "tail" keyword.
1194 bool IsTailCallRelease;
1196 /// Partial - True of we've seen an opportunity for partial RR elimination,
1197 /// such as pushing calls into a CFG triangle or into one side of a
1199 /// TODO: Consider moving this to PtrState.
1202 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1203 /// a clang.imprecise_release tag, this is the metadata tag.
1204 MDNode *ReleaseMetadata;
1206 /// Calls - For a top-down sequence, the set of objc_retains or
1207 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1208 SmallPtrSet<Instruction *, 2> Calls;
1210 /// ReverseInsertPts - The set of optimal insert positions for
1211 /// moving calls in the opposite sequence.
1212 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1215 KnownSafe(false), IsRetainBlock(false),
1216 IsTailCallRelease(false), Partial(false),
1217 ReleaseMetadata(0) {}
1223 void RRInfo::clear() {
1225 IsRetainBlock = false;
1226 IsTailCallRelease = false;
1228 ReleaseMetadata = 0;
1230 ReverseInsertPts.clear();
1234 /// PtrState - This class summarizes several per-pointer runtime properties
1235 /// which are propogated through the flow graph.
1237 /// RefCount - The known minimum number of reference count increments.
1240 /// NestCount - The known minimum level of retain+release nesting.
1243 /// Seq - The current position in the sequence.
1247 /// RRI - Unidirectional information about the current sequence.
1248 /// TODO: Encapsulate this better.
1251 PtrState() : RefCount(0), NestCount(0), Seq(S_None) {}
1253 void SetAtLeastOneRefCount() {
1254 if (RefCount == 0) RefCount = 1;
1257 void IncrementRefCount() {
1258 if (RefCount != UINT_MAX) ++RefCount;
1261 void DecrementRefCount() {
1262 if (RefCount != 0) --RefCount;
1265 bool IsKnownIncremented() const {
1266 return RefCount > 0;
1269 void IncrementNestCount() {
1270 if (NestCount != UINT_MAX) ++NestCount;
1273 void DecrementNestCount() {
1274 if (NestCount != 0) --NestCount;
1277 bool IsKnownNested() const {
1278 return NestCount > 0;
1281 void SetSeq(Sequence NewSeq) {
1285 Sequence GetSeq() const {
1289 void ClearSequenceProgress() {
1294 void Merge(const PtrState &Other, bool TopDown);
1299 PtrState::Merge(const PtrState &Other, bool TopDown) {
1300 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1301 RefCount = std::min(RefCount, Other.RefCount);
1302 NestCount = std::min(NestCount, Other.NestCount);
1304 // We can't merge a plain objc_retain with an objc_retainBlock.
1305 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1308 // If we're not in a sequence (anymore), drop all associated state.
1309 if (Seq == S_None) {
1311 } else if (RRI.Partial || Other.RRI.Partial) {
1312 // If we're doing a merge on a path that's previously seen a partial
1313 // merge, conservatively drop the sequence, to avoid doing partial
1314 // RR elimination. If the branch predicates for the two merge differ,
1315 // mixing them is unsafe.
1319 // Conservatively merge the ReleaseMetadata information.
1320 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1321 RRI.ReleaseMetadata = 0;
1323 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
1324 RRI.IsTailCallRelease = RRI.IsTailCallRelease && Other.RRI.IsTailCallRelease;
1325 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1327 // Merge the insert point sets. If there are any differences,
1328 // that makes this a partial merge.
1329 RRI.Partial = RRI.ReverseInsertPts.size() !=
1330 Other.RRI.ReverseInsertPts.size();
1331 for (SmallPtrSet<Instruction *, 2>::const_iterator
1332 I = Other.RRI.ReverseInsertPts.begin(),
1333 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1334 RRI.Partial |= RRI.ReverseInsertPts.insert(*I);
1339 /// BBState - Per-BasicBlock state.
1341 /// TopDownPathCount - The number of unique control paths from the entry
1342 /// which can reach this block.
1343 unsigned TopDownPathCount;
1345 /// BottomUpPathCount - The number of unique control paths to exits
1346 /// from this block.
1347 unsigned BottomUpPathCount;
1349 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1350 typedef MapVector<const Value *, PtrState> MapTy;
1352 /// PerPtrTopDown - The top-down traversal uses this to record information
1353 /// known about a pointer at the bottom of each block.
1354 MapTy PerPtrTopDown;
1356 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1357 /// known about a pointer at the top of each block.
1358 MapTy PerPtrBottomUp;
1361 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1363 typedef MapTy::iterator ptr_iterator;
1364 typedef MapTy::const_iterator ptr_const_iterator;
1366 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1367 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1368 ptr_const_iterator top_down_ptr_begin() const {
1369 return PerPtrTopDown.begin();
1371 ptr_const_iterator top_down_ptr_end() const {
1372 return PerPtrTopDown.end();
1375 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1376 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1377 ptr_const_iterator bottom_up_ptr_begin() const {
1378 return PerPtrBottomUp.begin();
1380 ptr_const_iterator bottom_up_ptr_end() const {
1381 return PerPtrBottomUp.end();
1384 /// SetAsEntry - Mark this block as being an entry block, which has one
1385 /// path from the entry by definition.
1386 void SetAsEntry() { TopDownPathCount = 1; }
1388 /// SetAsExit - Mark this block as being an exit block, which has one
1389 /// path to an exit by definition.
1390 void SetAsExit() { BottomUpPathCount = 1; }
1392 PtrState &getPtrTopDownState(const Value *Arg) {
1393 return PerPtrTopDown[Arg];
1396 PtrState &getPtrBottomUpState(const Value *Arg) {
1397 return PerPtrBottomUp[Arg];
1400 void clearBottomUpPointers() {
1401 PerPtrBottomUp.clear();
1404 void clearTopDownPointers() {
1405 PerPtrTopDown.clear();
1408 void InitFromPred(const BBState &Other);
1409 void InitFromSucc(const BBState &Other);
1410 void MergePred(const BBState &Other);
1411 void MergeSucc(const BBState &Other);
1413 /// GetAllPathCount - Return the number of possible unique paths from an
1414 /// entry to an exit which pass through this block. This is only valid
1415 /// after both the top-down and bottom-up traversals are complete.
1416 unsigned GetAllPathCount() const {
1417 return TopDownPathCount * BottomUpPathCount;
1420 /// IsVisitedTopDown - Test whether the block for this BBState has been
1421 /// visited by the top-down portion of the algorithm.
1422 bool isVisitedTopDown() const {
1423 return TopDownPathCount != 0;
1428 void BBState::InitFromPred(const BBState &Other) {
1429 PerPtrTopDown = Other.PerPtrTopDown;
1430 TopDownPathCount = Other.TopDownPathCount;
1433 void BBState::InitFromSucc(const BBState &Other) {
1434 PerPtrBottomUp = Other.PerPtrBottomUp;
1435 BottomUpPathCount = Other.BottomUpPathCount;
1438 /// MergePred - The top-down traversal uses this to merge information about
1439 /// predecessors to form the initial state for a new block.
1440 void BBState::MergePred(const BBState &Other) {
1441 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1442 // loop backedge. Loop backedges are special.
1443 TopDownPathCount += Other.TopDownPathCount;
1445 // For each entry in the other set, if our set has an entry with the same key,
1446 // merge the entries. Otherwise, copy the entry and merge it with an empty
1448 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1449 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1450 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1451 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1455 // For each entry in our set, if the other set doesn't have an entry with the
1456 // same key, force it to merge with an empty entry.
1457 for (ptr_iterator MI = top_down_ptr_begin(),
1458 ME = top_down_ptr_end(); MI != ME; ++MI)
1459 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1460 MI->second.Merge(PtrState(), /*TopDown=*/true);
1463 /// MergeSucc - The bottom-up traversal uses this to merge information about
1464 /// successors to form the initial state for a new block.
1465 void BBState::MergeSucc(const BBState &Other) {
1466 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1467 // loop backedge. Loop backedges are special.
1468 BottomUpPathCount += Other.BottomUpPathCount;
1470 // For each entry in the other set, if our set has an entry with the
1471 // same key, merge the entries. Otherwise, copy the entry and merge
1472 // it with an empty entry.
1473 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1474 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1475 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1476 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1480 // For each entry in our set, if the other set doesn't have an entry
1481 // with the same key, force it to merge with an empty entry.
1482 for (ptr_iterator MI = bottom_up_ptr_begin(),
1483 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1484 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1485 MI->second.Merge(PtrState(), /*TopDown=*/false);
1489 /// ObjCARCOpt - The main ARC optimization pass.
1490 class ObjCARCOpt : public FunctionPass {
1492 ProvenanceAnalysis PA;
1494 /// Run - A flag indicating whether this optimization pass should run.
1497 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1498 /// functions, for use in creating calls to them. These are initialized
1499 /// lazily to avoid cluttering up the Module with unused declarations.
1500 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
1501 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
1503 /// UsedInThisFunciton - Flags which determine whether each of the
1504 /// interesting runtine functions is in fact used in the current function.
1505 unsigned UsedInThisFunction;
1507 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1509 unsigned ImpreciseReleaseMDKind;
1511 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
1513 unsigned CopyOnEscapeMDKind;
1515 Constant *getRetainRVCallee(Module *M);
1516 Constant *getAutoreleaseRVCallee(Module *M);
1517 Constant *getReleaseCallee(Module *M);
1518 Constant *getRetainCallee(Module *M);
1519 Constant *getRetainBlockCallee(Module *M);
1520 Constant *getAutoreleaseCallee(Module *M);
1522 bool IsRetainBlockOptimizable(const Instruction *Inst);
1524 void OptimizeRetainCall(Function &F, Instruction *Retain);
1525 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1526 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1527 void OptimizeIndividualCalls(Function &F);
1529 void CheckForCFGHazards(const BasicBlock *BB,
1530 DenseMap<const BasicBlock *, BBState> &BBStates,
1531 BBState &MyStates) const;
1532 bool VisitBottomUp(BasicBlock *BB,
1533 DenseMap<const BasicBlock *, BBState> &BBStates,
1534 MapVector<Value *, RRInfo> &Retains);
1535 bool VisitTopDown(BasicBlock *BB,
1536 DenseMap<const BasicBlock *, BBState> &BBStates,
1537 DenseMap<Value *, RRInfo> &Releases);
1538 bool Visit(Function &F,
1539 DenseMap<const BasicBlock *, BBState> &BBStates,
1540 MapVector<Value *, RRInfo> &Retains,
1541 DenseMap<Value *, RRInfo> &Releases);
1543 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1544 MapVector<Value *, RRInfo> &Retains,
1545 DenseMap<Value *, RRInfo> &Releases,
1546 SmallVectorImpl<Instruction *> &DeadInsts,
1549 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1550 MapVector<Value *, RRInfo> &Retains,
1551 DenseMap<Value *, RRInfo> &Releases,
1554 void OptimizeWeakCalls(Function &F);
1556 bool OptimizeSequences(Function &F);
1558 void OptimizeReturns(Function &F);
1560 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1561 virtual bool doInitialization(Module &M);
1562 virtual bool runOnFunction(Function &F);
1563 virtual void releaseMemory();
1567 ObjCARCOpt() : FunctionPass(ID) {
1568 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1573 char ObjCARCOpt::ID = 0;
1574 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1575 "objc-arc", "ObjC ARC optimization", false, false)
1576 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1577 INITIALIZE_PASS_END(ObjCARCOpt,
1578 "objc-arc", "ObjC ARC optimization", false, false)
1580 Pass *llvm::createObjCARCOptPass() {
1581 return new ObjCARCOpt();
1584 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1585 AU.addRequired<ObjCARCAliasAnalysis>();
1586 AU.addRequired<AliasAnalysis>();
1587 // ARC optimization doesn't currently split critical edges.
1588 AU.setPreservesCFG();
1591 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1592 // Without the magic metadata tag, we have to assume this might be an
1593 // objc_retainBlock call inserted to convert a block pointer to an id,
1594 // in which case it really is needed.
1595 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1598 // If the pointer "escapes" (not including being used in a call),
1599 // the copy may be needed.
1600 if (DoesObjCBlockEscape(Inst))
1603 // Otherwise, it's not needed.
1607 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1608 if (!RetainRVCallee) {
1609 LLVMContext &C = M->getContext();
1610 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1611 std::vector<Type *> Params;
1612 Params.push_back(I8X);
1614 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1615 AttrListPtr Attributes;
1616 Attributes.addAttr(~0u, Attribute::NoUnwind);
1618 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1621 return RetainRVCallee;
1624 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1625 if (!AutoreleaseRVCallee) {
1626 LLVMContext &C = M->getContext();
1627 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1628 std::vector<Type *> Params;
1629 Params.push_back(I8X);
1631 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1632 AttrListPtr Attributes;
1633 Attributes.addAttr(~0u, Attribute::NoUnwind);
1634 AutoreleaseRVCallee =
1635 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1638 return AutoreleaseRVCallee;
1641 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1642 if (!ReleaseCallee) {
1643 LLVMContext &C = M->getContext();
1644 std::vector<Type *> Params;
1645 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1646 AttrListPtr Attributes;
1647 Attributes.addAttr(~0u, Attribute::NoUnwind);
1649 M->getOrInsertFunction(
1651 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1654 return ReleaseCallee;
1657 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1658 if (!RetainCallee) {
1659 LLVMContext &C = M->getContext();
1660 std::vector<Type *> Params;
1661 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1662 AttrListPtr Attributes;
1663 Attributes.addAttr(~0u, Attribute::NoUnwind);
1665 M->getOrInsertFunction(
1667 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1670 return RetainCallee;
1673 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1674 if (!RetainBlockCallee) {
1675 LLVMContext &C = M->getContext();
1676 std::vector<Type *> Params;
1677 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1678 AttrListPtr Attributes;
1679 // objc_retainBlock is not nounwind because it calls user copy constructors
1680 // which could theoretically throw.
1682 M->getOrInsertFunction(
1684 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1687 return RetainBlockCallee;
1690 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1691 if (!AutoreleaseCallee) {
1692 LLVMContext &C = M->getContext();
1693 std::vector<Type *> Params;
1694 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1695 AttrListPtr Attributes;
1696 Attributes.addAttr(~0u, Attribute::NoUnwind);
1698 M->getOrInsertFunction(
1700 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1703 return AutoreleaseCallee;
1706 /// CanAlterRefCount - Test whether the given instruction can result in a
1707 /// reference count modification (positive or negative) for the pointer's
1710 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1711 ProvenanceAnalysis &PA, InstructionClass Class) {
1713 case IC_Autorelease:
1714 case IC_AutoreleaseRV:
1716 // These operations never directly modify a reference count.
1721 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1722 assert(CS && "Only calls can alter reference counts!");
1724 // See if AliasAnalysis can help us with the call.
1725 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1726 if (AliasAnalysis::onlyReadsMemory(MRB))
1728 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1729 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1731 const Value *Op = *I;
1732 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1738 // Assume the worst.
1742 /// CanUse - Test whether the given instruction can "use" the given pointer's
1743 /// object in a way that requires the reference count to be positive.
1745 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1746 InstructionClass Class) {
1747 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1748 if (Class == IC_Call)
1751 // Consider various instructions which may have pointer arguments which are
1753 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1754 // Comparing a pointer with null, or any other constant, isn't really a use,
1755 // because we don't care what the pointer points to, or about the values
1756 // of any other dynamic reference-counted pointers.
1757 if (!IsPotentialUse(ICI->getOperand(1)))
1759 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1760 // For calls, just check the arguments (and not the callee operand).
1761 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1762 OE = CS.arg_end(); OI != OE; ++OI) {
1763 const Value *Op = *OI;
1764 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1768 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1769 // Special-case stores, because we don't care about the stored value, just
1770 // the store address.
1771 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1772 // If we can't tell what the underlying object was, assume there is a
1774 return IsPotentialUse(Op) && PA.related(Op, Ptr);
1777 // Check each operand for a match.
1778 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1780 const Value *Op = *OI;
1781 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1787 /// CanInterruptRV - Test whether the given instruction can autorelease
1788 /// any pointer or cause an autoreleasepool pop.
1790 CanInterruptRV(InstructionClass Class) {
1792 case IC_AutoreleasepoolPop:
1795 case IC_Autorelease:
1796 case IC_AutoreleaseRV:
1797 case IC_FusedRetainAutorelease:
1798 case IC_FusedRetainAutoreleaseRV:
1806 /// DependenceKind - There are several kinds of dependence-like concepts in
1808 enum DependenceKind {
1809 NeedsPositiveRetainCount,
1810 CanChangeRetainCount,
1811 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1812 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1813 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1817 /// Depends - Test if there can be dependencies on Inst through Arg. This
1818 /// function only tests dependencies relevant for removing pairs of calls.
1820 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1821 ProvenanceAnalysis &PA) {
1822 // If we've reached the definition of Arg, stop.
1827 case NeedsPositiveRetainCount: {
1828 InstructionClass Class = GetInstructionClass(Inst);
1830 case IC_AutoreleasepoolPop:
1831 case IC_AutoreleasepoolPush:
1835 return CanUse(Inst, Arg, PA, Class);
1839 case CanChangeRetainCount: {
1840 InstructionClass Class = GetInstructionClass(Inst);
1842 case IC_AutoreleasepoolPop:
1843 // Conservatively assume this can decrement any count.
1845 case IC_AutoreleasepoolPush:
1849 return CanAlterRefCount(Inst, Arg, PA, Class);
1853 case RetainAutoreleaseDep:
1854 switch (GetBasicInstructionClass(Inst)) {
1855 case IC_AutoreleasepoolPop:
1856 // Don't merge an objc_autorelease with an objc_retain inside a different
1857 // autoreleasepool scope.
1861 // Check for a retain of the same pointer for merging.
1862 return GetObjCArg(Inst) == Arg;
1864 // Nothing else matters for objc_retainAutorelease formation.
1869 case RetainAutoreleaseRVDep: {
1870 InstructionClass Class = GetBasicInstructionClass(Inst);
1874 // Check for a retain of the same pointer for merging.
1875 return GetObjCArg(Inst) == Arg;
1877 // Anything that can autorelease interrupts
1878 // retainAutoreleaseReturnValue formation.
1879 return CanInterruptRV(Class);
1885 return CanInterruptRV(GetBasicInstructionClass(Inst));
1888 llvm_unreachable("Invalid dependence flavor");
1892 /// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
1893 /// find local and non-local dependencies on Arg.
1894 /// TODO: Cache results?
1896 FindDependencies(DependenceKind Flavor,
1898 BasicBlock *StartBB, Instruction *StartInst,
1899 SmallPtrSet<Instruction *, 4> &DependingInstructions,
1900 SmallPtrSet<const BasicBlock *, 4> &Visited,
1901 ProvenanceAnalysis &PA) {
1902 BasicBlock::iterator StartPos = StartInst;
1904 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
1905 Worklist.push_back(std::make_pair(StartBB, StartPos));
1907 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
1908 Worklist.pop_back_val();
1909 BasicBlock *LocalStartBB = Pair.first;
1910 BasicBlock::iterator LocalStartPos = Pair.second;
1911 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
1913 if (LocalStartPos == StartBBBegin) {
1914 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
1916 // If we've reached the function entry, produce a null dependence.
1917 DependingInstructions.insert(0);
1919 // Add the predecessors to the worklist.
1921 BasicBlock *PredBB = *PI;
1922 if (Visited.insert(PredBB))
1923 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
1924 } while (++PI != PE);
1928 Instruction *Inst = --LocalStartPos;
1929 if (Depends(Flavor, Inst, Arg, PA)) {
1930 DependingInstructions.insert(Inst);
1934 } while (!Worklist.empty());
1936 // Determine whether the original StartBB post-dominates all of the blocks we
1937 // visited. If not, insert a sentinal indicating that most optimizations are
1939 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
1940 E = Visited.end(); I != E; ++I) {
1941 const BasicBlock *BB = *I;
1944 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1945 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
1946 const BasicBlock *Succ = *SI;
1947 if (Succ != StartBB && !Visited.count(Succ)) {
1948 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
1955 static bool isNullOrUndef(const Value *V) {
1956 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
1959 static bool isNoopInstruction(const Instruction *I) {
1960 return isa<BitCastInst>(I) ||
1961 (isa<GetElementPtrInst>(I) &&
1962 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
1965 /// OptimizeRetainCall - Turn objc_retain into
1966 /// objc_retainAutoreleasedReturnValue if the operand is a return value.
1968 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
1969 CallSite CS(GetObjCArg(Retain));
1970 Instruction *Call = CS.getInstruction();
1972 if (Call->getParent() != Retain->getParent()) return;
1974 // Check that the call is next to the retain.
1975 BasicBlock::iterator I = Call;
1977 while (isNoopInstruction(I)) ++I;
1981 // Turn it to an objc_retainAutoreleasedReturnValue..
1984 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
1987 /// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
1988 /// objc_retain if the operand is not a return value. Or, if it can be
1989 /// paired with an objc_autoreleaseReturnValue, delete the pair and
1992 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1993 // Check for the argument being from an immediately preceding call.
1994 Value *Arg = GetObjCArg(RetainRV);
1996 if (Instruction *Call = CS.getInstruction())
1997 if (Call->getParent() == RetainRV->getParent()) {
1998 BasicBlock::iterator I = Call;
2000 while (isNoopInstruction(I)) ++I;
2001 if (&*I == RetainRV)
2005 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2006 // pointer. In this case, we can delete the pair.
2007 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2009 do --I; while (I != Begin && isNoopInstruction(I));
2010 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2011 GetObjCArg(I) == Arg) {
2014 EraseInstruction(I);
2015 EraseInstruction(RetainRV);
2020 // Turn it to a plain objc_retain.
2023 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2027 /// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2028 /// objc_autorelease if the result is not used as a return value.
2030 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
2031 // Check for a return of the pointer value.
2032 const Value *Ptr = GetObjCArg(AutoreleaseRV);
2033 SmallVector<const Value *, 2> Users;
2034 Users.push_back(Ptr);
2036 Ptr = Users.pop_back_val();
2037 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2039 const User *I = *UI;
2040 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2042 if (isa<BitCastInst>(I))
2045 } while (!Users.empty());
2049 cast<CallInst>(AutoreleaseRV)->
2050 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2053 /// OptimizeIndividualCalls - Visit each call, one at a time, and make
2054 /// simplifications without doing any additional analysis.
2055 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2056 // Reset all the flags in preparation for recomputing them.
2057 UsedInThisFunction = 0;
2059 // Visit all objc_* calls in F.
2060 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2061 Instruction *Inst = &*I++;
2062 InstructionClass Class = GetBasicInstructionClass(Inst);
2067 // Delete no-op casts. These function calls have special semantics, but
2068 // the semantics are entirely implemented via lowering in the front-end,
2069 // so by the time they reach the optimizer, they are just no-op calls
2070 // which return their argument.
2072 // There are gray areas here, as the ability to cast reference-counted
2073 // pointers to raw void* and back allows code to break ARC assumptions,
2074 // however these are currently considered to be unimportant.
2078 EraseInstruction(Inst);
2081 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2084 case IC_LoadWeakRetained:
2086 case IC_DestroyWeak: {
2087 CallInst *CI = cast<CallInst>(Inst);
2088 if (isNullOrUndef(CI->getArgOperand(0))) {
2089 Type *Ty = CI->getArgOperand(0)->getType();
2090 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2091 Constant::getNullValue(Ty),
2093 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2094 CI->eraseFromParent();
2101 CallInst *CI = cast<CallInst>(Inst);
2102 if (isNullOrUndef(CI->getArgOperand(0)) ||
2103 isNullOrUndef(CI->getArgOperand(1))) {
2104 Type *Ty = CI->getArgOperand(0)->getType();
2105 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2106 Constant::getNullValue(Ty),
2108 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2109 CI->eraseFromParent();
2115 OptimizeRetainCall(F, Inst);
2118 if (OptimizeRetainRVCall(F, Inst))
2121 case IC_AutoreleaseRV:
2122 OptimizeAutoreleaseRVCall(F, Inst);
2126 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2127 if (IsAutorelease(Class) && Inst->use_empty()) {
2128 CallInst *Call = cast<CallInst>(Inst);
2129 const Value *Arg = Call->getArgOperand(0);
2130 Arg = FindSingleUseIdentifiedObject(Arg);
2135 // Create the declaration lazily.
2136 LLVMContext &C = Inst->getContext();
2138 CallInst::Create(getReleaseCallee(F.getParent()),
2139 Call->getArgOperand(0), "", Call);
2140 NewCall->setMetadata(ImpreciseReleaseMDKind,
2141 MDNode::get(C, ArrayRef<Value *>()));
2142 EraseInstruction(Call);
2148 // For functions which can never be passed stack arguments, add
2150 if (IsAlwaysTail(Class)) {
2152 cast<CallInst>(Inst)->setTailCall();
2155 // Set nounwind as needed.
2156 if (IsNoThrow(Class)) {
2158 cast<CallInst>(Inst)->setDoesNotThrow();
2161 if (!IsNoopOnNull(Class)) {
2162 UsedInThisFunction |= 1 << Class;
2166 const Value *Arg = GetObjCArg(Inst);
2168 // ARC calls with null are no-ops. Delete them.
2169 if (isNullOrUndef(Arg)) {
2172 EraseInstruction(Inst);
2176 // Keep track of which of retain, release, autorelease, and retain_block
2177 // are actually present in this function.
2178 UsedInThisFunction |= 1 << Class;
2180 // If Arg is a PHI, and one or more incoming values to the
2181 // PHI are null, and the call is control-equivalent to the PHI, and there
2182 // are no relevant side effects between the PHI and the call, the call
2183 // could be pushed up to just those paths with non-null incoming values.
2184 // For now, don't bother splitting critical edges for this.
2185 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2186 Worklist.push_back(std::make_pair(Inst, Arg));
2188 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2192 const PHINode *PN = dyn_cast<PHINode>(Arg);
2195 // Determine if the PHI has any null operands, or any incoming
2197 bool HasNull = false;
2198 bool HasCriticalEdges = false;
2199 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2201 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2202 if (isNullOrUndef(Incoming))
2204 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2205 .getNumSuccessors() != 1) {
2206 HasCriticalEdges = true;
2210 // If we have null operands and no critical edges, optimize.
2211 if (!HasCriticalEdges && HasNull) {
2212 SmallPtrSet<Instruction *, 4> DependingInstructions;
2213 SmallPtrSet<const BasicBlock *, 4> Visited;
2215 // Check that there is nothing that cares about the reference
2216 // count between the call and the phi.
2217 FindDependencies(NeedsPositiveRetainCount, Arg,
2218 Inst->getParent(), Inst,
2219 DependingInstructions, Visited, PA);
2220 if (DependingInstructions.size() == 1 &&
2221 *DependingInstructions.begin() == PN) {
2224 // Clone the call into each predecessor that has a non-null value.
2225 CallInst *CInst = cast<CallInst>(Inst);
2226 Type *ParamTy = CInst->getArgOperand(0)->getType();
2227 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2229 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2230 if (!isNullOrUndef(Incoming)) {
2231 CallInst *Clone = cast<CallInst>(CInst->clone());
2232 Value *Op = PN->getIncomingValue(i);
2233 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2234 if (Op->getType() != ParamTy)
2235 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2236 Clone->setArgOperand(0, Op);
2237 Clone->insertBefore(InsertPos);
2238 Worklist.push_back(std::make_pair(Clone, Incoming));
2241 // Erase the original call.
2242 EraseInstruction(CInst);
2246 } while (!Worklist.empty());
2250 /// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2251 /// control flow, or other CFG structures where moving code across the edge
2252 /// would result in it being executed more.
2254 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2255 DenseMap<const BasicBlock *, BBState> &BBStates,
2256 BBState &MyStates) const {
2257 // If any top-down local-use or possible-dec has a succ which is earlier in
2258 // the sequence, forget it.
2259 for (BBState::ptr_const_iterator I = MyStates.top_down_ptr_begin(),
2260 E = MyStates.top_down_ptr_end(); I != E; ++I)
2261 switch (I->second.GetSeq()) {
2264 const Value *Arg = I->first;
2265 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2266 bool SomeSuccHasSame = false;
2267 bool AllSuccsHaveSame = true;
2268 PtrState &S = MyStates.getPtrTopDownState(Arg);
2269 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2270 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2271 switch (SuccS.GetSeq()) {
2273 case S_CanRelease: {
2274 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2275 S.ClearSequenceProgress();
2279 SomeSuccHasSame = true;
2283 case S_MovableRelease:
2284 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2285 AllSuccsHaveSame = false;
2288 llvm_unreachable("bottom-up pointer in retain state!");
2291 // If the state at the other end of any of the successor edges
2292 // matches the current state, require all edges to match. This
2293 // guards against loops in the middle of a sequence.
2294 if (SomeSuccHasSame && !AllSuccsHaveSame)
2295 S.ClearSequenceProgress();
2298 case S_CanRelease: {
2299 const Value *Arg = I->first;
2300 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2301 bool SomeSuccHasSame = false;
2302 bool AllSuccsHaveSame = true;
2303 PtrState &S = MyStates.getPtrTopDownState(Arg);
2304 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2305 PtrState &SuccS = BBStates[*SI].getPtrBottomUpState(Arg);
2306 switch (SuccS.GetSeq()) {
2308 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2309 S.ClearSequenceProgress();
2313 SomeSuccHasSame = true;
2317 case S_MovableRelease:
2319 if (!S.RRI.KnownSafe && !SuccS.RRI.KnownSafe)
2320 AllSuccsHaveSame = false;
2323 llvm_unreachable("bottom-up pointer in retain state!");
2326 // If the state at the other end of any of the successor edges
2327 // matches the current state, require all edges to match. This
2328 // guards against loops in the middle of a sequence.
2329 if (SomeSuccHasSame && !AllSuccsHaveSame)
2330 S.ClearSequenceProgress();
2337 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2338 DenseMap<const BasicBlock *, BBState> &BBStates,
2339 MapVector<Value *, RRInfo> &Retains) {
2340 bool NestingDetected = false;
2341 BBState &MyStates = BBStates[BB];
2343 // Merge the states from each successor to compute the initial state
2344 // for the current block.
2345 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2346 succ_const_iterator SI(TI), SE(TI, false);
2348 MyStates.SetAsExit();
2351 const BasicBlock *Succ = *SI++;
2354 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2355 // If we haven't seen this node yet, then we've found a CFG cycle.
2356 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2357 if (I == BBStates.end())
2359 MyStates.InitFromSucc(I->second);
2363 I = BBStates.find(Succ);
2364 if (I != BBStates.end())
2365 MyStates.MergeSucc(I->second);
2371 // Visit all the instructions, bottom-up.
2372 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2373 Instruction *Inst = llvm::prior(I);
2374 InstructionClass Class = GetInstructionClass(Inst);
2375 const Value *Arg = 0;
2379 Arg = GetObjCArg(Inst);
2381 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2383 // If we see two releases in a row on the same pointer. If so, make
2384 // a note, and we'll cicle back to revisit it after we've
2385 // hopefully eliminated the second release, which may allow us to
2386 // eliminate the first release too.
2387 // Theoretically we could implement removal of nested retain+release
2388 // pairs by making PtrState hold a stack of states, but this is
2389 // simple and avoids adding overhead for the non-nested case.
2390 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2391 NestingDetected = true;
2395 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2396 S.SetSeq(ReleaseMetadata ? S_MovableRelease : S_Release);
2397 S.RRI.ReleaseMetadata = ReleaseMetadata;
2398 S.RRI.KnownSafe = S.IsKnownNested() || S.IsKnownIncremented();
2399 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2400 S.RRI.Calls.insert(Inst);
2402 S.IncrementRefCount();
2403 S.IncrementNestCount();
2406 case IC_RetainBlock:
2407 // An objc_retainBlock call with just a use may need to be kept,
2408 // because it may be copying a block from the stack to the heap.
2409 if (!IsRetainBlockOptimizable(Inst))
2414 Arg = GetObjCArg(Inst);
2416 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2417 S.DecrementRefCount();
2418 S.SetAtLeastOneRefCount();
2419 S.DecrementNestCount();
2421 switch (S.GetSeq()) {
2424 case S_MovableRelease:
2426 S.RRI.ReverseInsertPts.clear();
2429 // Don't do retain+release tracking for IC_RetainRV, because it's
2430 // better to let it remain as the first instruction after a call.
2431 if (Class != IC_RetainRV) {
2432 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2433 Retains[Inst] = S.RRI;
2435 S.ClearSequenceProgress();
2440 llvm_unreachable("bottom-up pointer in retain state!");
2444 case IC_AutoreleasepoolPop:
2445 // Conservatively, clear MyStates for all known pointers.
2446 MyStates.clearBottomUpPointers();
2448 case IC_AutoreleasepoolPush:
2450 // These are irrelevant.
2456 // Consider any other possible effects of this instruction on each
2457 // pointer being tracked.
2458 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2459 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2460 const Value *Ptr = MI->first;
2462 continue; // Handled above.
2463 PtrState &S = MI->second;
2464 Sequence Seq = S.GetSeq();
2466 // Check for possible releases.
2467 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2468 S.DecrementRefCount();
2471 S.SetSeq(S_CanRelease);
2475 case S_MovableRelease:
2480 llvm_unreachable("bottom-up pointer in retain state!");
2484 // Check for possible direct uses.
2487 case S_MovableRelease:
2488 if (CanUse(Inst, Ptr, PA, Class)) {
2489 assert(S.RRI.ReverseInsertPts.empty());
2490 S.RRI.ReverseInsertPts.insert(Inst);
2492 } else if (Seq == S_Release &&
2493 (Class == IC_User || Class == IC_CallOrUser)) {
2494 // Non-movable releases depend on any possible objc pointer use.
2496 assert(S.RRI.ReverseInsertPts.empty());
2497 S.RRI.ReverseInsertPts.insert(Inst);
2501 if (CanUse(Inst, Ptr, PA, Class))
2509 llvm_unreachable("bottom-up pointer in retain state!");
2514 return NestingDetected;
2518 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2519 DenseMap<const BasicBlock *, BBState> &BBStates,
2520 DenseMap<Value *, RRInfo> &Releases) {
2521 bool NestingDetected = false;
2522 BBState &MyStates = BBStates[BB];
2524 // Merge the states from each predecessor to compute the initial state
2525 // for the current block.
2526 const_pred_iterator PI(BB), PE(BB, false);
2528 MyStates.SetAsEntry();
2531 const BasicBlock *Pred = *PI++;
2534 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2535 // If we haven't seen this node yet, then we've found a CFG cycle.
2536 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2537 if (I == BBStates.end() || !I->second.isVisitedTopDown())
2539 MyStates.InitFromPred(I->second);
2543 I = BBStates.find(Pred);
2544 if (I != BBStates.end() && I->second.isVisitedTopDown())
2545 MyStates.MergePred(I->second);
2551 // Visit all the instructions, top-down.
2552 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2553 Instruction *Inst = I;
2554 InstructionClass Class = GetInstructionClass(Inst);
2555 const Value *Arg = 0;
2558 case IC_RetainBlock:
2559 // An objc_retainBlock call with just a use may need to be kept,
2560 // because it may be copying a block from the stack to the heap.
2561 if (!IsRetainBlockOptimizable(Inst))
2566 Arg = GetObjCArg(Inst);
2568 PtrState &S = MyStates.getPtrTopDownState(Arg);
2570 // Don't do retain+release tracking for IC_RetainRV, because it's
2571 // better to let it remain as the first instruction after a call.
2572 if (Class != IC_RetainRV) {
2573 // If we see two retains in a row on the same pointer. If so, make
2574 // a note, and we'll cicle back to revisit it after we've
2575 // hopefully eliminated the second retain, which may allow us to
2576 // eliminate the first retain too.
2577 // Theoretically we could implement removal of nested retain+release
2578 // pairs by making PtrState hold a stack of states, but this is
2579 // simple and avoids adding overhead for the non-nested case.
2580 if (S.GetSeq() == S_Retain)
2581 NestingDetected = true;
2585 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2586 // Don't check S.IsKnownIncremented() here because it's not
2588 S.RRI.KnownSafe = S.IsKnownNested();
2589 S.RRI.Calls.insert(Inst);
2592 S.SetAtLeastOneRefCount();
2593 S.IncrementRefCount();
2594 S.IncrementNestCount();
2598 Arg = GetObjCArg(Inst);
2600 PtrState &S = MyStates.getPtrTopDownState(Arg);
2601 S.DecrementRefCount();
2602 S.DecrementNestCount();
2604 switch (S.GetSeq()) {
2607 S.RRI.ReverseInsertPts.clear();
2610 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2611 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2612 Releases[Inst] = S.RRI;
2613 S.ClearSequenceProgress();
2619 case S_MovableRelease:
2620 llvm_unreachable("top-down pointer in release state!");
2624 case IC_AutoreleasepoolPop:
2625 // Conservatively, clear MyStates for all known pointers.
2626 MyStates.clearTopDownPointers();
2628 case IC_AutoreleasepoolPush:
2630 // These are irrelevant.
2636 // Consider any other possible effects of this instruction on each
2637 // pointer being tracked.
2638 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2639 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2640 const Value *Ptr = MI->first;
2642 continue; // Handled above.
2643 PtrState &S = MI->second;
2644 Sequence Seq = S.GetSeq();
2646 // Check for possible releases.
2647 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2648 S.DecrementRefCount();
2651 S.SetSeq(S_CanRelease);
2652 assert(S.RRI.ReverseInsertPts.empty());
2653 S.RRI.ReverseInsertPts.insert(Inst);
2655 // One call can't cause a transition from S_Retain to S_CanRelease
2656 // and S_CanRelease to S_Use. If we've made the first transition,
2665 case S_MovableRelease:
2666 llvm_unreachable("top-down pointer in release state!");
2670 // Check for possible direct uses.
2673 if (CanUse(Inst, Ptr, PA, Class))
2682 case S_MovableRelease:
2683 llvm_unreachable("top-down pointer in release state!");
2688 CheckForCFGHazards(BB, BBStates, MyStates);
2689 return NestingDetected;
2693 ComputePostOrders(Function &F,
2694 SmallVectorImpl<BasicBlock *> &PostOrder,
2695 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder) {
2696 /// Backedges - Backedges detected in the DFS. These edges will be
2697 /// ignored in the reverse-CFG DFS, so that loops with multiple exits will be
2698 /// traversed in the desired order.
2699 DenseSet<std::pair<BasicBlock *, BasicBlock *> > Backedges;
2701 /// Visited - The visited set, for doing DFS walks.
2702 SmallPtrSet<BasicBlock *, 16> Visited;
2704 // Do DFS, computing the PostOrder.
2705 SmallPtrSet<BasicBlock *, 16> OnStack;
2706 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2707 BasicBlock *EntryBB = &F.getEntryBlock();
2708 SuccStack.push_back(std::make_pair(EntryBB, succ_begin(EntryBB)));
2709 Visited.insert(EntryBB);
2710 OnStack.insert(EntryBB);
2713 succ_iterator End = succ_end(SuccStack.back().first);
2714 while (SuccStack.back().second != End) {
2715 BasicBlock *BB = *SuccStack.back().second++;
2716 if (Visited.insert(BB)) {
2717 SuccStack.push_back(std::make_pair(BB, succ_begin(BB)));
2721 if (OnStack.count(BB))
2722 Backedges.insert(std::make_pair(SuccStack.back().first, BB));
2724 OnStack.erase(SuccStack.back().first);
2725 PostOrder.push_back(SuccStack.pop_back_val().first);
2726 } while (!SuccStack.empty());
2730 // Compute the exits, which are the starting points for reverse-CFG DFS.
2731 SmallVector<BasicBlock *, 4> Exits;
2732 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2734 if (BB->getTerminator()->getNumSuccessors() == 0)
2735 Exits.push_back(BB);
2738 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2739 SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> PredStack;
2740 for (SmallVectorImpl<BasicBlock *>::iterator I = Exits.begin(), E = Exits.end();
2742 BasicBlock *ExitBB = *I;
2743 PredStack.push_back(std::make_pair(ExitBB, pred_begin(ExitBB)));
2744 Visited.insert(ExitBB);
2745 while (!PredStack.empty()) {
2746 reverse_dfs_next_succ:
2747 pred_iterator End = pred_end(PredStack.back().first);
2748 while (PredStack.back().second != End) {
2749 BasicBlock *BB = *PredStack.back().second++;
2750 // Skip backedges detected in the forward-CFG DFS.
2751 if (Backedges.count(std::make_pair(BB, PredStack.back().first)))
2753 if (Visited.insert(BB)) {
2754 PredStack.push_back(std::make_pair(BB, pred_begin(BB)));
2755 goto reverse_dfs_next_succ;
2758 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2763 // Visit - Visit the function both top-down and bottom-up.
2765 ObjCARCOpt::Visit(Function &F,
2766 DenseMap<const BasicBlock *, BBState> &BBStates,
2767 MapVector<Value *, RRInfo> &Retains,
2768 DenseMap<Value *, RRInfo> &Releases) {
2770 // Use reverse-postorder traversals, because we magically know that loops
2771 // will be well behaved, i.e. they won't repeatedly call retain on a single
2772 // pointer without doing a release. We can't use the ReversePostOrderTraversal
2773 // class here because we want the reverse-CFG postorder to consider each
2774 // function exit point, and we want to ignore selected cycle edges.
2775 SmallVector<BasicBlock *, 16> PostOrder;
2776 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
2777 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder);
2779 // Use reverse-postorder on the reverse CFG for bottom-up.
2780 bool BottomUpNestingDetected = false;
2781 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2782 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
2784 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
2786 // Use reverse-postorder for top-down.
2787 bool TopDownNestingDetected = false;
2788 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
2789 PostOrder.rbegin(), E = PostOrder.rend();
2791 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
2793 return TopDownNestingDetected && BottomUpNestingDetected;
2796 /// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
2797 void ObjCARCOpt::MoveCalls(Value *Arg,
2798 RRInfo &RetainsToMove,
2799 RRInfo &ReleasesToMove,
2800 MapVector<Value *, RRInfo> &Retains,
2801 DenseMap<Value *, RRInfo> &Releases,
2802 SmallVectorImpl<Instruction *> &DeadInsts,
2804 Type *ArgTy = Arg->getType();
2805 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
2807 // Insert the new retain and release calls.
2808 for (SmallPtrSet<Instruction *, 2>::const_iterator
2809 PI = ReleasesToMove.ReverseInsertPts.begin(),
2810 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2811 Instruction *InsertPt = *PI;
2812 Value *MyArg = ArgTy == ParamTy ? Arg :
2813 new BitCastInst(Arg, ParamTy, "", InsertPt);
2815 CallInst::Create(RetainsToMove.IsRetainBlock ?
2816 getRetainBlockCallee(M) : getRetainCallee(M),
2817 MyArg, "", InsertPt);
2818 Call->setDoesNotThrow();
2819 if (RetainsToMove.IsRetainBlock)
2820 Call->setMetadata(CopyOnEscapeMDKind,
2821 MDNode::get(M->getContext(), ArrayRef<Value *>()));
2823 Call->setTailCall();
2825 for (SmallPtrSet<Instruction *, 2>::const_iterator
2826 PI = RetainsToMove.ReverseInsertPts.begin(),
2827 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2828 Instruction *LastUse = *PI;
2829 Instruction *InsertPts[] = { 0, 0, 0 };
2830 if (InvokeInst *II = dyn_cast<InvokeInst>(LastUse)) {
2831 // We can't insert code immediately after an invoke instruction, so
2832 // insert code at the beginning of both successor blocks instead.
2833 // The invoke's return value isn't available in the unwind block,
2834 // but our releases will never depend on it, because they must be
2835 // paired with retains from before the invoke.
2836 InsertPts[0] = II->getNormalDest()->getFirstInsertionPt();
2837 InsertPts[1] = II->getUnwindDest()->getFirstInsertionPt();
2839 // Insert code immediately after the last use.
2840 InsertPts[0] = llvm::next(BasicBlock::iterator(LastUse));
2843 for (Instruction **I = InsertPts; *I; ++I) {
2844 Instruction *InsertPt = *I;
2845 Value *MyArg = ArgTy == ParamTy ? Arg :
2846 new BitCastInst(Arg, ParamTy, "", InsertPt);
2847 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
2849 // Attach a clang.imprecise_release metadata tag, if appropriate.
2850 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2851 Call->setMetadata(ImpreciseReleaseMDKind, M);
2852 Call->setDoesNotThrow();
2853 if (ReleasesToMove.IsTailCallRelease)
2854 Call->setTailCall();
2858 // Delete the original retain and release calls.
2859 for (SmallPtrSet<Instruction *, 2>::const_iterator
2860 AI = RetainsToMove.Calls.begin(),
2861 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2862 Instruction *OrigRetain = *AI;
2863 Retains.blot(OrigRetain);
2864 DeadInsts.push_back(OrigRetain);
2866 for (SmallPtrSet<Instruction *, 2>::const_iterator
2867 AI = ReleasesToMove.Calls.begin(),
2868 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2869 Instruction *OrigRelease = *AI;
2870 Releases.erase(OrigRelease);
2871 DeadInsts.push_back(OrigRelease);
2876 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2878 MapVector<Value *, RRInfo> &Retains,
2879 DenseMap<Value *, RRInfo> &Releases,
2881 bool AnyPairsCompletelyEliminated = false;
2882 RRInfo RetainsToMove;
2883 RRInfo ReleasesToMove;
2884 SmallVector<Instruction *, 4> NewRetains;
2885 SmallVector<Instruction *, 4> NewReleases;
2886 SmallVector<Instruction *, 8> DeadInsts;
2888 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2889 E = Retains.end(); I != E; ++I) {
2890 Value *V = I->first;
2891 if (!V) continue; // blotted
2893 Instruction *Retain = cast<Instruction>(V);
2894 Value *Arg = GetObjCArg(Retain);
2896 // If the object being released is in static or stack storage, we know it's
2897 // not being managed by ObjC reference counting, so we can delete pairs
2898 // regardless of what possible decrements or uses lie between them.
2899 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
2901 // A constant pointer can't be pointing to an object on the heap. It may
2902 // be reference-counted, but it won't be deleted.
2903 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
2904 if (const GlobalVariable *GV =
2905 dyn_cast<GlobalVariable>(
2906 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
2907 if (GV->isConstant())
2910 // If a pair happens in a region where it is known that the reference count
2911 // is already incremented, we can similarly ignore possible decrements.
2912 bool KnownSafeTD = true, KnownSafeBU = true;
2914 // Connect the dots between the top-down-collected RetainsToMove and
2915 // bottom-up-collected ReleasesToMove to form sets of related calls.
2916 // This is an iterative process so that we connect multiple releases
2917 // to multiple retains if needed.
2918 unsigned OldDelta = 0;
2919 unsigned NewDelta = 0;
2920 unsigned OldCount = 0;
2921 unsigned NewCount = 0;
2922 bool FirstRelease = true;
2923 bool FirstRetain = true;
2924 NewRetains.push_back(Retain);
2926 for (SmallVectorImpl<Instruction *>::const_iterator
2927 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2928 Instruction *NewRetain = *NI;
2929 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2930 assert(It != Retains.end());
2931 const RRInfo &NewRetainRRI = It->second;
2932 KnownSafeTD &= NewRetainRRI.KnownSafe;
2933 for (SmallPtrSet<Instruction *, 2>::const_iterator
2934 LI = NewRetainRRI.Calls.begin(),
2935 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2936 Instruction *NewRetainRelease = *LI;
2937 DenseMap<Value *, RRInfo>::const_iterator Jt =
2938 Releases.find(NewRetainRelease);
2939 if (Jt == Releases.end())
2941 const RRInfo &NewRetainReleaseRRI = Jt->second;
2942 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2943 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2945 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2947 // Merge the ReleaseMetadata and IsTailCallRelease values.
2949 ReleasesToMove.ReleaseMetadata =
2950 NewRetainReleaseRRI.ReleaseMetadata;
2951 ReleasesToMove.IsTailCallRelease =
2952 NewRetainReleaseRRI.IsTailCallRelease;
2953 FirstRelease = false;
2955 if (ReleasesToMove.ReleaseMetadata !=
2956 NewRetainReleaseRRI.ReleaseMetadata)
2957 ReleasesToMove.ReleaseMetadata = 0;
2958 if (ReleasesToMove.IsTailCallRelease !=
2959 NewRetainReleaseRRI.IsTailCallRelease)
2960 ReleasesToMove.IsTailCallRelease = false;
2963 // Collect the optimal insertion points.
2965 for (SmallPtrSet<Instruction *, 2>::const_iterator
2966 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2967 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2969 Instruction *RIP = *RI;
2970 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2971 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2973 NewReleases.push_back(NewRetainRelease);
2978 if (NewReleases.empty()) break;
2980 // Back the other way.
2981 for (SmallVectorImpl<Instruction *>::const_iterator
2982 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2983 Instruction *NewRelease = *NI;
2984 DenseMap<Value *, RRInfo>::const_iterator It =
2985 Releases.find(NewRelease);
2986 assert(It != Releases.end());
2987 const RRInfo &NewReleaseRRI = It->second;
2988 KnownSafeBU &= NewReleaseRRI.KnownSafe;
2989 for (SmallPtrSet<Instruction *, 2>::const_iterator
2990 LI = NewReleaseRRI.Calls.begin(),
2991 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2992 Instruction *NewReleaseRetain = *LI;
2993 MapVector<Value *, RRInfo>::const_iterator Jt =
2994 Retains.find(NewReleaseRetain);
2995 if (Jt == Retains.end())
2997 const RRInfo &NewReleaseRetainRRI = Jt->second;
2998 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2999 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3000 unsigned PathCount =
3001 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3002 OldDelta += PathCount;
3003 OldCount += PathCount;
3005 // Merge the IsRetainBlock values.
3007 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3008 FirstRetain = false;
3009 } else if (ReleasesToMove.IsRetainBlock !=
3010 NewReleaseRetainRRI.IsRetainBlock)
3011 // It's not possible to merge the sequences if one uses
3012 // objc_retain and the other uses objc_retainBlock.
3015 // Collect the optimal insertion points.
3017 for (SmallPtrSet<Instruction *, 2>::const_iterator
3018 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3019 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3021 Instruction *RIP = *RI;
3022 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3023 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3024 NewDelta += PathCount;
3025 NewCount += PathCount;
3028 NewRetains.push_back(NewReleaseRetain);
3032 NewReleases.clear();
3033 if (NewRetains.empty()) break;
3036 // If the pointer is known incremented or nested, we can safely delete the
3037 // pair regardless of what's between them.
3038 if (KnownSafeTD || KnownSafeBU) {
3039 RetainsToMove.ReverseInsertPts.clear();
3040 ReleasesToMove.ReverseInsertPts.clear();
3043 // Determine whether the new insertion points we computed preserve the
3044 // balance of retain and release calls through the program.
3045 // TODO: If the fully aggressive solution isn't valid, try to find a
3046 // less aggressive solution which is.
3051 // Determine whether the original call points are balanced in the retain and
3052 // release calls through the program. If not, conservatively don't touch
3054 // TODO: It's theoretically possible to do code motion in this case, as
3055 // long as the existing imbalances are maintained.
3059 // Ok, everything checks out and we're all set. Let's move some code!
3061 AnyPairsCompletelyEliminated = NewCount == 0;
3062 NumRRs += OldCount - NewCount;
3063 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3064 Retains, Releases, DeadInsts, M);
3067 NewReleases.clear();
3069 RetainsToMove.clear();
3070 ReleasesToMove.clear();
3073 // Now that we're done moving everything, we can delete the newly dead
3074 // instructions, as we no longer need them as insert points.
3075 while (!DeadInsts.empty())
3076 EraseInstruction(DeadInsts.pop_back_val());
3078 return AnyPairsCompletelyEliminated;
3081 /// OptimizeWeakCalls - Weak pointer optimizations.
3082 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3083 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3084 // itself because it uses AliasAnalysis and we need to do provenance
3086 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3087 Instruction *Inst = &*I++;
3088 InstructionClass Class = GetBasicInstructionClass(Inst);
3089 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3092 // Delete objc_loadWeak calls with no users.
3093 if (Class == IC_LoadWeak && Inst->use_empty()) {
3094 Inst->eraseFromParent();
3098 // TODO: For now, just look for an earlier available version of this value
3099 // within the same block. Theoretically, we could do memdep-style non-local
3100 // analysis too, but that would want caching. A better approach would be to
3101 // use the technique that EarlyCSE uses.
3102 inst_iterator Current = llvm::prior(I);
3103 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3104 for (BasicBlock::iterator B = CurrentBB->begin(),
3105 J = Current.getInstructionIterator();
3107 Instruction *EarlierInst = &*llvm::prior(J);
3108 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3109 switch (EarlierClass) {
3111 case IC_LoadWeakRetained: {
3112 // If this is loading from the same pointer, replace this load's value
3114 CallInst *Call = cast<CallInst>(Inst);
3115 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3116 Value *Arg = Call->getArgOperand(0);
3117 Value *EarlierArg = EarlierCall->getArgOperand(0);
3118 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3119 case AliasAnalysis::MustAlias:
3121 // If the load has a builtin retain, insert a plain retain for it.
3122 if (Class == IC_LoadWeakRetained) {
3124 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3128 // Zap the fully redundant load.
3129 Call->replaceAllUsesWith(EarlierCall);
3130 Call->eraseFromParent();
3132 case AliasAnalysis::MayAlias:
3133 case AliasAnalysis::PartialAlias:
3135 case AliasAnalysis::NoAlias:
3142 // If this is storing to the same pointer and has the same size etc.
3143 // replace this load's value with the stored value.
3144 CallInst *Call = cast<CallInst>(Inst);
3145 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3146 Value *Arg = Call->getArgOperand(0);
3147 Value *EarlierArg = EarlierCall->getArgOperand(0);
3148 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3149 case AliasAnalysis::MustAlias:
3151 // If the load has a builtin retain, insert a plain retain for it.
3152 if (Class == IC_LoadWeakRetained) {
3154 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3158 // Zap the fully redundant load.
3159 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3160 Call->eraseFromParent();
3162 case AliasAnalysis::MayAlias:
3163 case AliasAnalysis::PartialAlias:
3165 case AliasAnalysis::NoAlias:
3172 // TOOD: Grab the copied value.
3174 case IC_AutoreleasepoolPush:
3177 // Weak pointers are only modified through the weak entry points
3178 // (and arbitrary calls, which could call the weak entry points).
3181 // Anything else could modify the weak pointer.
3188 // Then, for each destroyWeak with an alloca operand, check to see if
3189 // the alloca and all its users can be zapped.
3190 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3191 Instruction *Inst = &*I++;
3192 InstructionClass Class = GetBasicInstructionClass(Inst);
3193 if (Class != IC_DestroyWeak)
3196 CallInst *Call = cast<CallInst>(Inst);
3197 Value *Arg = Call->getArgOperand(0);
3198 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3199 for (Value::use_iterator UI = Alloca->use_begin(),
3200 UE = Alloca->use_end(); UI != UE; ++UI) {
3201 Instruction *UserInst = cast<Instruction>(*UI);
3202 switch (GetBasicInstructionClass(UserInst)) {
3205 case IC_DestroyWeak:
3212 for (Value::use_iterator UI = Alloca->use_begin(),
3213 UE = Alloca->use_end(); UI != UE; ) {
3214 CallInst *UserInst = cast<CallInst>(*UI++);
3215 if (!UserInst->use_empty())
3216 UserInst->replaceAllUsesWith(UserInst->getArgOperand(0));
3217 UserInst->eraseFromParent();
3219 Alloca->eraseFromParent();
3225 /// OptimizeSequences - Identify program paths which execute sequences of
3226 /// retains and releases which can be eliminated.
3227 bool ObjCARCOpt::OptimizeSequences(Function &F) {
3228 /// Releases, Retains - These are used to store the results of the main flow
3229 /// analysis. These use Value* as the key instead of Instruction* so that the
3230 /// map stays valid when we get around to rewriting code and calls get
3231 /// replaced by arguments.
3232 DenseMap<Value *, RRInfo> Releases;
3233 MapVector<Value *, RRInfo> Retains;
3235 /// BBStates, This is used during the traversal of the function to track the
3236 /// states for each identified object at each block.
3237 DenseMap<const BasicBlock *, BBState> BBStates;
3239 // Analyze the CFG of the function, and all instructions.
3240 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3243 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3247 /// OptimizeReturns - Look for this pattern:
3249 /// %call = call i8* @something(...)
3250 /// %2 = call i8* @objc_retain(i8* %call)
3251 /// %3 = call i8* @objc_autorelease(i8* %2)
3254 /// And delete the retain and autorelease.
3256 /// Otherwise if it's just this:
3258 /// %3 = call i8* @objc_autorelease(i8* %2)
3261 /// convert the autorelease to autoreleaseRV.
3262 void ObjCARCOpt::OptimizeReturns(Function &F) {
3263 if (!F.getReturnType()->isPointerTy())
3266 SmallPtrSet<Instruction *, 4> DependingInstructions;
3267 SmallPtrSet<const BasicBlock *, 4> Visited;
3268 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3269 BasicBlock *BB = FI;
3270 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3273 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3274 FindDependencies(NeedsPositiveRetainCount, Arg,
3275 BB, Ret, DependingInstructions, Visited, PA);
3276 if (DependingInstructions.size() != 1)
3280 CallInst *Autorelease =
3281 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3284 InstructionClass AutoreleaseClass =
3285 GetBasicInstructionClass(Autorelease);
3286 if (!IsAutorelease(AutoreleaseClass))
3288 if (GetObjCArg(Autorelease) != Arg)
3291 DependingInstructions.clear();
3294 // Check that there is nothing that can affect the reference
3295 // count between the autorelease and the retain.
3296 FindDependencies(CanChangeRetainCount, Arg,
3297 BB, Autorelease, DependingInstructions, Visited, PA);
3298 if (DependingInstructions.size() != 1)
3303 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3305 // Check that we found a retain with the same argument.
3307 !IsRetain(GetBasicInstructionClass(Retain)) ||
3308 GetObjCArg(Retain) != Arg)
3311 DependingInstructions.clear();
3314 // Convert the autorelease to an autoreleaseRV, since it's
3315 // returning the value.
3316 if (AutoreleaseClass == IC_Autorelease) {
3317 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3318 AutoreleaseClass = IC_AutoreleaseRV;
3321 // Check that there is nothing that can affect the reference
3322 // count between the retain and the call.
3323 // Note that Retain need not be in BB.
3324 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3325 DependingInstructions, Visited, PA);
3326 if (DependingInstructions.size() != 1)
3331 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3333 // Check that the pointer is the return value of the call.
3334 if (!Call || Arg != Call)
3337 // Check that the call is a regular call.
3338 InstructionClass Class = GetBasicInstructionClass(Call);
3339 if (Class != IC_CallOrUser && Class != IC_Call)
3342 // If so, we can zap the retain and autorelease.
3345 EraseInstruction(Retain);
3346 EraseInstruction(Autorelease);
3352 DependingInstructions.clear();
3357 bool ObjCARCOpt::doInitialization(Module &M) {
3361 Run = ModuleHasARC(M);
3365 // Identify the imprecise release metadata kind.
3366 ImpreciseReleaseMDKind =
3367 M.getContext().getMDKindID("clang.imprecise_release");
3368 CopyOnEscapeMDKind =
3369 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3371 // Intuitively, objc_retain and others are nocapture, however in practice
3372 // they are not, because they return their argument value. And objc_release
3373 // calls finalizers.
3375 // These are initialized lazily.
3377 AutoreleaseRVCallee = 0;
3380 RetainBlockCallee = 0;
3381 AutoreleaseCallee = 0;
3386 bool ObjCARCOpt::runOnFunction(Function &F) {
3390 // If nothing in the Module uses ARC, don't do anything.
3396 PA.setAA(&getAnalysis<AliasAnalysis>());
3398 // This pass performs several distinct transformations. As a compile-time aid
3399 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3400 // library functions aren't declared.
3402 // Preliminary optimizations. This also computs UsedInThisFunction.
3403 OptimizeIndividualCalls(F);
3405 // Optimizations for weak pointers.
3406 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3407 (1 << IC_LoadWeakRetained) |
3408 (1 << IC_StoreWeak) |
3409 (1 << IC_InitWeak) |
3410 (1 << IC_CopyWeak) |
3411 (1 << IC_MoveWeak) |
3412 (1 << IC_DestroyWeak)))
3413 OptimizeWeakCalls(F);
3415 // Optimizations for retain+release pairs.
3416 if (UsedInThisFunction & ((1 << IC_Retain) |
3417 (1 << IC_RetainRV) |
3418 (1 << IC_RetainBlock)))
3419 if (UsedInThisFunction & (1 << IC_Release))
3420 // Run OptimizeSequences until it either stops making changes or
3421 // no retain+release pair nesting is detected.
3422 while (OptimizeSequences(F)) {}
3424 // Optimizations if objc_autorelease is used.
3425 if (UsedInThisFunction &
3426 ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
3432 void ObjCARCOpt::releaseMemory() {
3436 //===----------------------------------------------------------------------===//
3438 //===----------------------------------------------------------------------===//
3440 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
3441 // dominated by single calls.
3443 #include "llvm/Operator.h"
3444 #include "llvm/InlineAsm.h"
3445 #include "llvm/Analysis/Dominators.h"
3447 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3450 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3451 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3452 class ObjCARCContract : public FunctionPass {
3456 ProvenanceAnalysis PA;
3458 /// Run - A flag indicating whether this optimization pass should run.
3461 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3462 /// functions, for use in creating calls to them. These are initialized
3463 /// lazily to avoid cluttering up the Module with unused declarations.
3464 Constant *StoreStrongCallee,
3465 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3467 /// RetainRVMarker - The inline asm string to insert between calls and
3468 /// RetainRV calls to make the optimization work on targets which need it.
3469 const MDString *RetainRVMarker;
3471 Constant *getStoreStrongCallee(Module *M);
3472 Constant *getRetainAutoreleaseCallee(Module *M);
3473 Constant *getRetainAutoreleaseRVCallee(Module *M);
3475 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3476 InstructionClass Class,
3477 SmallPtrSet<Instruction *, 4>
3478 &DependingInstructions,
3479 SmallPtrSet<const BasicBlock *, 4>
3482 void ContractRelease(Instruction *Release,
3483 inst_iterator &Iter);
3485 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3486 virtual bool doInitialization(Module &M);
3487 virtual bool runOnFunction(Function &F);
3491 ObjCARCContract() : FunctionPass(ID) {
3492 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3497 char ObjCARCContract::ID = 0;
3498 INITIALIZE_PASS_BEGIN(ObjCARCContract,
3499 "objc-arc-contract", "ObjC ARC contraction", false, false)
3500 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3501 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3502 INITIALIZE_PASS_END(ObjCARCContract,
3503 "objc-arc-contract", "ObjC ARC contraction", false, false)
3505 Pass *llvm::createObjCARCContractPass() {
3506 return new ObjCARCContract();
3509 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3510 AU.addRequired<AliasAnalysis>();
3511 AU.addRequired<DominatorTree>();
3512 AU.setPreservesCFG();
3515 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3516 if (!StoreStrongCallee) {
3517 LLVMContext &C = M->getContext();
3518 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3519 Type *I8XX = PointerType::getUnqual(I8X);
3520 std::vector<Type *> Params;
3521 Params.push_back(I8XX);
3522 Params.push_back(I8X);
3524 AttrListPtr Attributes;
3525 Attributes.addAttr(~0u, Attribute::NoUnwind);
3526 Attributes.addAttr(1, Attribute::NoCapture);
3529 M->getOrInsertFunction(
3531 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3534 return StoreStrongCallee;
3537 Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3538 if (!RetainAutoreleaseCallee) {
3539 LLVMContext &C = M->getContext();
3540 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3541 std::vector<Type *> Params;
3542 Params.push_back(I8X);
3544 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3545 AttrListPtr Attributes;
3546 Attributes.addAttr(~0u, Attribute::NoUnwind);
3547 RetainAutoreleaseCallee =
3548 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3550 return RetainAutoreleaseCallee;
3553 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3554 if (!RetainAutoreleaseRVCallee) {
3555 LLVMContext &C = M->getContext();
3556 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3557 std::vector<Type *> Params;
3558 Params.push_back(I8X);
3560 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3561 AttrListPtr Attributes;
3562 Attributes.addAttr(~0u, Attribute::NoUnwind);
3563 RetainAutoreleaseRVCallee =
3564 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3567 return RetainAutoreleaseRVCallee;
3570 /// ContractAutorelease - Merge an autorelease with a retain into a fused
3573 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3574 InstructionClass Class,
3575 SmallPtrSet<Instruction *, 4>
3576 &DependingInstructions,
3577 SmallPtrSet<const BasicBlock *, 4>
3579 const Value *Arg = GetObjCArg(Autorelease);
3581 // Check that there are no instructions between the retain and the autorelease
3582 // (such as an autorelease_pop) which may change the count.
3583 CallInst *Retain = 0;
3584 if (Class == IC_AutoreleaseRV)
3585 FindDependencies(RetainAutoreleaseRVDep, Arg,
3586 Autorelease->getParent(), Autorelease,
3587 DependingInstructions, Visited, PA);
3589 FindDependencies(RetainAutoreleaseDep, Arg,
3590 Autorelease->getParent(), Autorelease,
3591 DependingInstructions, Visited, PA);
3594 if (DependingInstructions.size() != 1) {
3595 DependingInstructions.clear();
3599 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3600 DependingInstructions.clear();
3603 GetBasicInstructionClass(Retain) != IC_Retain ||
3604 GetObjCArg(Retain) != Arg)
3610 if (Class == IC_AutoreleaseRV)
3611 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3613 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3615 EraseInstruction(Autorelease);
3619 /// ContractRelease - Attempt to merge an objc_release with a store, load, and
3620 /// objc_retain to form an objc_storeStrong. This can be a little tricky because
3621 /// the instructions don't always appear in order, and there may be unrelated
3622 /// intervening instructions.
3623 void ObjCARCContract::ContractRelease(Instruction *Release,
3624 inst_iterator &Iter) {
3625 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
3626 if (!Load || !Load->isSimple()) return;
3628 // For now, require everything to be in one basic block.
3629 BasicBlock *BB = Release->getParent();
3630 if (Load->getParent() != BB) return;
3632 // Walk down to find the store.
3633 BasicBlock::iterator I = Load, End = BB->end();
3635 AliasAnalysis::Location Loc = AA->getLocation(Load);
3638 IsRetain(GetBasicInstructionClass(I)) ||
3639 !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
3641 StoreInst *Store = dyn_cast<StoreInst>(I);
3642 if (!Store || !Store->isSimple()) return;
3643 if (Store->getPointerOperand() != Loc.Ptr) return;
3645 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3647 // Walk up to find the retain.
3649 BasicBlock::iterator Begin = BB->begin();
3650 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3652 Instruction *Retain = I;
3653 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3654 if (GetObjCArg(Retain) != New) return;
3659 LLVMContext &C = Release->getContext();
3660 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3661 Type *I8XX = PointerType::getUnqual(I8X);
3663 Value *Args[] = { Load->getPointerOperand(), New };
3664 if (Args[0]->getType() != I8XX)
3665 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3666 if (Args[1]->getType() != I8X)
3667 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3668 CallInst *StoreStrong =
3669 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
3671 StoreStrong->setDoesNotThrow();
3672 StoreStrong->setDebugLoc(Store->getDebugLoc());
3674 if (&*Iter == Store) ++Iter;
3675 Store->eraseFromParent();
3676 Release->eraseFromParent();
3677 EraseInstruction(Retain);
3678 if (Load->use_empty())
3679 Load->eraseFromParent();
3682 bool ObjCARCContract::doInitialization(Module &M) {
3683 Run = ModuleHasARC(M);
3687 // These are initialized lazily.
3688 StoreStrongCallee = 0;
3689 RetainAutoreleaseCallee = 0;
3690 RetainAutoreleaseRVCallee = 0;
3692 // Initialize RetainRVMarker.
3694 if (NamedMDNode *NMD =
3695 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3696 if (NMD->getNumOperands() == 1) {
3697 const MDNode *N = NMD->getOperand(0);
3698 if (N->getNumOperands() == 1)
3699 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
3706 bool ObjCARCContract::runOnFunction(Function &F) {
3710 // If nothing in the Module uses ARC, don't do anything.
3715 AA = &getAnalysis<AliasAnalysis>();
3716 DT = &getAnalysis<DominatorTree>();
3718 PA.setAA(&getAnalysis<AliasAnalysis>());
3720 // For ObjC library calls which return their argument, replace uses of the
3721 // argument with uses of the call return value, if it dominates the use. This
3722 // reduces register pressure.
3723 SmallPtrSet<Instruction *, 4> DependingInstructions;
3724 SmallPtrSet<const BasicBlock *, 4> Visited;
3725 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3726 Instruction *Inst = &*I++;
3728 // Only these library routines return their argument. In particular,
3729 // objc_retainBlock does not necessarily return its argument.
3730 InstructionClass Class = GetBasicInstructionClass(Inst);
3733 case IC_FusedRetainAutorelease:
3734 case IC_FusedRetainAutoreleaseRV:
3736 case IC_Autorelease:
3737 case IC_AutoreleaseRV:
3738 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
3742 // If we're compiling for a target which needs a special inline-asm
3743 // marker to do the retainAutoreleasedReturnValue optimization,
3745 if (!RetainRVMarker)
3747 BasicBlock::iterator BBI = Inst;
3749 while (isNoopInstruction(BBI)) --BBI;
3750 if (&*BBI == GetObjCArg(Inst)) {
3752 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
3753 /*isVarArg=*/false),
3754 RetainRVMarker->getString(),
3755 /*Constraints=*/"", /*hasSideEffects=*/true);
3756 CallInst::Create(IA, "", Inst);
3761 // objc_initWeak(p, null) => *p = null
3762 CallInst *CI = cast<CallInst>(Inst);
3763 if (isNullOrUndef(CI->getArgOperand(1))) {
3765 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
3767 new StoreInst(Null, CI->getArgOperand(0), CI);
3768 CI->replaceAllUsesWith(Null);
3769 CI->eraseFromParent();
3774 ContractRelease(Inst, I);
3780 // Don't use GetObjCArg because we don't want to look through bitcasts
3781 // and such; to do the replacement, the argument must have type i8*.
3782 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
3784 // If we're compiling bugpointed code, don't get in trouble.
3785 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
3787 // Look through the uses of the pointer.
3788 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
3790 Use &U = UI.getUse();
3791 unsigned OperandNo = UI.getOperandNo();
3792 ++UI; // Increment UI now, because we may unlink its element.
3793 if (Instruction *UserInst = dyn_cast<Instruction>(U.getUser()))
3794 if (Inst != UserInst && DT->dominates(Inst, UserInst)) {
3796 Instruction *Replacement = Inst;
3797 Type *UseTy = U.get()->getType();
3798 if (PHINode *PHI = dyn_cast<PHINode>(UserInst)) {
3799 // For PHI nodes, insert the bitcast in the predecessor block.
3801 PHINode::getIncomingValueNumForOperand(OperandNo);
3803 PHI->getIncomingBlock(ValNo);
3804 if (Replacement->getType() != UseTy)
3805 Replacement = new BitCastInst(Replacement, UseTy, "",
3807 for (unsigned i = 0, e = PHI->getNumIncomingValues();
3809 if (PHI->getIncomingBlock(i) == BB) {
3810 // Keep the UI iterator valid.
3811 if (&PHI->getOperandUse(
3812 PHINode::getOperandNumForIncomingValue(i)) ==
3815 PHI->setIncomingValue(i, Replacement);
3818 if (Replacement->getType() != UseTy)
3819 Replacement = new BitCastInst(Replacement, UseTy, "", UserInst);
3825 // If Arg is a no-op casted pointer, strip one level of casts and
3827 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
3828 Arg = BI->getOperand(0);
3829 else if (isa<GEPOperator>(Arg) &&
3830 cast<GEPOperator>(Arg)->hasAllZeroIndices())
3831 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
3832 else if (isa<GlobalAlias>(Arg) &&
3833 !cast<GlobalAlias>(Arg)->mayBeOverridden())
3834 Arg = cast<GlobalAlias>(Arg)->getAliasee();