1 //===- ObjCARC.cpp - ObjC ARC Optimization --------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines ObjC ARC optimizations. ARC stands for
11 // Automatic Reference Counting and is a system for managing reference counts
12 // for objects in Objective C.
14 // The optimizations performed include elimination of redundant, partially
15 // redundant, and inconsequential reference count operations, elimination of
16 // redundant weak pointer operations, pattern-matching and replacement of
17 // low-level operations into higher-level operations, and numerous minor
20 // This file also defines a simple ARC-aware AliasAnalysis.
22 // WARNING: This file knows about certain library functions. It recognizes them
23 // by name, and hardwires knowedge of their semantics.
25 // WARNING: This file knows about how certain Objective-C library functions are
26 // used. Naive LLVM IR transformations which would otherwise be
27 // behavior-preserving may break these assumptions.
29 //===----------------------------------------------------------------------===//
31 #define DEBUG_TYPE "objc-arc"
32 #include "llvm/Function.h"
33 #include "llvm/Intrinsics.h"
34 #include "llvm/GlobalVariable.h"
35 #include "llvm/DerivedTypes.h"
36 #include "llvm/Module.h"
37 #include "llvm/Analysis/ValueTracking.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 #include "llvm/Support/CallSite.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/ADT/StringSwitch.h"
42 #include "llvm/ADT/DenseMap.h"
43 #include "llvm/ADT/STLExtras.h"
46 // A handy option to enable/disable all optimizations in this file.
47 static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
49 //===----------------------------------------------------------------------===//
51 //===----------------------------------------------------------------------===//
54 /// MapVector - An associative container with fast insertion-order
55 /// (deterministic) iteration over its elements. Plus the special
57 template<class KeyT, class ValueT>
59 /// Map - Map keys to indices in Vector.
60 typedef DenseMap<KeyT, size_t> MapTy;
63 /// Vector - Keys and values.
64 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
68 typedef typename VectorTy::iterator iterator;
69 typedef typename VectorTy::const_iterator const_iterator;
70 iterator begin() { return Vector.begin(); }
71 iterator end() { return Vector.end(); }
72 const_iterator begin() const { return Vector.begin(); }
73 const_iterator end() const { return Vector.end(); }
77 assert(Vector.size() >= Map.size()); // May differ due to blotting.
78 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
80 assert(I->second < Vector.size());
81 assert(Vector[I->second].first == I->first);
83 for (typename VectorTy::const_iterator I = Vector.begin(),
84 E = Vector.end(); I != E; ++I)
86 (Map.count(I->first) &&
87 Map[I->first] == size_t(I - Vector.begin())));
91 ValueT &operator[](const KeyT &Arg) {
92 std::pair<typename MapTy::iterator, bool> Pair =
93 Map.insert(std::make_pair(Arg, size_t(0)));
95 size_t Num = Vector.size();
96 Pair.first->second = Num;
97 Vector.push_back(std::make_pair(Arg, ValueT()));
98 return Vector[Num].second;
100 return Vector[Pair.first->second].second;
103 std::pair<iterator, bool>
104 insert(const std::pair<KeyT, ValueT> &InsertPair) {
105 std::pair<typename MapTy::iterator, bool> Pair =
106 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
108 size_t Num = Vector.size();
109 Pair.first->second = Num;
110 Vector.push_back(InsertPair);
111 return std::make_pair(Vector.begin() + Num, true);
113 return std::make_pair(Vector.begin() + Pair.first->second, false);
116 const_iterator find(const KeyT &Key) const {
117 typename MapTy::const_iterator It = Map.find(Key);
118 if (It == Map.end()) return Vector.end();
119 return Vector.begin() + It->second;
122 /// blot - This is similar to erase, but instead of removing the element
123 /// from the vector, it just zeros out the key in the vector. This leaves
124 /// iterators intact, but clients must be prepared for zeroed-out keys when
126 void blot(const KeyT &Key) {
127 typename MapTy::iterator It = Map.find(Key);
128 if (It == Map.end()) return;
129 Vector[It->second].first = KeyT();
140 //===----------------------------------------------------------------------===//
142 //===----------------------------------------------------------------------===//
145 /// InstructionClass - A simple classification for instructions.
146 enum InstructionClass {
147 IC_Retain, ///< objc_retain
148 IC_RetainRV, ///< objc_retainAutoreleasedReturnValue
149 IC_RetainBlock, ///< objc_retainBlock
150 IC_Release, ///< objc_release
151 IC_Autorelease, ///< objc_autorelease
152 IC_AutoreleaseRV, ///< objc_autoreleaseReturnValue
153 IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
154 IC_AutoreleasepoolPop, ///< objc_autoreleasePoolPop
155 IC_NoopCast, ///< objc_retainedObject, etc.
156 IC_FusedRetainAutorelease, ///< objc_retainAutorelease
157 IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
158 IC_LoadWeakRetained, ///< objc_loadWeakRetained (primitive)
159 IC_StoreWeak, ///< objc_storeWeak (primitive)
160 IC_InitWeak, ///< objc_initWeak (derived)
161 IC_LoadWeak, ///< objc_loadWeak (derived)
162 IC_MoveWeak, ///< objc_moveWeak (derived)
163 IC_CopyWeak, ///< objc_copyWeak (derived)
164 IC_DestroyWeak, ///< objc_destroyWeak (derived)
165 IC_CallOrUser, ///< could call objc_release and/or "use" pointers
166 IC_Call, ///< could call objc_release
167 IC_User, ///< could "use" a pointer
168 IC_None ///< anything else
172 /// IsPotentialUse - Test whether the given value is possible a
173 /// reference-counted pointer.
174 static bool IsPotentialUse(const Value *Op) {
175 // Pointers to static or stack storage are not reference-counted pointers.
176 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
178 // Special arguments are not reference-counted.
179 if (const Argument *Arg = dyn_cast<Argument>(Op))
180 if (Arg->hasByValAttr() ||
181 Arg->hasNestAttr() ||
182 Arg->hasStructRetAttr())
184 // Only consider values with pointer types.
185 // It seemes intuitive to exclude function pointer types as well, since
186 // functions are never reference-counted, however clang occasionally
187 // bitcasts reference-counted pointers to function-pointer type
189 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
192 // Conservatively assume anything else is a potential use.
196 /// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind
197 /// of construct CS is.
198 static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
199 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
201 if (IsPotentialUse(*I))
202 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
204 return CS.onlyReadsMemory() ? IC_None : IC_Call;
207 /// GetFunctionClass - Determine if F is one of the special known Functions.
208 /// If it isn't, return IC_CallOrUser.
209 static InstructionClass GetFunctionClass(const Function *F) {
210 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
214 return StringSwitch<InstructionClass>(F->getName())
215 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
216 .Default(IC_CallOrUser);
219 const Argument *A0 = AI++;
221 // Argument is a pointer.
222 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
223 Type *ETy = PTy->getElementType();
225 if (ETy->isIntegerTy(8))
226 return StringSwitch<InstructionClass>(F->getName())
227 .Case("objc_retain", IC_Retain)
228 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
229 .Case("objc_retainBlock", IC_RetainBlock)
230 .Case("objc_release", IC_Release)
231 .Case("objc_autorelease", IC_Autorelease)
232 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
233 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
234 .Case("objc_retainedObject", IC_NoopCast)
235 .Case("objc_unretainedObject", IC_NoopCast)
236 .Case("objc_unretainedPointer", IC_NoopCast)
237 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
238 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
239 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
240 .Default(IC_CallOrUser);
243 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
244 if (Pte->getElementType()->isIntegerTy(8))
245 return StringSwitch<InstructionClass>(F->getName())
246 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
247 .Case("objc_loadWeak", IC_LoadWeak)
248 .Case("objc_destroyWeak", IC_DestroyWeak)
249 .Default(IC_CallOrUser);
252 // Two arguments, first is i8**.
253 const Argument *A1 = AI++;
255 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
256 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
257 if (Pte->getElementType()->isIntegerTy(8))
258 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
259 Type *ETy1 = PTy1->getElementType();
260 // Second argument is i8*
261 if (ETy1->isIntegerTy(8))
262 return StringSwitch<InstructionClass>(F->getName())
263 .Case("objc_storeWeak", IC_StoreWeak)
264 .Case("objc_initWeak", IC_InitWeak)
265 .Default(IC_CallOrUser);
266 // Second argument is i8**.
267 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
268 if (Pte1->getElementType()->isIntegerTy(8))
269 return StringSwitch<InstructionClass>(F->getName())
270 .Case("objc_moveWeak", IC_MoveWeak)
271 .Case("objc_copyWeak", IC_CopyWeak)
272 .Default(IC_CallOrUser);
276 return IC_CallOrUser;
279 /// GetInstructionClass - Determine what kind of construct V is.
280 static InstructionClass GetInstructionClass(const Value *V) {
281 if (const Instruction *I = dyn_cast<Instruction>(V)) {
282 // Any instruction other than bitcast and gep with a pointer operand have a
283 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
284 // to a subsequent use, rather than using it themselves, in this sense.
285 // As a short cut, several other opcodes are known to have no pointer
286 // operands of interest. And ret is never followed by a release, so it's
287 // not interesting to examine.
288 switch (I->getOpcode()) {
289 case Instruction::Call: {
290 const CallInst *CI = cast<CallInst>(I);
291 // Check for calls to special functions.
292 if (const Function *F = CI->getCalledFunction()) {
293 InstructionClass Class = GetFunctionClass(F);
294 if (Class != IC_CallOrUser)
297 // None of the intrinsic functions do objc_release. For intrinsics, the
298 // only question is whether or not they may be users.
299 switch (F->getIntrinsicID()) {
301 case Intrinsic::bswap: case Intrinsic::ctpop:
302 case Intrinsic::ctlz: case Intrinsic::cttz:
303 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
304 case Intrinsic::stacksave: case Intrinsic::stackrestore:
305 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
306 // Don't let dbg info affect our results.
307 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
308 // Short cut: Some intrinsics obviously don't use ObjC pointers.
311 for (Function::const_arg_iterator AI = F->arg_begin(),
312 AE = F->arg_end(); AI != AE; ++AI)
313 if (IsPotentialUse(AI))
318 return GetCallSiteClass(CI);
320 case Instruction::Invoke:
321 return GetCallSiteClass(cast<InvokeInst>(I));
322 case Instruction::BitCast:
323 case Instruction::GetElementPtr:
324 case Instruction::Select: case Instruction::PHI:
325 case Instruction::Ret: case Instruction::Br:
326 case Instruction::Switch: case Instruction::IndirectBr:
327 case Instruction::Alloca: case Instruction::VAArg:
328 case Instruction::Add: case Instruction::FAdd:
329 case Instruction::Sub: case Instruction::FSub:
330 case Instruction::Mul: case Instruction::FMul:
331 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
332 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
333 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
334 case Instruction::And: case Instruction::Or: case Instruction::Xor:
335 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
336 case Instruction::IntToPtr: case Instruction::FCmp:
337 case Instruction::FPTrunc: case Instruction::FPExt:
338 case Instruction::FPToUI: case Instruction::FPToSI:
339 case Instruction::UIToFP: case Instruction::SIToFP:
340 case Instruction::InsertElement: case Instruction::ExtractElement:
341 case Instruction::ShuffleVector:
342 case Instruction::ExtractValue:
344 case Instruction::ICmp:
345 // Comparing a pointer with null, or any other constant, isn't an
346 // interesting use, because we don't care what the pointer points to, or
347 // about the values of any other dynamic reference-counted pointers.
348 if (IsPotentialUse(I->getOperand(1)))
352 // For anything else, check all the operands.
353 // Note that this includes both operands of a Store: while the first
354 // operand isn't actually being dereferenced, it is being stored to
355 // memory where we can no longer track who might read it and dereference
356 // it, so we have to consider it potentially used.
357 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
359 if (IsPotentialUse(*OI))
364 // Otherwise, it's totally inert for ARC purposes.
368 /// GetBasicInstructionClass - Determine what kind of construct V is. This is
369 /// similar to GetInstructionClass except that it only detects objc runtine
370 /// calls. This allows it to be faster.
371 static InstructionClass GetBasicInstructionClass(const Value *V) {
372 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
373 if (const Function *F = CI->getCalledFunction())
374 return GetFunctionClass(F);
375 // Otherwise, be conservative.
376 return IC_CallOrUser;
379 // Otherwise, be conservative.
380 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
383 /// IsRetain - Test if the the given class is objc_retain or
385 static bool IsRetain(InstructionClass Class) {
386 return Class == IC_Retain ||
387 Class == IC_RetainRV;
390 /// IsAutorelease - Test if the the given class is objc_autorelease or
392 static bool IsAutorelease(InstructionClass Class) {
393 return Class == IC_Autorelease ||
394 Class == IC_AutoreleaseRV;
397 /// IsForwarding - Test if the given class represents instructions which return
398 /// their argument verbatim.
399 static bool IsForwarding(InstructionClass Class) {
400 // objc_retainBlock technically doesn't always return its argument
401 // verbatim, but it doesn't matter for our purposes here.
402 return Class == IC_Retain ||
403 Class == IC_RetainRV ||
404 Class == IC_Autorelease ||
405 Class == IC_AutoreleaseRV ||
406 Class == IC_RetainBlock ||
407 Class == IC_NoopCast;
410 /// IsNoopOnNull - Test if the given class represents instructions which do
411 /// nothing if passed a null pointer.
412 static bool IsNoopOnNull(InstructionClass Class) {
413 return Class == IC_Retain ||
414 Class == IC_RetainRV ||
415 Class == IC_Release ||
416 Class == IC_Autorelease ||
417 Class == IC_AutoreleaseRV ||
418 Class == IC_RetainBlock;
421 /// IsAlwaysTail - Test if the given class represents instructions which are
422 /// always safe to mark with the "tail" keyword.
423 static bool IsAlwaysTail(InstructionClass Class) {
424 // IC_RetainBlock may be given a stack argument.
425 return Class == IC_Retain ||
426 Class == IC_RetainRV ||
427 Class == IC_Autorelease ||
428 Class == IC_AutoreleaseRV;
431 /// IsNoThrow - Test if the given class represents instructions which are always
432 /// safe to mark with the nounwind attribute..
433 static bool IsNoThrow(InstructionClass Class) {
434 // objc_retainBlock is not nounwind because it calls user copy constructors
435 // which could theoretically throw.
436 return Class == IC_Retain ||
437 Class == IC_RetainRV ||
438 Class == IC_Release ||
439 Class == IC_Autorelease ||
440 Class == IC_AutoreleaseRV ||
441 Class == IC_AutoreleasepoolPush ||
442 Class == IC_AutoreleasepoolPop;
445 /// EraseInstruction - Erase the given instruction. ObjC calls return their
446 /// argument verbatim, so if it's such a call and the return value has users,
447 /// replace them with the argument value.
448 static void EraseInstruction(Instruction *CI) {
449 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
451 bool Unused = CI->use_empty();
454 // Replace the return value with the argument.
455 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
456 "Can't delete non-forwarding instruction with users!");
457 CI->replaceAllUsesWith(OldArg);
460 CI->eraseFromParent();
463 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
466 /// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
467 /// also knows how to look through objc_retain and objc_autorelease calls, which
468 /// we know to return their argument verbatim.
469 static const Value *GetUnderlyingObjCPtr(const Value *V) {
471 V = GetUnderlyingObject(V);
472 if (!IsForwarding(GetBasicInstructionClass(V)))
474 V = cast<CallInst>(V)->getArgOperand(0);
480 /// StripPointerCastsAndObjCCalls - This is a wrapper around
481 /// Value::stripPointerCasts which also knows how to look through objc_retain
482 /// and objc_autorelease calls, which we know to return their argument verbatim.
483 static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
485 V = V->stripPointerCasts();
486 if (!IsForwarding(GetBasicInstructionClass(V)))
488 V = cast<CallInst>(V)->getArgOperand(0);
493 /// StripPointerCastsAndObjCCalls - This is a wrapper around
494 /// Value::stripPointerCasts which also knows how to look through objc_retain
495 /// and objc_autorelease calls, which we know to return their argument verbatim.
496 static Value *StripPointerCastsAndObjCCalls(Value *V) {
498 V = V->stripPointerCasts();
499 if (!IsForwarding(GetBasicInstructionClass(V)))
501 V = cast<CallInst>(V)->getArgOperand(0);
506 /// GetObjCArg - Assuming the given instruction is one of the special calls such
507 /// as objc_retain or objc_release, return the argument value, stripped of no-op
508 /// casts and forwarding calls.
509 static Value *GetObjCArg(Value *Inst) {
510 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
513 /// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
514 /// isObjCIdentifiedObject, except that it uses special knowledge of
515 /// ObjC conventions...
516 static bool IsObjCIdentifiedObject(const Value *V) {
517 // Assume that call results and arguments have their own "provenance".
518 // Constants (including GlobalVariables) and Allocas are never
519 // reference-counted.
520 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
521 isa<Argument>(V) || isa<Constant>(V) ||
525 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
526 const Value *Pointer =
527 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
528 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
529 // A constant pointer can't be pointing to an object on the heap. It may
530 // be reference-counted, but it won't be deleted.
531 if (GV->isConstant())
533 StringRef Name = GV->getName();
534 // These special variables are known to hold values which are not
535 // reference-counted pointers.
536 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
537 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
538 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
539 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
540 Name.startswith("\01l_objc_msgSend_fixup_"))
548 /// FindSingleUseIdentifiedObject - This is similar to
549 /// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
550 /// with multiple uses.
551 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
552 if (Arg->hasOneUse()) {
553 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
554 return FindSingleUseIdentifiedObject(BC->getOperand(0));
555 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
556 if (GEP->hasAllZeroIndices())
557 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
558 if (IsForwarding(GetBasicInstructionClass(Arg)))
559 return FindSingleUseIdentifiedObject(
560 cast<CallInst>(Arg)->getArgOperand(0));
561 if (!IsObjCIdentifiedObject(Arg))
566 // If we found an identifiable object but it has multiple uses, but they
567 // are trivial uses, we can still consider this to be a single-use
569 if (IsObjCIdentifiedObject(Arg)) {
570 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
573 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
583 /// ModuleHasARC - Test if the given module looks interesting to run ARC
585 static bool ModuleHasARC(const Module &M) {
587 M.getNamedValue("objc_retain") ||
588 M.getNamedValue("objc_release") ||
589 M.getNamedValue("objc_autorelease") ||
590 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
591 M.getNamedValue("objc_retainBlock") ||
592 M.getNamedValue("objc_autoreleaseReturnValue") ||
593 M.getNamedValue("objc_autoreleasePoolPush") ||
594 M.getNamedValue("objc_loadWeakRetained") ||
595 M.getNamedValue("objc_loadWeak") ||
596 M.getNamedValue("objc_destroyWeak") ||
597 M.getNamedValue("objc_storeWeak") ||
598 M.getNamedValue("objc_initWeak") ||
599 M.getNamedValue("objc_moveWeak") ||
600 M.getNamedValue("objc_copyWeak") ||
601 M.getNamedValue("objc_retainedObject") ||
602 M.getNamedValue("objc_unretainedObject") ||
603 M.getNamedValue("objc_unretainedPointer");
606 /// DoesObjCBlockEscape - Test whether the given pointer, which is an
607 /// Objective C block pointer, does not "escape". This differs from regular
608 /// escape analysis in that a use as an argument to a call is not considered
610 static bool DoesObjCBlockEscape(const Value *BlockPtr) {
611 // Walk the def-use chains.
612 SmallVector<const Value *, 4> Worklist;
613 Worklist.push_back(BlockPtr);
615 const Value *V = Worklist.pop_back_val();
616 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
618 const User *UUser = *UI;
619 // Special - Use by a call (callee or argument) is not considered
621 if (isa<CallInst>(UUser) || isa<InvokeInst>(UUser))
623 // Use by an instruction which copies the value is an escape if the
624 // result is an escape.
625 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
626 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
627 Worklist.push_back(UUser);
630 // Use by a load is not an escape.
631 if (isa<LoadInst>(UUser))
633 // Use by a store is not an escape if the use is the address.
634 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
635 if (V != SI->getValueOperand())
637 // Otherwise, conservatively assume an escape.
640 } while (!Worklist.empty());
646 //===----------------------------------------------------------------------===//
647 // ARC AliasAnalysis.
648 //===----------------------------------------------------------------------===//
650 #include "llvm/Pass.h"
651 #include "llvm/Analysis/AliasAnalysis.h"
652 #include "llvm/Analysis/Passes.h"
655 /// ObjCARCAliasAnalysis - This is a simple alias analysis
656 /// implementation that uses knowledge of ARC constructs to answer queries.
658 /// TODO: This class could be generalized to know about other ObjC-specific
659 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
660 /// even though their offsets are dynamic.
661 class ObjCARCAliasAnalysis : public ImmutablePass,
662 public AliasAnalysis {
664 static char ID; // Class identification, replacement for typeinfo
665 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
666 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
670 virtual void initializePass() {
671 InitializeAliasAnalysis(this);
674 /// getAdjustedAnalysisPointer - This method is used when a pass implements
675 /// an analysis interface through multiple inheritance. If needed, it
676 /// should override this to adjust the this pointer as needed for the
677 /// specified pass info.
678 virtual void *getAdjustedAnalysisPointer(const void *PI) {
679 if (PI == &AliasAnalysis::ID)
680 return (AliasAnalysis*)this;
684 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
685 virtual AliasResult alias(const Location &LocA, const Location &LocB);
686 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
687 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
688 virtual ModRefBehavior getModRefBehavior(const Function *F);
689 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
690 const Location &Loc);
691 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
692 ImmutableCallSite CS2);
694 } // End of anonymous namespace
696 // Register this pass...
697 char ObjCARCAliasAnalysis::ID = 0;
698 INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
699 "ObjC-ARC-Based Alias Analysis", false, true, false)
701 ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
702 return new ObjCARCAliasAnalysis();
706 ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
707 AU.setPreservesAll();
708 AliasAnalysis::getAnalysisUsage(AU);
711 AliasAnalysis::AliasResult
712 ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
714 return AliasAnalysis::alias(LocA, LocB);
716 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
717 // precise alias query.
718 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
719 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
721 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
722 Location(SB, LocB.Size, LocB.TBAATag));
723 if (Result != MayAlias)
726 // If that failed, climb to the underlying object, including climbing through
727 // ObjC-specific no-ops, and try making an imprecise alias query.
728 const Value *UA = GetUnderlyingObjCPtr(SA);
729 const Value *UB = GetUnderlyingObjCPtr(SB);
730 if (UA != SA || UB != SB) {
731 Result = AliasAnalysis::alias(Location(UA), Location(UB));
732 // We can't use MustAlias or PartialAlias results here because
733 // GetUnderlyingObjCPtr may return an offsetted pointer value.
734 if (Result == NoAlias)
738 // If that failed, fail. We don't need to chain here, since that's covered
739 // by the earlier precise query.
744 ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
747 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
749 // First, strip off no-ops, including ObjC-specific no-ops, and try making
750 // a precise alias query.
751 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
752 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
756 // If that failed, climb to the underlying object, including climbing through
757 // ObjC-specific no-ops, and try making an imprecise alias query.
758 const Value *U = GetUnderlyingObjCPtr(S);
760 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
762 // If that failed, fail. We don't need to chain here, since that's covered
763 // by the earlier precise query.
767 AliasAnalysis::ModRefBehavior
768 ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
769 // We have nothing to do. Just chain to the next AliasAnalysis.
770 return AliasAnalysis::getModRefBehavior(CS);
773 AliasAnalysis::ModRefBehavior
774 ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
776 return AliasAnalysis::getModRefBehavior(F);
778 switch (GetFunctionClass(F)) {
780 return DoesNotAccessMemory;
785 return AliasAnalysis::getModRefBehavior(F);
788 AliasAnalysis::ModRefResult
789 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
791 return AliasAnalysis::getModRefInfo(CS, Loc);
793 switch (GetBasicInstructionClass(CS.getInstruction())) {
797 case IC_AutoreleaseRV:
799 case IC_AutoreleasepoolPush:
800 case IC_FusedRetainAutorelease:
801 case IC_FusedRetainAutoreleaseRV:
802 // These functions don't access any memory visible to the compiler.
803 // Note that this doesn't include objc_retainBlock, becuase it updates
804 // pointers when it copies block data.
810 return AliasAnalysis::getModRefInfo(CS, Loc);
813 AliasAnalysis::ModRefResult
814 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
815 ImmutableCallSite CS2) {
816 // TODO: Theoretically we could check for dependencies between objc_* calls
817 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
818 return AliasAnalysis::getModRefInfo(CS1, CS2);
821 //===----------------------------------------------------------------------===//
823 //===----------------------------------------------------------------------===//
825 #include "llvm/Support/InstIterator.h"
826 #include "llvm/Transforms/Scalar.h"
829 /// ObjCARCExpand - Early ARC transformations.
830 class ObjCARCExpand : public FunctionPass {
831 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
832 virtual bool doInitialization(Module &M);
833 virtual bool runOnFunction(Function &F);
835 /// Run - A flag indicating whether this optimization pass should run.
840 ObjCARCExpand() : FunctionPass(ID) {
841 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
846 char ObjCARCExpand::ID = 0;
847 INITIALIZE_PASS(ObjCARCExpand,
848 "objc-arc-expand", "ObjC ARC expansion", false, false)
850 Pass *llvm::createObjCARCExpandPass() {
851 return new ObjCARCExpand();
854 void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
855 AU.setPreservesCFG();
858 bool ObjCARCExpand::doInitialization(Module &M) {
859 Run = ModuleHasARC(M);
863 bool ObjCARCExpand::runOnFunction(Function &F) {
867 // If nothing in the Module uses ARC, don't do anything.
871 bool Changed = false;
873 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
874 Instruction *Inst = &*I;
876 switch (GetBasicInstructionClass(Inst)) {
880 case IC_AutoreleaseRV:
881 case IC_FusedRetainAutorelease:
882 case IC_FusedRetainAutoreleaseRV:
883 // These calls return their argument verbatim, as a low-level
884 // optimization. However, this makes high-level optimizations
885 // harder. Undo any uses of this optimization that the front-end
886 // emitted here. We'll redo them in a later pass.
888 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
898 //===----------------------------------------------------------------------===//
899 // ARC autorelease pool elimination.
900 //===----------------------------------------------------------------------===//
902 #include "llvm/Constants.h"
905 /// ObjCARCAPElim - Autorelease pool elimination.
906 class ObjCARCAPElim : public ModulePass {
907 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
908 virtual bool runOnModule(Module &M);
910 bool MayAutorelease(CallSite CS, unsigned Depth = 0);
911 bool OptimizeBB(BasicBlock *BB);
915 ObjCARCAPElim() : ModulePass(ID) {
916 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
921 char ObjCARCAPElim::ID = 0;
922 INITIALIZE_PASS(ObjCARCAPElim,
924 "ObjC ARC autorelease pool elimination",
927 Pass *llvm::createObjCARCAPElimPass() {
928 return new ObjCARCAPElim();
931 void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
932 AU.setPreservesCFG();
935 /// MayAutorelease - Interprocedurally determine if calls made by the
936 /// given call site can possibly produce autoreleases.
937 bool ObjCARCAPElim::MayAutorelease(CallSite CS, unsigned Depth) {
938 if (Function *Callee = CS.getCalledFunction()) {
939 if (Callee->isDeclaration() || Callee->mayBeOverridden())
941 for (Function::iterator I = Callee->begin(), E = Callee->end();
944 for (BasicBlock::iterator J = BB->begin(), F = BB->end(); J != F; ++J)
945 if (CallSite JCS = CallSite(J))
946 // This recursion depth limit is arbitrary. It's just great
947 // enough to cover known interesting testcases.
949 !JCS.onlyReadsMemory() &&
950 MayAutorelease(JCS, Depth + 1))
959 bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
960 bool Changed = false;
962 Instruction *Push = 0;
963 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
964 Instruction *Inst = I++;
965 switch (GetBasicInstructionClass(Inst)) {
966 case IC_AutoreleasepoolPush:
969 case IC_AutoreleasepoolPop:
970 // If this pop matches a push and nothing in between can autorelease,
972 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
974 Inst->eraseFromParent();
975 Push->eraseFromParent();
980 if (MayAutorelease(CallSite(Inst)))
991 bool ObjCARCAPElim::runOnModule(Module &M) {
995 // If nothing in the Module uses ARC, don't do anything.
996 if (!ModuleHasARC(M))
999 // Find the llvm.global_ctors variable, as the first step in
1000 // identifying the global constructors.
1001 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1005 assert(GV->hasDefinitiveInitializer() &&
1006 "llvm.global_ctors is uncooperative!");
1008 bool Changed = false;
1010 // Dig the constructor functions out of GV's initializer.
1011 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1012 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1015 // llvm.global_ctors is an array of pairs where the second members
1016 // are constructor functions.
1017 Function *F = cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1018 // Only look at function definitions.
1019 if (F->isDeclaration())
1021 // Only look at functions with one basic block.
1022 if (llvm::next(F->begin()) != F->end())
1024 // Ok, a single-block constructor function definition. Try to optimize it.
1025 Changed |= OptimizeBB(F->begin());
1031 //===----------------------------------------------------------------------===//
1032 // ARC optimization.
1033 //===----------------------------------------------------------------------===//
1035 // TODO: On code like this:
1038 // stuff_that_cannot_release()
1039 // objc_autorelease(%x)
1040 // stuff_that_cannot_release()
1042 // stuff_that_cannot_release()
1043 // objc_autorelease(%x)
1045 // The second retain and autorelease can be deleted.
1047 // TODO: It should be possible to delete
1048 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
1049 // pairs if nothing is actually autoreleased between them. Also, autorelease
1050 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1051 // after inlining) can be turned into plain release calls.
1053 // TODO: Critical-edge splitting. If the optimial insertion point is
1054 // a critical edge, the current algorithm has to fail, because it doesn't
1055 // know how to split edges. It should be possible to make the optimizer
1056 // think in terms of edges, rather than blocks, and then split critical
1059 // TODO: OptimizeSequences could generalized to be Interprocedural.
1061 // TODO: Recognize that a bunch of other objc runtime calls have
1062 // non-escaping arguments and non-releasing arguments, and may be
1063 // non-autoreleasing.
1065 // TODO: Sink autorelease calls as far as possible. Unfortunately we
1066 // usually can't sink them past other calls, which would be the main
1067 // case where it would be useful.
1069 // TODO: The pointer returned from objc_loadWeakRetained is retained.
1071 // TODO: Delete release+retain pairs (rare).
1073 #include "llvm/GlobalAlias.h"
1074 #include "llvm/Constants.h"
1075 #include "llvm/LLVMContext.h"
1076 #include "llvm/Support/ErrorHandling.h"
1077 #include "llvm/Support/CFG.h"
1078 #include "llvm/ADT/Statistic.h"
1079 #include "llvm/ADT/SmallPtrSet.h"
1080 #include "llvm/ADT/DenseSet.h"
1082 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1083 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1084 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1085 STATISTIC(NumRets, "Number of return value forwarding "
1086 "retain+autoreleaes eliminated");
1087 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1088 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1091 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1092 /// uses many of the same techniques, except it uses special ObjC-specific
1093 /// reasoning about pointer relationships.
1094 class ProvenanceAnalysis {
1097 typedef std::pair<const Value *, const Value *> ValuePairTy;
1098 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1099 CachedResultsTy CachedResults;
1101 bool relatedCheck(const Value *A, const Value *B);
1102 bool relatedSelect(const SelectInst *A, const Value *B);
1103 bool relatedPHI(const PHINode *A, const Value *B);
1105 // Do not implement.
1106 void operator=(const ProvenanceAnalysis &);
1107 ProvenanceAnalysis(const ProvenanceAnalysis &);
1110 ProvenanceAnalysis() {}
1112 void setAA(AliasAnalysis *aa) { AA = aa; }
1114 AliasAnalysis *getAA() const { return AA; }
1116 bool related(const Value *A, const Value *B);
1119 CachedResults.clear();
1124 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1125 // If the values are Selects with the same condition, we can do a more precise
1126 // check: just check for relations between the values on corresponding arms.
1127 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
1128 if (A->getCondition() == SB->getCondition()) {
1129 if (related(A->getTrueValue(), SB->getTrueValue()))
1131 if (related(A->getFalseValue(), SB->getFalseValue()))
1136 // Check both arms of the Select node individually.
1137 if (related(A->getTrueValue(), B))
1139 if (related(A->getFalseValue(), B))
1142 // The arms both checked out.
1146 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1147 // If the values are PHIs in the same block, we can do a more precise as well
1148 // as efficient check: just check for relations between the values on
1149 // corresponding edges.
1150 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1151 if (PNB->getParent() == A->getParent()) {
1152 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1153 if (related(A->getIncomingValue(i),
1154 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1159 // Check each unique source of the PHI node against B.
1160 SmallPtrSet<const Value *, 4> UniqueSrc;
1161 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1162 const Value *PV1 = A->getIncomingValue(i);
1163 if (UniqueSrc.insert(PV1) && related(PV1, B))
1167 // All of the arms checked out.
1171 /// isStoredObjCPointer - Test if the value of P, or any value covered by its
1172 /// provenance, is ever stored within the function (not counting callees).
1173 static bool isStoredObjCPointer(const Value *P) {
1174 SmallPtrSet<const Value *, 8> Visited;
1175 SmallVector<const Value *, 8> Worklist;
1176 Worklist.push_back(P);
1179 P = Worklist.pop_back_val();
1180 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1182 const User *Ur = *UI;
1183 if (isa<StoreInst>(Ur)) {
1184 if (UI.getOperandNo() == 0)
1185 // The pointer is stored.
1187 // The pointed is stored through.
1190 if (isa<CallInst>(Ur))
1191 // The pointer is passed as an argument, ignore this.
1193 if (isa<PtrToIntInst>(P))
1194 // Assume the worst.
1196 if (Visited.insert(Ur))
1197 Worklist.push_back(Ur);
1199 } while (!Worklist.empty());
1201 // Everything checked out.
1205 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1206 // Skip past provenance pass-throughs.
1207 A = GetUnderlyingObjCPtr(A);
1208 B = GetUnderlyingObjCPtr(B);
1214 // Ask regular AliasAnalysis, for a first approximation.
1215 switch (AA->alias(A, B)) {
1216 case AliasAnalysis::NoAlias:
1218 case AliasAnalysis::MustAlias:
1219 case AliasAnalysis::PartialAlias:
1221 case AliasAnalysis::MayAlias:
1225 bool AIsIdentified = IsObjCIdentifiedObject(A);
1226 bool BIsIdentified = IsObjCIdentifiedObject(B);
1228 // An ObjC-Identified object can't alias a load if it is never locally stored.
1229 if (AIsIdentified) {
1230 if (BIsIdentified) {
1231 // If both pointers have provenance, they can be directly compared.
1235 if (isa<LoadInst>(B))
1236 return isStoredObjCPointer(A);
1239 if (BIsIdentified && isa<LoadInst>(A))
1240 return isStoredObjCPointer(B);
1243 // Special handling for PHI and Select.
1244 if (const PHINode *PN = dyn_cast<PHINode>(A))
1245 return relatedPHI(PN, B);
1246 if (const PHINode *PN = dyn_cast<PHINode>(B))
1247 return relatedPHI(PN, A);
1248 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1249 return relatedSelect(S, B);
1250 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1251 return relatedSelect(S, A);
1257 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1258 // Begin by inserting a conservative value into the map. If the insertion
1259 // fails, we have the answer already. If it succeeds, leave it there until we
1260 // compute the real answer to guard against recursive queries.
1261 if (A > B) std::swap(A, B);
1262 std::pair<CachedResultsTy::iterator, bool> Pair =
1263 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1265 return Pair.first->second;
1267 bool Result = relatedCheck(A, B);
1268 CachedResults[ValuePairTy(A, B)] = Result;
1273 // Sequence - A sequence of states that a pointer may go through in which an
1274 // objc_retain and objc_release are actually needed.
1277 S_Retain, ///< objc_retain(x)
1278 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1279 S_Use, ///< any use of x
1280 S_Stop, ///< like S_Release, but code motion is stopped
1281 S_Release, ///< objc_release(x)
1282 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1286 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1290 if (A == S_None || B == S_None)
1293 if (A > B) std::swap(A, B);
1295 // Choose the side which is further along in the sequence.
1296 if ((A == S_Retain || A == S_CanRelease) &&
1297 (B == S_CanRelease || B == S_Use))
1300 // Choose the side which is further along in the sequence.
1301 if ((A == S_Use || A == S_CanRelease) &&
1302 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
1304 // If both sides are releases, choose the more conservative one.
1305 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1307 if (A == S_Release && B == S_MovableRelease)
1315 /// RRInfo - Unidirectional information about either a
1316 /// retain-decrement-use-release sequence or release-use-decrement-retain
1317 /// reverese sequence.
1319 /// KnownSafe - After an objc_retain, the reference count of the referenced
1320 /// object is known to be positive. Similarly, before an objc_release, the
1321 /// reference count of the referenced object is known to be positive. If
1322 /// there are retain-release pairs in code regions where the retain count
1323 /// is known to be positive, they can be eliminated, regardless of any side
1324 /// effects between them.
1326 /// Also, a retain+release pair nested within another retain+release
1327 /// pair all on the known same pointer value can be eliminated, regardless
1328 /// of any intervening side effects.
1330 /// KnownSafe is true when either of these conditions is satisfied.
1333 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1334 /// opposed to objc_retain calls).
1337 /// IsTailCallRelease - True of the objc_release calls are all marked
1338 /// with the "tail" keyword.
1339 bool IsTailCallRelease;
1341 /// Partial - True of we've seen an opportunity for partial RR elimination,
1342 /// such as pushing calls into a CFG triangle or into one side of a
1344 /// TODO: Consider moving this to PtrState.
1347 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1348 /// a clang.imprecise_release tag, this is the metadata tag.
1349 MDNode *ReleaseMetadata;
1351 /// Calls - For a top-down sequence, the set of objc_retains or
1352 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1353 SmallPtrSet<Instruction *, 2> Calls;
1355 /// ReverseInsertPts - The set of optimal insert positions for
1356 /// moving calls in the opposite sequence.
1357 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1360 KnownSafe(false), IsRetainBlock(false),
1361 IsTailCallRelease(false), Partial(false),
1362 ReleaseMetadata(0) {}
1368 void RRInfo::clear() {
1370 IsRetainBlock = false;
1371 IsTailCallRelease = false;
1373 ReleaseMetadata = 0;
1375 ReverseInsertPts.clear();
1379 /// PtrState - This class summarizes several per-pointer runtime properties
1380 /// which are propogated through the flow graph.
1382 /// RefCount - The known minimum number of reference count increments.
1385 /// NestCount - The known minimum level of retain+release nesting.
1388 /// Seq - The current position in the sequence.
1392 /// RRI - Unidirectional information about the current sequence.
1393 /// TODO: Encapsulate this better.
1396 PtrState() : RefCount(0), NestCount(0), Seq(S_None) {}
1398 void SetAtLeastOneRefCount() {
1399 if (RefCount == 0) RefCount = 1;
1402 void IncrementRefCount() {
1403 if (RefCount != UINT_MAX) ++RefCount;
1406 void DecrementRefCount() {
1407 if (RefCount != 0) --RefCount;
1410 bool IsKnownIncremented() const {
1411 return RefCount > 0;
1414 void IncrementNestCount() {
1415 if (NestCount != UINT_MAX) ++NestCount;
1418 void DecrementNestCount() {
1419 if (NestCount != 0) --NestCount;
1422 bool IsKnownNested() const {
1423 return NestCount > 0;
1426 void SetSeq(Sequence NewSeq) {
1430 Sequence GetSeq() const {
1434 void ClearSequenceProgress() {
1439 void Merge(const PtrState &Other, bool TopDown);
1444 PtrState::Merge(const PtrState &Other, bool TopDown) {
1445 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1446 RefCount = std::min(RefCount, Other.RefCount);
1447 NestCount = std::min(NestCount, Other.NestCount);
1449 // We can't merge a plain objc_retain with an objc_retainBlock.
1450 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1453 // If we're not in a sequence (anymore), drop all associated state.
1454 if (Seq == S_None) {
1456 } else if (RRI.Partial || Other.RRI.Partial) {
1457 // If we're doing a merge on a path that's previously seen a partial
1458 // merge, conservatively drop the sequence, to avoid doing partial
1459 // RR elimination. If the branch predicates for the two merge differ,
1460 // mixing them is unsafe.
1464 // Conservatively merge the ReleaseMetadata information.
1465 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1466 RRI.ReleaseMetadata = 0;
1468 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
1469 RRI.IsTailCallRelease = RRI.IsTailCallRelease && Other.RRI.IsTailCallRelease;
1470 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1472 // Merge the insert point sets. If there are any differences,
1473 // that makes this a partial merge.
1474 RRI.Partial = RRI.ReverseInsertPts.size() !=
1475 Other.RRI.ReverseInsertPts.size();
1476 for (SmallPtrSet<Instruction *, 2>::const_iterator
1477 I = Other.RRI.ReverseInsertPts.begin(),
1478 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1479 RRI.Partial |= RRI.ReverseInsertPts.insert(*I);
1484 /// BBState - Per-BasicBlock state.
1486 /// TopDownPathCount - The number of unique control paths from the entry
1487 /// which can reach this block.
1488 unsigned TopDownPathCount;
1490 /// BottomUpPathCount - The number of unique control paths to exits
1491 /// from this block.
1492 unsigned BottomUpPathCount;
1494 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1495 typedef MapVector<const Value *, PtrState> MapTy;
1497 /// PerPtrTopDown - The top-down traversal uses this to record information
1498 /// known about a pointer at the bottom of each block.
1499 MapTy PerPtrTopDown;
1501 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1502 /// known about a pointer at the top of each block.
1503 MapTy PerPtrBottomUp;
1506 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1508 typedef MapTy::iterator ptr_iterator;
1509 typedef MapTy::const_iterator ptr_const_iterator;
1511 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1512 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1513 ptr_const_iterator top_down_ptr_begin() const {
1514 return PerPtrTopDown.begin();
1516 ptr_const_iterator top_down_ptr_end() const {
1517 return PerPtrTopDown.end();
1520 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1521 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1522 ptr_const_iterator bottom_up_ptr_begin() const {
1523 return PerPtrBottomUp.begin();
1525 ptr_const_iterator bottom_up_ptr_end() const {
1526 return PerPtrBottomUp.end();
1529 /// SetAsEntry - Mark this block as being an entry block, which has one
1530 /// path from the entry by definition.
1531 void SetAsEntry() { TopDownPathCount = 1; }
1533 /// SetAsExit - Mark this block as being an exit block, which has one
1534 /// path to an exit by definition.
1535 void SetAsExit() { BottomUpPathCount = 1; }
1537 PtrState &getPtrTopDownState(const Value *Arg) {
1538 return PerPtrTopDown[Arg];
1541 PtrState &getPtrBottomUpState(const Value *Arg) {
1542 return PerPtrBottomUp[Arg];
1545 void clearBottomUpPointers() {
1546 PerPtrBottomUp.clear();
1549 void clearTopDownPointers() {
1550 PerPtrTopDown.clear();
1553 void InitFromPred(const BBState &Other);
1554 void InitFromSucc(const BBState &Other);
1555 void MergePred(const BBState &Other);
1556 void MergeSucc(const BBState &Other);
1558 /// GetAllPathCount - Return the number of possible unique paths from an
1559 /// entry to an exit which pass through this block. This is only valid
1560 /// after both the top-down and bottom-up traversals are complete.
1561 unsigned GetAllPathCount() const {
1562 return TopDownPathCount * BottomUpPathCount;
1565 /// IsVisitedTopDown - Test whether the block for this BBState has been
1566 /// visited by the top-down portion of the algorithm.
1567 bool isVisitedTopDown() const {
1568 return TopDownPathCount != 0;
1573 void BBState::InitFromPred(const BBState &Other) {
1574 PerPtrTopDown = Other.PerPtrTopDown;
1575 TopDownPathCount = Other.TopDownPathCount;
1578 void BBState::InitFromSucc(const BBState &Other) {
1579 PerPtrBottomUp = Other.PerPtrBottomUp;
1580 BottomUpPathCount = Other.BottomUpPathCount;
1583 /// MergePred - The top-down traversal uses this to merge information about
1584 /// predecessors to form the initial state for a new block.
1585 void BBState::MergePred(const BBState &Other) {
1586 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1587 // loop backedge. Loop backedges are special.
1588 TopDownPathCount += Other.TopDownPathCount;
1590 // For each entry in the other set, if our set has an entry with the same key,
1591 // merge the entries. Otherwise, copy the entry and merge it with an empty
1593 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1594 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1595 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1596 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1600 // For each entry in our set, if the other set doesn't have an entry with the
1601 // same key, force it to merge with an empty entry.
1602 for (ptr_iterator MI = top_down_ptr_begin(),
1603 ME = top_down_ptr_end(); MI != ME; ++MI)
1604 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1605 MI->second.Merge(PtrState(), /*TopDown=*/true);
1608 /// MergeSucc - The bottom-up traversal uses this to merge information about
1609 /// successors to form the initial state for a new block.
1610 void BBState::MergeSucc(const BBState &Other) {
1611 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1612 // loop backedge. Loop backedges are special.
1613 BottomUpPathCount += Other.BottomUpPathCount;
1615 // For each entry in the other set, if our set has an entry with the
1616 // same key, merge the entries. Otherwise, copy the entry and merge
1617 // it with an empty entry.
1618 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1619 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1620 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1621 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1625 // For each entry in our set, if the other set doesn't have an entry
1626 // with the same key, force it to merge with an empty entry.
1627 for (ptr_iterator MI = bottom_up_ptr_begin(),
1628 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1629 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1630 MI->second.Merge(PtrState(), /*TopDown=*/false);
1634 /// ObjCARCOpt - The main ARC optimization pass.
1635 class ObjCARCOpt : public FunctionPass {
1637 ProvenanceAnalysis PA;
1639 /// Run - A flag indicating whether this optimization pass should run.
1642 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1643 /// functions, for use in creating calls to them. These are initialized
1644 /// lazily to avoid cluttering up the Module with unused declarations.
1645 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
1646 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
1648 /// UsedInThisFunciton - Flags which determine whether each of the
1649 /// interesting runtine functions is in fact used in the current function.
1650 unsigned UsedInThisFunction;
1652 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1654 unsigned ImpreciseReleaseMDKind;
1656 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
1658 unsigned CopyOnEscapeMDKind;
1660 /// NoObjCARCExceptionsMDKind - The Metadata Kind for
1661 /// clang.arc.no_objc_arc_exceptions metadata.
1662 unsigned NoObjCARCExceptionsMDKind;
1664 Constant *getRetainRVCallee(Module *M);
1665 Constant *getAutoreleaseRVCallee(Module *M);
1666 Constant *getReleaseCallee(Module *M);
1667 Constant *getRetainCallee(Module *M);
1668 Constant *getRetainBlockCallee(Module *M);
1669 Constant *getAutoreleaseCallee(Module *M);
1671 bool IsRetainBlockOptimizable(const Instruction *Inst);
1673 void OptimizeRetainCall(Function &F, Instruction *Retain);
1674 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1675 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1676 void OptimizeIndividualCalls(Function &F);
1678 void CheckForCFGHazards(const BasicBlock *BB,
1679 DenseMap<const BasicBlock *, BBState> &BBStates,
1680 BBState &MyStates) const;
1681 bool VisitInstructionBottomUp(Instruction *Inst,
1683 MapVector<Value *, RRInfo> &Retains,
1685 bool VisitBottomUp(BasicBlock *BB,
1686 DenseMap<const BasicBlock *, BBState> &BBStates,
1687 MapVector<Value *, RRInfo> &Retains);
1688 bool VisitInstructionTopDown(Instruction *Inst,
1689 DenseMap<Value *, RRInfo> &Releases,
1691 bool VisitTopDown(BasicBlock *BB,
1692 DenseMap<const BasicBlock *, BBState> &BBStates,
1693 DenseMap<Value *, RRInfo> &Releases);
1694 bool Visit(Function &F,
1695 DenseMap<const BasicBlock *, BBState> &BBStates,
1696 MapVector<Value *, RRInfo> &Retains,
1697 DenseMap<Value *, RRInfo> &Releases);
1699 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1700 MapVector<Value *, RRInfo> &Retains,
1701 DenseMap<Value *, RRInfo> &Releases,
1702 SmallVectorImpl<Instruction *> &DeadInsts,
1705 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1706 MapVector<Value *, RRInfo> &Retains,
1707 DenseMap<Value *, RRInfo> &Releases,
1710 void OptimizeWeakCalls(Function &F);
1712 bool OptimizeSequences(Function &F);
1714 void OptimizeReturns(Function &F);
1716 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1717 virtual bool doInitialization(Module &M);
1718 virtual bool runOnFunction(Function &F);
1719 virtual void releaseMemory();
1723 ObjCARCOpt() : FunctionPass(ID) {
1724 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1729 char ObjCARCOpt::ID = 0;
1730 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1731 "objc-arc", "ObjC ARC optimization", false, false)
1732 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1733 INITIALIZE_PASS_END(ObjCARCOpt,
1734 "objc-arc", "ObjC ARC optimization", false, false)
1736 Pass *llvm::createObjCARCOptPass() {
1737 return new ObjCARCOpt();
1740 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1741 AU.addRequired<ObjCARCAliasAnalysis>();
1742 AU.addRequired<AliasAnalysis>();
1743 // ARC optimization doesn't currently split critical edges.
1744 AU.setPreservesCFG();
1747 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1748 // Without the magic metadata tag, we have to assume this might be an
1749 // objc_retainBlock call inserted to convert a block pointer to an id,
1750 // in which case it really is needed.
1751 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1754 // If the pointer "escapes" (not including being used in a call),
1755 // the copy may be needed.
1756 if (DoesObjCBlockEscape(Inst))
1759 // Otherwise, it's not needed.
1763 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1764 if (!RetainRVCallee) {
1765 LLVMContext &C = M->getContext();
1766 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1767 std::vector<Type *> Params;
1768 Params.push_back(I8X);
1770 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1771 AttrListPtr Attributes;
1772 Attributes.addAttr(~0u, Attribute::NoUnwind);
1774 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1777 return RetainRVCallee;
1780 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1781 if (!AutoreleaseRVCallee) {
1782 LLVMContext &C = M->getContext();
1783 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1784 std::vector<Type *> Params;
1785 Params.push_back(I8X);
1787 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1788 AttrListPtr Attributes;
1789 Attributes.addAttr(~0u, Attribute::NoUnwind);
1790 AutoreleaseRVCallee =
1791 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1794 return AutoreleaseRVCallee;
1797 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1798 if (!ReleaseCallee) {
1799 LLVMContext &C = M->getContext();
1800 std::vector<Type *> Params;
1801 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1802 AttrListPtr Attributes;
1803 Attributes.addAttr(~0u, Attribute::NoUnwind);
1805 M->getOrInsertFunction(
1807 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1810 return ReleaseCallee;
1813 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1814 if (!RetainCallee) {
1815 LLVMContext &C = M->getContext();
1816 std::vector<Type *> Params;
1817 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1818 AttrListPtr Attributes;
1819 Attributes.addAttr(~0u, Attribute::NoUnwind);
1821 M->getOrInsertFunction(
1823 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1826 return RetainCallee;
1829 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1830 if (!RetainBlockCallee) {
1831 LLVMContext &C = M->getContext();
1832 std::vector<Type *> Params;
1833 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1834 AttrListPtr Attributes;
1835 // objc_retainBlock is not nounwind because it calls user copy constructors
1836 // which could theoretically throw.
1838 M->getOrInsertFunction(
1840 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1843 return RetainBlockCallee;
1846 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1847 if (!AutoreleaseCallee) {
1848 LLVMContext &C = M->getContext();
1849 std::vector<Type *> Params;
1850 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1851 AttrListPtr Attributes;
1852 Attributes.addAttr(~0u, Attribute::NoUnwind);
1854 M->getOrInsertFunction(
1856 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1859 return AutoreleaseCallee;
1862 /// CanAlterRefCount - Test whether the given instruction can result in a
1863 /// reference count modification (positive or negative) for the pointer's
1866 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1867 ProvenanceAnalysis &PA, InstructionClass Class) {
1869 case IC_Autorelease:
1870 case IC_AutoreleaseRV:
1872 // These operations never directly modify a reference count.
1877 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1878 assert(CS && "Only calls can alter reference counts!");
1880 // See if AliasAnalysis can help us with the call.
1881 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1882 if (AliasAnalysis::onlyReadsMemory(MRB))
1884 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1885 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1887 const Value *Op = *I;
1888 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1894 // Assume the worst.
1898 /// CanUse - Test whether the given instruction can "use" the given pointer's
1899 /// object in a way that requires the reference count to be positive.
1901 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1902 InstructionClass Class) {
1903 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1904 if (Class == IC_Call)
1907 // Consider various instructions which may have pointer arguments which are
1909 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1910 // Comparing a pointer with null, or any other constant, isn't really a use,
1911 // because we don't care what the pointer points to, or about the values
1912 // of any other dynamic reference-counted pointers.
1913 if (!IsPotentialUse(ICI->getOperand(1)))
1915 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1916 // For calls, just check the arguments (and not the callee operand).
1917 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1918 OE = CS.arg_end(); OI != OE; ++OI) {
1919 const Value *Op = *OI;
1920 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1924 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1925 // Special-case stores, because we don't care about the stored value, just
1926 // the store address.
1927 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1928 // If we can't tell what the underlying object was, assume there is a
1930 return IsPotentialUse(Op) && PA.related(Op, Ptr);
1933 // Check each operand for a match.
1934 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1936 const Value *Op = *OI;
1937 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1943 /// CanInterruptRV - Test whether the given instruction can autorelease
1944 /// any pointer or cause an autoreleasepool pop.
1946 CanInterruptRV(InstructionClass Class) {
1948 case IC_AutoreleasepoolPop:
1951 case IC_Autorelease:
1952 case IC_AutoreleaseRV:
1953 case IC_FusedRetainAutorelease:
1954 case IC_FusedRetainAutoreleaseRV:
1962 /// DependenceKind - There are several kinds of dependence-like concepts in
1964 enum DependenceKind {
1965 NeedsPositiveRetainCount,
1966 CanChangeRetainCount,
1967 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1968 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1969 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1973 /// Depends - Test if there can be dependencies on Inst through Arg. This
1974 /// function only tests dependencies relevant for removing pairs of calls.
1976 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1977 ProvenanceAnalysis &PA) {
1978 // If we've reached the definition of Arg, stop.
1983 case NeedsPositiveRetainCount: {
1984 InstructionClass Class = GetInstructionClass(Inst);
1986 case IC_AutoreleasepoolPop:
1987 case IC_AutoreleasepoolPush:
1991 return CanUse(Inst, Arg, PA, Class);
1995 case CanChangeRetainCount: {
1996 InstructionClass Class = GetInstructionClass(Inst);
1998 case IC_AutoreleasepoolPop:
1999 // Conservatively assume this can decrement any count.
2001 case IC_AutoreleasepoolPush:
2005 return CanAlterRefCount(Inst, Arg, PA, Class);
2009 case RetainAutoreleaseDep:
2010 switch (GetBasicInstructionClass(Inst)) {
2011 case IC_AutoreleasepoolPop:
2012 // Don't merge an objc_autorelease with an objc_retain inside a different
2013 // autoreleasepool scope.
2017 // Check for a retain of the same pointer for merging.
2018 return GetObjCArg(Inst) == Arg;
2020 // Nothing else matters for objc_retainAutorelease formation.
2024 case RetainAutoreleaseRVDep: {
2025 InstructionClass Class = GetBasicInstructionClass(Inst);
2029 // Check for a retain of the same pointer for merging.
2030 return GetObjCArg(Inst) == Arg;
2032 // Anything that can autorelease interrupts
2033 // retainAutoreleaseReturnValue formation.
2034 return CanInterruptRV(Class);
2039 return CanInterruptRV(GetBasicInstructionClass(Inst));
2042 llvm_unreachable("Invalid dependence flavor");
2045 /// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2046 /// find local and non-local dependencies on Arg.
2047 /// TODO: Cache results?
2049 FindDependencies(DependenceKind Flavor,
2051 BasicBlock *StartBB, Instruction *StartInst,
2052 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2053 SmallPtrSet<const BasicBlock *, 4> &Visited,
2054 ProvenanceAnalysis &PA) {
2055 BasicBlock::iterator StartPos = StartInst;
2057 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2058 Worklist.push_back(std::make_pair(StartBB, StartPos));
2060 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2061 Worklist.pop_back_val();
2062 BasicBlock *LocalStartBB = Pair.first;
2063 BasicBlock::iterator LocalStartPos = Pair.second;
2064 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2066 if (LocalStartPos == StartBBBegin) {
2067 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2069 // If we've reached the function entry, produce a null dependence.
2070 DependingInstructions.insert(0);
2072 // Add the predecessors to the worklist.
2074 BasicBlock *PredBB = *PI;
2075 if (Visited.insert(PredBB))
2076 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2077 } while (++PI != PE);
2081 Instruction *Inst = --LocalStartPos;
2082 if (Depends(Flavor, Inst, Arg, PA)) {
2083 DependingInstructions.insert(Inst);
2087 } while (!Worklist.empty());
2089 // Determine whether the original StartBB post-dominates all of the blocks we
2090 // visited. If not, insert a sentinal indicating that most optimizations are
2092 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2093 E = Visited.end(); I != E; ++I) {
2094 const BasicBlock *BB = *I;
2097 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2098 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2099 const BasicBlock *Succ = *SI;
2100 if (Succ != StartBB && !Visited.count(Succ)) {
2101 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2108 static bool isNullOrUndef(const Value *V) {
2109 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2112 static bool isNoopInstruction(const Instruction *I) {
2113 return isa<BitCastInst>(I) ||
2114 (isa<GetElementPtrInst>(I) &&
2115 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2118 /// OptimizeRetainCall - Turn objc_retain into
2119 /// objc_retainAutoreleasedReturnValue if the operand is a return value.
2121 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
2122 CallSite CS(GetObjCArg(Retain));
2123 Instruction *Call = CS.getInstruction();
2125 if (Call->getParent() != Retain->getParent()) return;
2127 // Check that the call is next to the retain.
2128 BasicBlock::iterator I = Call;
2130 while (isNoopInstruction(I)) ++I;
2134 // Turn it to an objc_retainAutoreleasedReturnValue..
2137 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2140 /// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
2141 /// objc_retain if the operand is not a return value. Or, if it can be
2142 /// paired with an objc_autoreleaseReturnValue, delete the pair and
2145 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
2146 // Check for the argument being from an immediately preceding call or invoke.
2147 Value *Arg = GetObjCArg(RetainRV);
2149 if (Instruction *Call = CS.getInstruction()) {
2150 if (Call->getParent() == RetainRV->getParent()) {
2151 BasicBlock::iterator I = Call;
2153 while (isNoopInstruction(I)) ++I;
2154 if (&*I == RetainRV)
2156 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
2157 BasicBlock *RetainRVParent = RetainRV->getParent();
2158 if (II->getNormalDest() == RetainRVParent) {
2159 BasicBlock::iterator I = RetainRVParent->begin();
2160 while (isNoopInstruction(I)) ++I;
2161 if (&*I == RetainRV)
2167 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2168 // pointer. In this case, we can delete the pair.
2169 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2171 do --I; while (I != Begin && isNoopInstruction(I));
2172 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2173 GetObjCArg(I) == Arg) {
2176 EraseInstruction(I);
2177 EraseInstruction(RetainRV);
2182 // Turn it to a plain objc_retain.
2185 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2189 /// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2190 /// objc_autorelease if the result is not used as a return value.
2192 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
2193 // Check for a return of the pointer value.
2194 const Value *Ptr = GetObjCArg(AutoreleaseRV);
2195 SmallVector<const Value *, 2> Users;
2196 Users.push_back(Ptr);
2198 Ptr = Users.pop_back_val();
2199 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2201 const User *I = *UI;
2202 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2204 if (isa<BitCastInst>(I))
2207 } while (!Users.empty());
2211 cast<CallInst>(AutoreleaseRV)->
2212 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2215 /// OptimizeIndividualCalls - Visit each call, one at a time, and make
2216 /// simplifications without doing any additional analysis.
2217 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2218 // Reset all the flags in preparation for recomputing them.
2219 UsedInThisFunction = 0;
2221 // Visit all objc_* calls in F.
2222 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2223 Instruction *Inst = &*I++;
2224 InstructionClass Class = GetBasicInstructionClass(Inst);
2229 // Delete no-op casts. These function calls have special semantics, but
2230 // the semantics are entirely implemented via lowering in the front-end,
2231 // so by the time they reach the optimizer, they are just no-op calls
2232 // which return their argument.
2234 // There are gray areas here, as the ability to cast reference-counted
2235 // pointers to raw void* and back allows code to break ARC assumptions,
2236 // however these are currently considered to be unimportant.
2240 EraseInstruction(Inst);
2243 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2246 case IC_LoadWeakRetained:
2248 case IC_DestroyWeak: {
2249 CallInst *CI = cast<CallInst>(Inst);
2250 if (isNullOrUndef(CI->getArgOperand(0))) {
2251 Type *Ty = CI->getArgOperand(0)->getType();
2252 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2253 Constant::getNullValue(Ty),
2255 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2256 CI->eraseFromParent();
2263 CallInst *CI = cast<CallInst>(Inst);
2264 if (isNullOrUndef(CI->getArgOperand(0)) ||
2265 isNullOrUndef(CI->getArgOperand(1))) {
2266 Type *Ty = CI->getArgOperand(0)->getType();
2267 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2268 Constant::getNullValue(Ty),
2270 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2271 CI->eraseFromParent();
2277 OptimizeRetainCall(F, Inst);
2280 if (OptimizeRetainRVCall(F, Inst))
2283 case IC_AutoreleaseRV:
2284 OptimizeAutoreleaseRVCall(F, Inst);
2288 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2289 if (IsAutorelease(Class) && Inst->use_empty()) {
2290 CallInst *Call = cast<CallInst>(Inst);
2291 const Value *Arg = Call->getArgOperand(0);
2292 Arg = FindSingleUseIdentifiedObject(Arg);
2297 // Create the declaration lazily.
2298 LLVMContext &C = Inst->getContext();
2300 CallInst::Create(getReleaseCallee(F.getParent()),
2301 Call->getArgOperand(0), "", Call);
2302 NewCall->setMetadata(ImpreciseReleaseMDKind,
2303 MDNode::get(C, ArrayRef<Value *>()));
2304 EraseInstruction(Call);
2310 // For functions which can never be passed stack arguments, add
2312 if (IsAlwaysTail(Class)) {
2314 cast<CallInst>(Inst)->setTailCall();
2317 // Set nounwind as needed.
2318 if (IsNoThrow(Class)) {
2320 cast<CallInst>(Inst)->setDoesNotThrow();
2323 if (!IsNoopOnNull(Class)) {
2324 UsedInThisFunction |= 1 << Class;
2328 const Value *Arg = GetObjCArg(Inst);
2330 // ARC calls with null are no-ops. Delete them.
2331 if (isNullOrUndef(Arg)) {
2334 EraseInstruction(Inst);
2338 // Keep track of which of retain, release, autorelease, and retain_block
2339 // are actually present in this function.
2340 UsedInThisFunction |= 1 << Class;
2342 // If Arg is a PHI, and one or more incoming values to the
2343 // PHI are null, and the call is control-equivalent to the PHI, and there
2344 // are no relevant side effects between the PHI and the call, the call
2345 // could be pushed up to just those paths with non-null incoming values.
2346 // For now, don't bother splitting critical edges for this.
2347 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2348 Worklist.push_back(std::make_pair(Inst, Arg));
2350 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2354 const PHINode *PN = dyn_cast<PHINode>(Arg);
2357 // Determine if the PHI has any null operands, or any incoming
2359 bool HasNull = false;
2360 bool HasCriticalEdges = false;
2361 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2363 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2364 if (isNullOrUndef(Incoming))
2366 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2367 .getNumSuccessors() != 1) {
2368 HasCriticalEdges = true;
2372 // If we have null operands and no critical edges, optimize.
2373 if (!HasCriticalEdges && HasNull) {
2374 SmallPtrSet<Instruction *, 4> DependingInstructions;
2375 SmallPtrSet<const BasicBlock *, 4> Visited;
2377 // Check that there is nothing that cares about the reference
2378 // count between the call and the phi.
2379 FindDependencies(NeedsPositiveRetainCount, Arg,
2380 Inst->getParent(), Inst,
2381 DependingInstructions, Visited, PA);
2382 if (DependingInstructions.size() == 1 &&
2383 *DependingInstructions.begin() == PN) {
2386 // Clone the call into each predecessor that has a non-null value.
2387 CallInst *CInst = cast<CallInst>(Inst);
2388 Type *ParamTy = CInst->getArgOperand(0)->getType();
2389 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2391 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2392 if (!isNullOrUndef(Incoming)) {
2393 CallInst *Clone = cast<CallInst>(CInst->clone());
2394 Value *Op = PN->getIncomingValue(i);
2395 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2396 if (Op->getType() != ParamTy)
2397 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2398 Clone->setArgOperand(0, Op);
2399 Clone->insertBefore(InsertPos);
2400 Worklist.push_back(std::make_pair(Clone, Incoming));
2403 // Erase the original call.
2404 EraseInstruction(CInst);
2408 } while (!Worklist.empty());
2412 /// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2413 /// control flow, or other CFG structures where moving code across the edge
2414 /// would result in it being executed more.
2416 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2417 DenseMap<const BasicBlock *, BBState> &BBStates,
2418 BBState &MyStates) const {
2419 // If any top-down local-use or possible-dec has a succ which is earlier in
2420 // the sequence, forget it.
2421 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
2422 E = MyStates.top_down_ptr_end(); I != E; ++I)
2423 switch (I->second.GetSeq()) {
2426 const Value *Arg = I->first;
2427 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2428 bool SomeSuccHasSame = false;
2429 bool AllSuccsHaveSame = true;
2430 PtrState &S = I->second;
2431 succ_const_iterator SI(TI), SE(TI, false);
2433 // If the terminator is an invoke marked with the
2434 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2435 // ignored, for ARC purposes.
2436 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2439 for (; SI != SE; ++SI) {
2440 Sequence SuccSSeq = S_None;
2441 bool SuccSRRIKnownSafe = false;
2442 // If VisitBottomUp has visited this successor, take what we know about it.
2443 DenseMap<const BasicBlock *, BBState>::iterator BBI = BBStates.find(*SI);
2444 if (BBI != BBStates.end()) {
2445 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2446 SuccSSeq = SuccS.GetSeq();
2447 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2451 case S_CanRelease: {
2452 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2453 S.ClearSequenceProgress();
2459 SomeSuccHasSame = true;
2463 case S_MovableRelease:
2464 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2465 AllSuccsHaveSame = false;
2468 llvm_unreachable("bottom-up pointer in retain state!");
2471 // If the state at the other end of any of the successor edges
2472 // matches the current state, require all edges to match. This
2473 // guards against loops in the middle of a sequence.
2474 if (SomeSuccHasSame && !AllSuccsHaveSame)
2475 S.ClearSequenceProgress();
2478 case S_CanRelease: {
2479 const Value *Arg = I->first;
2480 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2481 bool SomeSuccHasSame = false;
2482 bool AllSuccsHaveSame = true;
2483 PtrState &S = I->second;
2484 succ_const_iterator SI(TI), SE(TI, false);
2486 // If the terminator is an invoke marked with the
2487 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2488 // ignored, for ARC purposes.
2489 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2492 for (; SI != SE; ++SI) {
2493 Sequence SuccSSeq = S_None;
2494 bool SuccSRRIKnownSafe = false;
2495 // If VisitBottomUp has visited this successor, take what we know about it.
2496 DenseMap<const BasicBlock *, BBState>::iterator BBI = BBStates.find(*SI);
2497 if (BBI != BBStates.end()) {
2498 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2499 SuccSSeq = SuccS.GetSeq();
2500 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2504 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2505 S.ClearSequenceProgress();
2511 SomeSuccHasSame = true;
2515 case S_MovableRelease:
2517 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2518 AllSuccsHaveSame = false;
2521 llvm_unreachable("bottom-up pointer in retain state!");
2524 // If the state at the other end of any of the successor edges
2525 // matches the current state, require all edges to match. This
2526 // guards against loops in the middle of a sequence.
2527 if (SomeSuccHasSame && !AllSuccsHaveSame)
2528 S.ClearSequenceProgress();
2535 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
2537 MapVector<Value *, RRInfo> &Retains,
2538 BBState &MyStates) {
2539 bool NestingDetected = false;
2540 InstructionClass Class = GetInstructionClass(Inst);
2541 const Value *Arg = 0;
2545 Arg = GetObjCArg(Inst);
2547 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2549 // If we see two releases in a row on the same pointer. If so, make
2550 // a note, and we'll cicle back to revisit it after we've
2551 // hopefully eliminated the second release, which may allow us to
2552 // eliminate the first release too.
2553 // Theoretically we could implement removal of nested retain+release
2554 // pairs by making PtrState hold a stack of states, but this is
2555 // simple and avoids adding overhead for the non-nested case.
2556 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2557 NestingDetected = true;
2561 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2562 S.SetSeq(ReleaseMetadata ? S_MovableRelease : S_Release);
2563 S.RRI.ReleaseMetadata = ReleaseMetadata;
2564 S.RRI.KnownSafe = S.IsKnownNested() || S.IsKnownIncremented();
2565 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2566 S.RRI.Calls.insert(Inst);
2568 S.IncrementRefCount();
2569 S.IncrementNestCount();
2572 case IC_RetainBlock:
2573 // An objc_retainBlock call with just a use may need to be kept,
2574 // because it may be copying a block from the stack to the heap.
2575 if (!IsRetainBlockOptimizable(Inst))
2580 Arg = GetObjCArg(Inst);
2582 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2583 S.DecrementRefCount();
2584 S.SetAtLeastOneRefCount();
2585 S.DecrementNestCount();
2587 switch (S.GetSeq()) {
2590 case S_MovableRelease:
2592 S.RRI.ReverseInsertPts.clear();
2595 // Don't do retain+release tracking for IC_RetainRV, because it's
2596 // better to let it remain as the first instruction after a call.
2597 if (Class != IC_RetainRV) {
2598 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2599 Retains[Inst] = S.RRI;
2601 S.ClearSequenceProgress();
2606 llvm_unreachable("bottom-up pointer in retain state!");
2608 return NestingDetected;
2610 case IC_AutoreleasepoolPop:
2611 // Conservatively, clear MyStates for all known pointers.
2612 MyStates.clearBottomUpPointers();
2613 return NestingDetected;
2614 case IC_AutoreleasepoolPush:
2616 // These are irrelevant.
2617 return NestingDetected;
2622 // Consider any other possible effects of this instruction on each
2623 // pointer being tracked.
2624 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2625 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2626 const Value *Ptr = MI->first;
2628 continue; // Handled above.
2629 PtrState &S = MI->second;
2630 Sequence Seq = S.GetSeq();
2632 // Check for possible releases.
2633 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2634 S.DecrementRefCount();
2637 S.SetSeq(S_CanRelease);
2641 case S_MovableRelease:
2646 llvm_unreachable("bottom-up pointer in retain state!");
2650 // Check for possible direct uses.
2653 case S_MovableRelease:
2654 if (CanUse(Inst, Ptr, PA, Class)) {
2655 assert(S.RRI.ReverseInsertPts.empty());
2656 // If this is an invoke instruction, we're scanning it as part of
2657 // one of its successor blocks, since we can't insert code after it
2658 // in its own block, and we don't want to split critical edges.
2659 if (isa<InvokeInst>(Inst))
2660 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2662 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2664 } else if (Seq == S_Release &&
2665 (Class == IC_User || Class == IC_CallOrUser)) {
2666 // Non-movable releases depend on any possible objc pointer use.
2668 assert(S.RRI.ReverseInsertPts.empty());
2669 // As above; handle invoke specially.
2670 if (isa<InvokeInst>(Inst))
2671 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2673 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2677 if (CanUse(Inst, Ptr, PA, Class))
2685 llvm_unreachable("bottom-up pointer in retain state!");
2689 return NestingDetected;
2693 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2694 DenseMap<const BasicBlock *, BBState> &BBStates,
2695 MapVector<Value *, RRInfo> &Retains) {
2696 bool NestingDetected = false;
2697 BBState &MyStates = BBStates[BB];
2699 // Merge the states from each successor to compute the initial state
2700 // for the current block.
2701 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2702 succ_const_iterator SI(TI), SE(TI, false);
2704 MyStates.SetAsExit();
2706 // If the terminator is an invoke marked with the
2707 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2708 // ignored, for ARC purposes.
2709 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2713 const BasicBlock *Succ = *SI++;
2716 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2717 // If we haven't seen this node yet, then we've found a CFG cycle.
2718 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2719 if (I == BBStates.end())
2721 MyStates.InitFromSucc(I->second);
2725 I = BBStates.find(Succ);
2726 if (I != BBStates.end())
2727 MyStates.MergeSucc(I->second);
2734 // Visit all the instructions, bottom-up.
2735 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2736 Instruction *Inst = llvm::prior(I);
2738 // Invoke instructions are visited as part of their successors (below).
2739 if (isa<InvokeInst>(Inst))
2742 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2745 // If there's a predecessor with an invoke, visit the invoke as
2746 // if it were part of this block, since we can't insert code after
2747 // an invoke in its own block, and we don't want to split critical
2749 for (pred_iterator PI(BB), PE(BB, false); PI != PE; ++PI) {
2750 BasicBlock *Pred = *PI;
2751 TerminatorInst *PredTI = cast<TerminatorInst>(&Pred->back());
2752 if (isa<InvokeInst>(PredTI))
2753 NestingDetected |= VisitInstructionBottomUp(PredTI, BB, Retains, MyStates);
2756 return NestingDetected;
2760 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2761 DenseMap<Value *, RRInfo> &Releases,
2762 BBState &MyStates) {
2763 bool NestingDetected = false;
2764 InstructionClass Class = GetInstructionClass(Inst);
2765 const Value *Arg = 0;
2768 case IC_RetainBlock:
2769 // An objc_retainBlock call with just a use may need to be kept,
2770 // because it may be copying a block from the stack to the heap.
2771 if (!IsRetainBlockOptimizable(Inst))
2776 Arg = GetObjCArg(Inst);
2778 PtrState &S = MyStates.getPtrTopDownState(Arg);
2780 // Don't do retain+release tracking for IC_RetainRV, because it's
2781 // better to let it remain as the first instruction after a call.
2782 if (Class != IC_RetainRV) {
2783 // If we see two retains in a row on the same pointer. If so, make
2784 // a note, and we'll cicle back to revisit it after we've
2785 // hopefully eliminated the second retain, which may allow us to
2786 // eliminate the first retain too.
2787 // Theoretically we could implement removal of nested retain+release
2788 // pairs by making PtrState hold a stack of states, but this is
2789 // simple and avoids adding overhead for the non-nested case.
2790 if (S.GetSeq() == S_Retain)
2791 NestingDetected = true;
2795 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2796 // Don't check S.IsKnownIncremented() here because it's not
2798 S.RRI.KnownSafe = S.IsKnownNested();
2799 S.RRI.Calls.insert(Inst);
2802 S.SetAtLeastOneRefCount();
2803 S.IncrementRefCount();
2804 S.IncrementNestCount();
2805 return NestingDetected;
2808 Arg = GetObjCArg(Inst);
2810 PtrState &S = MyStates.getPtrTopDownState(Arg);
2811 S.DecrementRefCount();
2812 S.DecrementNestCount();
2814 switch (S.GetSeq()) {
2817 S.RRI.ReverseInsertPts.clear();
2820 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2821 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2822 Releases[Inst] = S.RRI;
2823 S.ClearSequenceProgress();
2829 case S_MovableRelease:
2830 llvm_unreachable("top-down pointer in release state!");
2834 case IC_AutoreleasepoolPop:
2835 // Conservatively, clear MyStates for all known pointers.
2836 MyStates.clearTopDownPointers();
2837 return NestingDetected;
2838 case IC_AutoreleasepoolPush:
2840 // These are irrelevant.
2841 return NestingDetected;
2846 // Consider any other possible effects of this instruction on each
2847 // pointer being tracked.
2848 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2849 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2850 const Value *Ptr = MI->first;
2852 continue; // Handled above.
2853 PtrState &S = MI->second;
2854 Sequence Seq = S.GetSeq();
2856 // Check for possible releases.
2857 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2858 S.DecrementRefCount();
2861 S.SetSeq(S_CanRelease);
2862 assert(S.RRI.ReverseInsertPts.empty());
2863 S.RRI.ReverseInsertPts.insert(Inst);
2865 // One call can't cause a transition from S_Retain to S_CanRelease
2866 // and S_CanRelease to S_Use. If we've made the first transition,
2875 case S_MovableRelease:
2876 llvm_unreachable("top-down pointer in release state!");
2880 // Check for possible direct uses.
2883 if (CanUse(Inst, Ptr, PA, Class))
2892 case S_MovableRelease:
2893 llvm_unreachable("top-down pointer in release state!");
2897 return NestingDetected;
2901 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2902 DenseMap<const BasicBlock *, BBState> &BBStates,
2903 DenseMap<Value *, RRInfo> &Releases) {
2904 bool NestingDetected = false;
2905 BBState &MyStates = BBStates[BB];
2907 // Merge the states from each predecessor to compute the initial state
2908 // for the current block.
2909 const_pred_iterator PI(BB), PE(BB, false);
2911 MyStates.SetAsEntry();
2914 unsigned OperandNo = PI.getOperandNo();
2915 const Use &Us = PI.getUse();
2918 // Skip invoke unwind edges on invoke instructions marked with
2919 // clang.arc.no_objc_arc_exceptions.
2920 if (const InvokeInst *II = dyn_cast<InvokeInst>(Us.getUser()))
2921 if (OperandNo == II->getNumArgOperands() + 2 &&
2922 II->getMetadata(NoObjCARCExceptionsMDKind))
2925 const BasicBlock *Pred = cast<TerminatorInst>(Us.getUser())->getParent();
2928 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2929 // If we haven't seen this node yet, then we've found a CFG cycle.
2930 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
2931 if (I == BBStates.end() || !I->second.isVisitedTopDown())
2933 MyStates.InitFromPred(I->second);
2937 I = BBStates.find(Pred);
2938 if (I != BBStates.end() && I->second.isVisitedTopDown())
2939 MyStates.MergePred(I->second);
2945 // Visit all the instructions, top-down.
2946 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2947 Instruction *Inst = I;
2948 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
2951 CheckForCFGHazards(BB, BBStates, MyStates);
2952 return NestingDetected;
2956 ComputePostOrders(Function &F,
2957 SmallVectorImpl<BasicBlock *> &PostOrder,
2958 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder) {
2959 /// Backedges - Backedges detected in the DFS. These edges will be
2960 /// ignored in the reverse-CFG DFS, so that loops with multiple exits will be
2961 /// traversed in the desired order.
2962 DenseSet<std::pair<BasicBlock *, BasicBlock *> > Backedges;
2964 /// Visited - The visited set, for doing DFS walks.
2965 SmallPtrSet<BasicBlock *, 16> Visited;
2967 // Do DFS, computing the PostOrder.
2968 SmallPtrSet<BasicBlock *, 16> OnStack;
2969 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2970 BasicBlock *EntryBB = &F.getEntryBlock();
2971 SuccStack.push_back(std::make_pair(EntryBB, succ_begin(EntryBB)));
2972 Visited.insert(EntryBB);
2973 OnStack.insert(EntryBB);
2976 TerminatorInst *TI = cast<TerminatorInst>(&SuccStack.back().first->back());
2977 succ_iterator End = succ_iterator(TI, true);
2978 while (SuccStack.back().second != End) {
2979 BasicBlock *BB = *SuccStack.back().second++;
2980 if (Visited.insert(BB)) {
2981 SuccStack.push_back(std::make_pair(BB, succ_begin(BB)));
2985 if (OnStack.count(BB))
2986 Backedges.insert(std::make_pair(SuccStack.back().first, BB));
2988 OnStack.erase(SuccStack.back().first);
2989 PostOrder.push_back(SuccStack.pop_back_val().first);
2990 } while (!SuccStack.empty());
2994 // Compute the exits, which are the starting points for reverse-CFG DFS.
2995 // This includes blocks where all the successors are backedges that
2997 SmallVector<BasicBlock *, 4> Exits;
2998 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3000 TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
3001 for (succ_iterator SI(TI), SE(TI, true); SI != SE; ++SI)
3002 if (!Backedges.count(std::make_pair(BB, *SI)))
3003 goto HasNonBackedgeSucc;
3004 Exits.push_back(BB);
3005 HasNonBackedgeSucc:;
3008 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
3009 SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> PredStack;
3010 for (SmallVectorImpl<BasicBlock *>::iterator I = Exits.begin(), E = Exits.end();
3012 BasicBlock *ExitBB = *I;
3013 PredStack.push_back(std::make_pair(ExitBB, pred_begin(ExitBB)));
3014 Visited.insert(ExitBB);
3015 while (!PredStack.empty()) {
3016 reverse_dfs_next_succ:
3017 pred_iterator End = pred_end(PredStack.back().first);
3018 while (PredStack.back().second != End) {
3019 BasicBlock *BB = *PredStack.back().second++;
3020 // Skip backedges detected in the forward-CFG DFS.
3021 if (Backedges.count(std::make_pair(BB, PredStack.back().first)))
3023 if (Visited.insert(BB)) {
3024 PredStack.push_back(std::make_pair(BB, pred_begin(BB)));
3025 goto reverse_dfs_next_succ;
3028 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3033 // Visit - Visit the function both top-down and bottom-up.
3035 ObjCARCOpt::Visit(Function &F,
3036 DenseMap<const BasicBlock *, BBState> &BBStates,
3037 MapVector<Value *, RRInfo> &Retains,
3038 DenseMap<Value *, RRInfo> &Releases) {
3040 // Use reverse-postorder traversals, because we magically know that loops
3041 // will be well behaved, i.e. they won't repeatedly call retain on a single
3042 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3043 // class here because we want the reverse-CFG postorder to consider each
3044 // function exit point, and we want to ignore selected cycle edges.
3045 SmallVector<BasicBlock *, 16> PostOrder;
3046 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
3047 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder);
3049 // Use reverse-postorder on the reverse CFG for bottom-up.
3050 bool BottomUpNestingDetected = false;
3051 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3052 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3054 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
3056 // Use reverse-postorder for top-down.
3057 bool TopDownNestingDetected = false;
3058 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3059 PostOrder.rbegin(), E = PostOrder.rend();
3061 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
3063 return TopDownNestingDetected && BottomUpNestingDetected;
3066 /// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
3067 void ObjCARCOpt::MoveCalls(Value *Arg,
3068 RRInfo &RetainsToMove,
3069 RRInfo &ReleasesToMove,
3070 MapVector<Value *, RRInfo> &Retains,
3071 DenseMap<Value *, RRInfo> &Releases,
3072 SmallVectorImpl<Instruction *> &DeadInsts,
3074 Type *ArgTy = Arg->getType();
3075 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
3077 // Insert the new retain and release calls.
3078 for (SmallPtrSet<Instruction *, 2>::const_iterator
3079 PI = ReleasesToMove.ReverseInsertPts.begin(),
3080 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3081 Instruction *InsertPt = *PI;
3082 Value *MyArg = ArgTy == ParamTy ? Arg :
3083 new BitCastInst(Arg, ParamTy, "", InsertPt);
3085 CallInst::Create(RetainsToMove.IsRetainBlock ?
3086 getRetainBlockCallee(M) : getRetainCallee(M),
3087 MyArg, "", InsertPt);
3088 Call->setDoesNotThrow();
3089 if (RetainsToMove.IsRetainBlock)
3090 Call->setMetadata(CopyOnEscapeMDKind,
3091 MDNode::get(M->getContext(), ArrayRef<Value *>()));
3093 Call->setTailCall();
3095 for (SmallPtrSet<Instruction *, 2>::const_iterator
3096 PI = RetainsToMove.ReverseInsertPts.begin(),
3097 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3098 Instruction *InsertPt = *PI;
3099 Value *MyArg = ArgTy == ParamTy ? Arg :
3100 new BitCastInst(Arg, ParamTy, "", InsertPt);
3101 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3103 // Attach a clang.imprecise_release metadata tag, if appropriate.
3104 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3105 Call->setMetadata(ImpreciseReleaseMDKind, M);
3106 Call->setDoesNotThrow();
3107 if (ReleasesToMove.IsTailCallRelease)
3108 Call->setTailCall();
3111 // Delete the original retain and release calls.
3112 for (SmallPtrSet<Instruction *, 2>::const_iterator
3113 AI = RetainsToMove.Calls.begin(),
3114 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3115 Instruction *OrigRetain = *AI;
3116 Retains.blot(OrigRetain);
3117 DeadInsts.push_back(OrigRetain);
3119 for (SmallPtrSet<Instruction *, 2>::const_iterator
3120 AI = ReleasesToMove.Calls.begin(),
3121 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3122 Instruction *OrigRelease = *AI;
3123 Releases.erase(OrigRelease);
3124 DeadInsts.push_back(OrigRelease);
3129 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3131 MapVector<Value *, RRInfo> &Retains,
3132 DenseMap<Value *, RRInfo> &Releases,
3134 bool AnyPairsCompletelyEliminated = false;
3135 RRInfo RetainsToMove;
3136 RRInfo ReleasesToMove;
3137 SmallVector<Instruction *, 4> NewRetains;
3138 SmallVector<Instruction *, 4> NewReleases;
3139 SmallVector<Instruction *, 8> DeadInsts;
3141 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
3142 E = Retains.end(); I != E; ++I) {
3143 Value *V = I->first;
3144 if (!V) continue; // blotted
3146 Instruction *Retain = cast<Instruction>(V);
3147 Value *Arg = GetObjCArg(Retain);
3149 // If the object being released is in static or stack storage, we know it's
3150 // not being managed by ObjC reference counting, so we can delete pairs
3151 // regardless of what possible decrements or uses lie between them.
3152 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
3154 // A constant pointer can't be pointing to an object on the heap. It may
3155 // be reference-counted, but it won't be deleted.
3156 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3157 if (const GlobalVariable *GV =
3158 dyn_cast<GlobalVariable>(
3159 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3160 if (GV->isConstant())
3163 // If a pair happens in a region where it is known that the reference count
3164 // is already incremented, we can similarly ignore possible decrements.
3165 bool KnownSafeTD = true, KnownSafeBU = true;
3167 // Connect the dots between the top-down-collected RetainsToMove and
3168 // bottom-up-collected ReleasesToMove to form sets of related calls.
3169 // This is an iterative process so that we connect multiple releases
3170 // to multiple retains if needed.
3171 unsigned OldDelta = 0;
3172 unsigned NewDelta = 0;
3173 unsigned OldCount = 0;
3174 unsigned NewCount = 0;
3175 bool FirstRelease = true;
3176 bool FirstRetain = true;
3177 NewRetains.push_back(Retain);
3179 for (SmallVectorImpl<Instruction *>::const_iterator
3180 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3181 Instruction *NewRetain = *NI;
3182 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3183 assert(It != Retains.end());
3184 const RRInfo &NewRetainRRI = It->second;
3185 KnownSafeTD &= NewRetainRRI.KnownSafe;
3186 for (SmallPtrSet<Instruction *, 2>::const_iterator
3187 LI = NewRetainRRI.Calls.begin(),
3188 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3189 Instruction *NewRetainRelease = *LI;
3190 DenseMap<Value *, RRInfo>::const_iterator Jt =
3191 Releases.find(NewRetainRelease);
3192 if (Jt == Releases.end())
3194 const RRInfo &NewRetainReleaseRRI = Jt->second;
3195 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3196 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3198 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3200 // Merge the ReleaseMetadata and IsTailCallRelease values.
3202 ReleasesToMove.ReleaseMetadata =
3203 NewRetainReleaseRRI.ReleaseMetadata;
3204 ReleasesToMove.IsTailCallRelease =
3205 NewRetainReleaseRRI.IsTailCallRelease;
3206 FirstRelease = false;
3208 if (ReleasesToMove.ReleaseMetadata !=
3209 NewRetainReleaseRRI.ReleaseMetadata)
3210 ReleasesToMove.ReleaseMetadata = 0;
3211 if (ReleasesToMove.IsTailCallRelease !=
3212 NewRetainReleaseRRI.IsTailCallRelease)
3213 ReleasesToMove.IsTailCallRelease = false;
3216 // Collect the optimal insertion points.
3218 for (SmallPtrSet<Instruction *, 2>::const_iterator
3219 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3220 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3222 Instruction *RIP = *RI;
3223 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3224 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3226 NewReleases.push_back(NewRetainRelease);
3231 if (NewReleases.empty()) break;
3233 // Back the other way.
3234 for (SmallVectorImpl<Instruction *>::const_iterator
3235 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3236 Instruction *NewRelease = *NI;
3237 DenseMap<Value *, RRInfo>::const_iterator It =
3238 Releases.find(NewRelease);
3239 assert(It != Releases.end());
3240 const RRInfo &NewReleaseRRI = It->second;
3241 KnownSafeBU &= NewReleaseRRI.KnownSafe;
3242 for (SmallPtrSet<Instruction *, 2>::const_iterator
3243 LI = NewReleaseRRI.Calls.begin(),
3244 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3245 Instruction *NewReleaseRetain = *LI;
3246 MapVector<Value *, RRInfo>::const_iterator Jt =
3247 Retains.find(NewReleaseRetain);
3248 if (Jt == Retains.end())
3250 const RRInfo &NewReleaseRetainRRI = Jt->second;
3251 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3252 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3253 unsigned PathCount =
3254 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3255 OldDelta += PathCount;
3256 OldCount += PathCount;
3258 // Merge the IsRetainBlock values.
3260 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3261 FirstRetain = false;
3262 } else if (ReleasesToMove.IsRetainBlock !=
3263 NewReleaseRetainRRI.IsRetainBlock)
3264 // It's not possible to merge the sequences if one uses
3265 // objc_retain and the other uses objc_retainBlock.
3268 // Collect the optimal insertion points.
3270 for (SmallPtrSet<Instruction *, 2>::const_iterator
3271 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3272 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3274 Instruction *RIP = *RI;
3275 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3276 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3277 NewDelta += PathCount;
3278 NewCount += PathCount;
3281 NewRetains.push_back(NewReleaseRetain);
3285 NewReleases.clear();
3286 if (NewRetains.empty()) break;
3289 // If the pointer is known incremented or nested, we can safely delete the
3290 // pair regardless of what's between them.
3291 if (KnownSafeTD || KnownSafeBU) {
3292 RetainsToMove.ReverseInsertPts.clear();
3293 ReleasesToMove.ReverseInsertPts.clear();
3296 // Determine whether the new insertion points we computed preserve the
3297 // balance of retain and release calls through the program.
3298 // TODO: If the fully aggressive solution isn't valid, try to find a
3299 // less aggressive solution which is.
3304 // Determine whether the original call points are balanced in the retain and
3305 // release calls through the program. If not, conservatively don't touch
3307 // TODO: It's theoretically possible to do code motion in this case, as
3308 // long as the existing imbalances are maintained.
3312 // Ok, everything checks out and we're all set. Let's move some code!
3314 AnyPairsCompletelyEliminated = NewCount == 0;
3315 NumRRs += OldCount - NewCount;
3316 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3317 Retains, Releases, DeadInsts, M);
3320 NewReleases.clear();
3322 RetainsToMove.clear();
3323 ReleasesToMove.clear();
3326 // Now that we're done moving everything, we can delete the newly dead
3327 // instructions, as we no longer need them as insert points.
3328 while (!DeadInsts.empty())
3329 EraseInstruction(DeadInsts.pop_back_val());
3331 return AnyPairsCompletelyEliminated;
3334 /// OptimizeWeakCalls - Weak pointer optimizations.
3335 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3336 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3337 // itself because it uses AliasAnalysis and we need to do provenance
3339 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3340 Instruction *Inst = &*I++;
3341 InstructionClass Class = GetBasicInstructionClass(Inst);
3342 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3345 // Delete objc_loadWeak calls with no users.
3346 if (Class == IC_LoadWeak && Inst->use_empty()) {
3347 Inst->eraseFromParent();
3351 // TODO: For now, just look for an earlier available version of this value
3352 // within the same block. Theoretically, we could do memdep-style non-local
3353 // analysis too, but that would want caching. A better approach would be to
3354 // use the technique that EarlyCSE uses.
3355 inst_iterator Current = llvm::prior(I);
3356 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3357 for (BasicBlock::iterator B = CurrentBB->begin(),
3358 J = Current.getInstructionIterator();
3360 Instruction *EarlierInst = &*llvm::prior(J);
3361 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3362 switch (EarlierClass) {
3364 case IC_LoadWeakRetained: {
3365 // If this is loading from the same pointer, replace this load's value
3367 CallInst *Call = cast<CallInst>(Inst);
3368 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3369 Value *Arg = Call->getArgOperand(0);
3370 Value *EarlierArg = EarlierCall->getArgOperand(0);
3371 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3372 case AliasAnalysis::MustAlias:
3374 // If the load has a builtin retain, insert a plain retain for it.
3375 if (Class == IC_LoadWeakRetained) {
3377 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3381 // Zap the fully redundant load.
3382 Call->replaceAllUsesWith(EarlierCall);
3383 Call->eraseFromParent();
3385 case AliasAnalysis::MayAlias:
3386 case AliasAnalysis::PartialAlias:
3388 case AliasAnalysis::NoAlias:
3395 // If this is storing to the same pointer and has the same size etc.
3396 // replace this load's value with the stored value.
3397 CallInst *Call = cast<CallInst>(Inst);
3398 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3399 Value *Arg = Call->getArgOperand(0);
3400 Value *EarlierArg = EarlierCall->getArgOperand(0);
3401 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3402 case AliasAnalysis::MustAlias:
3404 // If the load has a builtin retain, insert a plain retain for it.
3405 if (Class == IC_LoadWeakRetained) {
3407 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3411 // Zap the fully redundant load.
3412 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3413 Call->eraseFromParent();
3415 case AliasAnalysis::MayAlias:
3416 case AliasAnalysis::PartialAlias:
3418 case AliasAnalysis::NoAlias:
3425 // TOOD: Grab the copied value.
3427 case IC_AutoreleasepoolPush:
3430 // Weak pointers are only modified through the weak entry points
3431 // (and arbitrary calls, which could call the weak entry points).
3434 // Anything else could modify the weak pointer.
3441 // Then, for each destroyWeak with an alloca operand, check to see if
3442 // the alloca and all its users can be zapped.
3443 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3444 Instruction *Inst = &*I++;
3445 InstructionClass Class = GetBasicInstructionClass(Inst);
3446 if (Class != IC_DestroyWeak)
3449 CallInst *Call = cast<CallInst>(Inst);
3450 Value *Arg = Call->getArgOperand(0);
3451 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3452 for (Value::use_iterator UI = Alloca->use_begin(),
3453 UE = Alloca->use_end(); UI != UE; ++UI) {
3454 Instruction *UserInst = cast<Instruction>(*UI);
3455 switch (GetBasicInstructionClass(UserInst)) {
3458 case IC_DestroyWeak:
3465 for (Value::use_iterator UI = Alloca->use_begin(),
3466 UE = Alloca->use_end(); UI != UE; ) {
3467 CallInst *UserInst = cast<CallInst>(*UI++);
3468 if (!UserInst->use_empty())
3469 UserInst->replaceAllUsesWith(UserInst->getArgOperand(0));
3470 UserInst->eraseFromParent();
3472 Alloca->eraseFromParent();
3478 /// OptimizeSequences - Identify program paths which execute sequences of
3479 /// retains and releases which can be eliminated.
3480 bool ObjCARCOpt::OptimizeSequences(Function &F) {
3481 /// Releases, Retains - These are used to store the results of the main flow
3482 /// analysis. These use Value* as the key instead of Instruction* so that the
3483 /// map stays valid when we get around to rewriting code and calls get
3484 /// replaced by arguments.
3485 DenseMap<Value *, RRInfo> Releases;
3486 MapVector<Value *, RRInfo> Retains;
3488 /// BBStates, This is used during the traversal of the function to track the
3489 /// states for each identified object at each block.
3490 DenseMap<const BasicBlock *, BBState> BBStates;
3492 // Analyze the CFG of the function, and all instructions.
3493 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3496 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3500 /// OptimizeReturns - Look for this pattern:
3502 /// %call = call i8* @something(...)
3503 /// %2 = call i8* @objc_retain(i8* %call)
3504 /// %3 = call i8* @objc_autorelease(i8* %2)
3507 /// And delete the retain and autorelease.
3509 /// Otherwise if it's just this:
3511 /// %3 = call i8* @objc_autorelease(i8* %2)
3514 /// convert the autorelease to autoreleaseRV.
3515 void ObjCARCOpt::OptimizeReturns(Function &F) {
3516 if (!F.getReturnType()->isPointerTy())
3519 SmallPtrSet<Instruction *, 4> DependingInstructions;
3520 SmallPtrSet<const BasicBlock *, 4> Visited;
3521 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3522 BasicBlock *BB = FI;
3523 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3526 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3527 FindDependencies(NeedsPositiveRetainCount, Arg,
3528 BB, Ret, DependingInstructions, Visited, PA);
3529 if (DependingInstructions.size() != 1)
3533 CallInst *Autorelease =
3534 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3537 InstructionClass AutoreleaseClass =
3538 GetBasicInstructionClass(Autorelease);
3539 if (!IsAutorelease(AutoreleaseClass))
3541 if (GetObjCArg(Autorelease) != Arg)
3544 DependingInstructions.clear();
3547 // Check that there is nothing that can affect the reference
3548 // count between the autorelease and the retain.
3549 FindDependencies(CanChangeRetainCount, Arg,
3550 BB, Autorelease, DependingInstructions, Visited, PA);
3551 if (DependingInstructions.size() != 1)
3556 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3558 // Check that we found a retain with the same argument.
3560 !IsRetain(GetBasicInstructionClass(Retain)) ||
3561 GetObjCArg(Retain) != Arg)
3564 DependingInstructions.clear();
3567 // Convert the autorelease to an autoreleaseRV, since it's
3568 // returning the value.
3569 if (AutoreleaseClass == IC_Autorelease) {
3570 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3571 AutoreleaseClass = IC_AutoreleaseRV;
3574 // Check that there is nothing that can affect the reference
3575 // count between the retain and the call.
3576 // Note that Retain need not be in BB.
3577 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3578 DependingInstructions, Visited, PA);
3579 if (DependingInstructions.size() != 1)
3584 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3586 // Check that the pointer is the return value of the call.
3587 if (!Call || Arg != Call)
3590 // Check that the call is a regular call.
3591 InstructionClass Class = GetBasicInstructionClass(Call);
3592 if (Class != IC_CallOrUser && Class != IC_Call)
3595 // If so, we can zap the retain and autorelease.
3598 EraseInstruction(Retain);
3599 EraseInstruction(Autorelease);
3605 DependingInstructions.clear();
3610 bool ObjCARCOpt::doInitialization(Module &M) {
3614 Run = ModuleHasARC(M);
3618 // Identify the imprecise release metadata kind.
3619 ImpreciseReleaseMDKind =
3620 M.getContext().getMDKindID("clang.imprecise_release");
3621 CopyOnEscapeMDKind =
3622 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3623 NoObjCARCExceptionsMDKind =
3624 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3626 // Intuitively, objc_retain and others are nocapture, however in practice
3627 // they are not, because they return their argument value. And objc_release
3628 // calls finalizers.
3630 // These are initialized lazily.
3632 AutoreleaseRVCallee = 0;
3635 RetainBlockCallee = 0;
3636 AutoreleaseCallee = 0;
3641 bool ObjCARCOpt::runOnFunction(Function &F) {
3645 // If nothing in the Module uses ARC, don't do anything.
3651 PA.setAA(&getAnalysis<AliasAnalysis>());
3653 // This pass performs several distinct transformations. As a compile-time aid
3654 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3655 // library functions aren't declared.
3657 // Preliminary optimizations. This also computs UsedInThisFunction.
3658 OptimizeIndividualCalls(F);
3660 // Optimizations for weak pointers.
3661 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3662 (1 << IC_LoadWeakRetained) |
3663 (1 << IC_StoreWeak) |
3664 (1 << IC_InitWeak) |
3665 (1 << IC_CopyWeak) |
3666 (1 << IC_MoveWeak) |
3667 (1 << IC_DestroyWeak)))
3668 OptimizeWeakCalls(F);
3670 // Optimizations for retain+release pairs.
3671 if (UsedInThisFunction & ((1 << IC_Retain) |
3672 (1 << IC_RetainRV) |
3673 (1 << IC_RetainBlock)))
3674 if (UsedInThisFunction & (1 << IC_Release))
3675 // Run OptimizeSequences until it either stops making changes or
3676 // no retain+release pair nesting is detected.
3677 while (OptimizeSequences(F)) {}
3679 // Optimizations if objc_autorelease is used.
3680 if (UsedInThisFunction &
3681 ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
3687 void ObjCARCOpt::releaseMemory() {
3691 //===----------------------------------------------------------------------===//
3693 //===----------------------------------------------------------------------===//
3695 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
3696 // dominated by single calls.
3698 #include "llvm/Operator.h"
3699 #include "llvm/InlineAsm.h"
3700 #include "llvm/Analysis/Dominators.h"
3702 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3705 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3706 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3707 class ObjCARCContract : public FunctionPass {
3711 ProvenanceAnalysis PA;
3713 /// Run - A flag indicating whether this optimization pass should run.
3716 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3717 /// functions, for use in creating calls to them. These are initialized
3718 /// lazily to avoid cluttering up the Module with unused declarations.
3719 Constant *StoreStrongCallee,
3720 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3722 /// RetainRVMarker - The inline asm string to insert between calls and
3723 /// RetainRV calls to make the optimization work on targets which need it.
3724 const MDString *RetainRVMarker;
3726 /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
3727 /// at the end of walking the function we have found no alloca
3728 /// instructions, these calls can be marked "tail".
3729 DenseSet<CallInst *> StoreStrongCalls;
3731 Constant *getStoreStrongCallee(Module *M);
3732 Constant *getRetainAutoreleaseCallee(Module *M);
3733 Constant *getRetainAutoreleaseRVCallee(Module *M);
3735 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3736 InstructionClass Class,
3737 SmallPtrSet<Instruction *, 4>
3738 &DependingInstructions,
3739 SmallPtrSet<const BasicBlock *, 4>
3742 void ContractRelease(Instruction *Release,
3743 inst_iterator &Iter);
3745 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3746 virtual bool doInitialization(Module &M);
3747 virtual bool runOnFunction(Function &F);
3751 ObjCARCContract() : FunctionPass(ID) {
3752 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3757 char ObjCARCContract::ID = 0;
3758 INITIALIZE_PASS_BEGIN(ObjCARCContract,
3759 "objc-arc-contract", "ObjC ARC contraction", false, false)
3760 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3761 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3762 INITIALIZE_PASS_END(ObjCARCContract,
3763 "objc-arc-contract", "ObjC ARC contraction", false, false)
3765 Pass *llvm::createObjCARCContractPass() {
3766 return new ObjCARCContract();
3769 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3770 AU.addRequired<AliasAnalysis>();
3771 AU.addRequired<DominatorTree>();
3772 AU.setPreservesCFG();
3775 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3776 if (!StoreStrongCallee) {
3777 LLVMContext &C = M->getContext();
3778 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3779 Type *I8XX = PointerType::getUnqual(I8X);
3780 std::vector<Type *> Params;
3781 Params.push_back(I8XX);
3782 Params.push_back(I8X);
3784 AttrListPtr Attributes;
3785 Attributes.addAttr(~0u, Attribute::NoUnwind);
3786 Attributes.addAttr(1, Attribute::NoCapture);
3789 M->getOrInsertFunction(
3791 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3794 return StoreStrongCallee;
3797 Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3798 if (!RetainAutoreleaseCallee) {
3799 LLVMContext &C = M->getContext();
3800 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3801 std::vector<Type *> Params;
3802 Params.push_back(I8X);
3804 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3805 AttrListPtr Attributes;
3806 Attributes.addAttr(~0u, Attribute::NoUnwind);
3807 RetainAutoreleaseCallee =
3808 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3810 return RetainAutoreleaseCallee;
3813 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3814 if (!RetainAutoreleaseRVCallee) {
3815 LLVMContext &C = M->getContext();
3816 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3817 std::vector<Type *> Params;
3818 Params.push_back(I8X);
3820 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3821 AttrListPtr Attributes;
3822 Attributes.addAttr(~0u, Attribute::NoUnwind);
3823 RetainAutoreleaseRVCallee =
3824 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3827 return RetainAutoreleaseRVCallee;
3830 /// ContractAutorelease - Merge an autorelease with a retain into a fused
3833 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3834 InstructionClass Class,
3835 SmallPtrSet<Instruction *, 4>
3836 &DependingInstructions,
3837 SmallPtrSet<const BasicBlock *, 4>
3839 const Value *Arg = GetObjCArg(Autorelease);
3841 // Check that there are no instructions between the retain and the autorelease
3842 // (such as an autorelease_pop) which may change the count.
3843 CallInst *Retain = 0;
3844 if (Class == IC_AutoreleaseRV)
3845 FindDependencies(RetainAutoreleaseRVDep, Arg,
3846 Autorelease->getParent(), Autorelease,
3847 DependingInstructions, Visited, PA);
3849 FindDependencies(RetainAutoreleaseDep, Arg,
3850 Autorelease->getParent(), Autorelease,
3851 DependingInstructions, Visited, PA);
3854 if (DependingInstructions.size() != 1) {
3855 DependingInstructions.clear();
3859 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3860 DependingInstructions.clear();
3863 GetBasicInstructionClass(Retain) != IC_Retain ||
3864 GetObjCArg(Retain) != Arg)
3870 if (Class == IC_AutoreleaseRV)
3871 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3873 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3875 EraseInstruction(Autorelease);
3879 /// ContractRelease - Attempt to merge an objc_release with a store, load, and
3880 /// objc_retain to form an objc_storeStrong. This can be a little tricky because
3881 /// the instructions don't always appear in order, and there may be unrelated
3882 /// intervening instructions.
3883 void ObjCARCContract::ContractRelease(Instruction *Release,
3884 inst_iterator &Iter) {
3885 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
3886 if (!Load || !Load->isSimple()) return;
3888 // For now, require everything to be in one basic block.
3889 BasicBlock *BB = Release->getParent();
3890 if (Load->getParent() != BB) return;
3892 // Walk down to find the store.
3893 BasicBlock::iterator I = Load, End = BB->end();
3895 AliasAnalysis::Location Loc = AA->getLocation(Load);
3898 IsRetain(GetBasicInstructionClass(I)) ||
3899 !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
3901 StoreInst *Store = dyn_cast<StoreInst>(I);
3902 if (!Store || !Store->isSimple()) return;
3903 if (Store->getPointerOperand() != Loc.Ptr) return;
3905 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3907 // Walk up to find the retain.
3909 BasicBlock::iterator Begin = BB->begin();
3910 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3912 Instruction *Retain = I;
3913 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3914 if (GetObjCArg(Retain) != New) return;
3919 LLVMContext &C = Release->getContext();
3920 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3921 Type *I8XX = PointerType::getUnqual(I8X);
3923 Value *Args[] = { Load->getPointerOperand(), New };
3924 if (Args[0]->getType() != I8XX)
3925 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3926 if (Args[1]->getType() != I8X)
3927 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3928 CallInst *StoreStrong =
3929 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
3931 StoreStrong->setDoesNotThrow();
3932 StoreStrong->setDebugLoc(Store->getDebugLoc());
3934 // We can't set the tail flag yet, because we haven't yet determined
3935 // whether there are any escaping allocas. Remember this call, so that
3936 // we can set the tail flag once we know it's safe.
3937 StoreStrongCalls.insert(StoreStrong);
3939 if (&*Iter == Store) ++Iter;
3940 Store->eraseFromParent();
3941 Release->eraseFromParent();
3942 EraseInstruction(Retain);
3943 if (Load->use_empty())
3944 Load->eraseFromParent();
3947 bool ObjCARCContract::doInitialization(Module &M) {
3948 Run = ModuleHasARC(M);
3952 // These are initialized lazily.
3953 StoreStrongCallee = 0;
3954 RetainAutoreleaseCallee = 0;
3955 RetainAutoreleaseRVCallee = 0;
3957 // Initialize RetainRVMarker.
3959 if (NamedMDNode *NMD =
3960 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3961 if (NMD->getNumOperands() == 1) {
3962 const MDNode *N = NMD->getOperand(0);
3963 if (N->getNumOperands() == 1)
3964 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
3971 bool ObjCARCContract::runOnFunction(Function &F) {
3975 // If nothing in the Module uses ARC, don't do anything.
3980 AA = &getAnalysis<AliasAnalysis>();
3981 DT = &getAnalysis<DominatorTree>();
3983 PA.setAA(&getAnalysis<AliasAnalysis>());
3985 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
3986 // keyword. Be conservative if the function has variadic arguments.
3987 // It seems that functions which "return twice" are also unsafe for the
3988 // "tail" argument, because they are setjmp, which could need to
3989 // return to an earlier stack state.
3990 bool TailOkForStoreStrongs = !F.isVarArg() && !F.callsFunctionThatReturnsTwice();
3992 // For ObjC library calls which return their argument, replace uses of the
3993 // argument with uses of the call return value, if it dominates the use. This
3994 // reduces register pressure.
3995 SmallPtrSet<Instruction *, 4> DependingInstructions;
3996 SmallPtrSet<const BasicBlock *, 4> Visited;
3997 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3998 Instruction *Inst = &*I++;
4000 // Only these library routines return their argument. In particular,
4001 // objc_retainBlock does not necessarily return its argument.
4002 InstructionClass Class = GetBasicInstructionClass(Inst);
4005 case IC_FusedRetainAutorelease:
4006 case IC_FusedRetainAutoreleaseRV:
4008 case IC_Autorelease:
4009 case IC_AutoreleaseRV:
4010 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4014 // If we're compiling for a target which needs a special inline-asm
4015 // marker to do the retainAutoreleasedReturnValue optimization,
4017 if (!RetainRVMarker)
4019 BasicBlock::iterator BBI = Inst;
4021 while (isNoopInstruction(BBI)) --BBI;
4022 if (&*BBI == GetObjCArg(Inst)) {
4024 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4025 /*isVarArg=*/false),
4026 RetainRVMarker->getString(),
4027 /*Constraints=*/"", /*hasSideEffects=*/true);
4028 CallInst::Create(IA, "", Inst);
4033 // objc_initWeak(p, null) => *p = null
4034 CallInst *CI = cast<CallInst>(Inst);
4035 if (isNullOrUndef(CI->getArgOperand(1))) {
4037 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4039 new StoreInst(Null, CI->getArgOperand(0), CI);
4040 CI->replaceAllUsesWith(Null);
4041 CI->eraseFromParent();
4046 ContractRelease(Inst, I);
4049 // Be conservative if the function has any alloca instructions.
4050 // Technically we only care about escaping alloca instructions,
4051 // but this is sufficient to handle some interesting cases.
4052 if (isa<AllocaInst>(Inst))
4053 TailOkForStoreStrongs = false;
4059 // Don't use GetObjCArg because we don't want to look through bitcasts
4060 // and such; to do the replacement, the argument must have type i8*.
4061 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4063 // If we're compiling bugpointed code, don't get in trouble.
4064 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4066 // Look through the uses of the pointer.
4067 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4069 Use &U = UI.getUse();
4070 unsigned OperandNo = UI.getOperandNo();
4071 ++UI; // Increment UI now, because we may unlink its element.
4072 Instruction *UserInst = dyn_cast<Instruction>(U.getUser());
4075 // FIXME: dominates should return true for unreachable UserInst.
4076 if (!DT->isReachableFromEntry(UserInst->getParent()) ||
4077 DT->dominates(Inst, UserInst)) {
4079 Instruction *Replacement = Inst;
4080 Type *UseTy = U.get()->getType();
4081 if (PHINode *PHI = dyn_cast<PHINode>(UserInst)) {
4082 // For PHI nodes, insert the bitcast in the predecessor block.
4084 PHINode::getIncomingValueNumForOperand(OperandNo);
4086 PHI->getIncomingBlock(ValNo);
4087 if (Replacement->getType() != UseTy)
4088 Replacement = new BitCastInst(Replacement, UseTy, "",
4090 for (unsigned i = 0, e = PHI->getNumIncomingValues();
4092 if (PHI->getIncomingBlock(i) == BB) {
4093 // Keep the UI iterator valid.
4094 if (&PHI->getOperandUse(
4095 PHINode::getOperandNumForIncomingValue(i)) ==
4098 PHI->setIncomingValue(i, Replacement);
4101 if (Replacement->getType() != UseTy)
4102 Replacement = new BitCastInst(Replacement, UseTy, "", UserInst);
4108 // If Arg is a no-op casted pointer, strip one level of casts and
4110 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4111 Arg = BI->getOperand(0);
4112 else if (isa<GEPOperator>(Arg) &&
4113 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4114 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4115 else if (isa<GlobalAlias>(Arg) &&
4116 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4117 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4123 // If this function has no escaping allocas or suspicious vararg usage,
4124 // objc_storeStrong calls can be marked with the "tail" keyword.
4125 if (TailOkForStoreStrongs)
4126 for (DenseSet<CallInst *>::iterator I = StoreStrongCalls.begin(),
4127 E = StoreStrongCalls.end(); I != E; ++I)
4128 (*I)->setTailCall();
4129 StoreStrongCalls.clear();