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 knowledge 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/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/raw_ostream.h"
39 // A handy option to enable/disable all optimizations in this file.
40 static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
42 //===----------------------------------------------------------------------===//
44 //===----------------------------------------------------------------------===//
47 /// MapVector - An associative container with fast insertion-order
48 /// (deterministic) iteration over its elements. Plus the special
50 template<class KeyT, class ValueT>
52 /// Map - Map keys to indices in Vector.
53 typedef DenseMap<KeyT, size_t> MapTy;
56 /// Vector - Keys and values.
57 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
61 typedef typename VectorTy::iterator iterator;
62 typedef typename VectorTy::const_iterator const_iterator;
63 iterator begin() { return Vector.begin(); }
64 iterator end() { return Vector.end(); }
65 const_iterator begin() const { return Vector.begin(); }
66 const_iterator end() const { return Vector.end(); }
70 assert(Vector.size() >= Map.size()); // May differ due to blotting.
71 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
73 assert(I->second < Vector.size());
74 assert(Vector[I->second].first == I->first);
76 for (typename VectorTy::const_iterator I = Vector.begin(),
77 E = Vector.end(); I != E; ++I)
79 (Map.count(I->first) &&
80 Map[I->first] == size_t(I - Vector.begin())));
84 ValueT &operator[](const KeyT &Arg) {
85 std::pair<typename MapTy::iterator, bool> Pair =
86 Map.insert(std::make_pair(Arg, size_t(0)));
88 size_t Num = Vector.size();
89 Pair.first->second = Num;
90 Vector.push_back(std::make_pair(Arg, ValueT()));
91 return Vector[Num].second;
93 return Vector[Pair.first->second].second;
96 std::pair<iterator, bool>
97 insert(const std::pair<KeyT, ValueT> &InsertPair) {
98 std::pair<typename MapTy::iterator, bool> Pair =
99 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
101 size_t Num = Vector.size();
102 Pair.first->second = Num;
103 Vector.push_back(InsertPair);
104 return std::make_pair(Vector.begin() + Num, true);
106 return std::make_pair(Vector.begin() + Pair.first->second, false);
109 const_iterator find(const KeyT &Key) const {
110 typename MapTy::const_iterator It = Map.find(Key);
111 if (It == Map.end()) return Vector.end();
112 return Vector.begin() + It->second;
115 /// blot - This is similar to erase, but instead of removing the element
116 /// from the vector, it just zeros out the key in the vector. This leaves
117 /// iterators intact, but clients must be prepared for zeroed-out keys when
119 void blot(const KeyT &Key) {
120 typename MapTy::iterator It = Map.find(Key);
121 if (It == Map.end()) return;
122 Vector[It->second].first = KeyT();
133 //===----------------------------------------------------------------------===//
135 //===----------------------------------------------------------------------===//
137 #include "llvm/ADT/StringSwitch.h"
138 #include "llvm/Analysis/ValueTracking.h"
139 #include "llvm/IR/Intrinsics.h"
140 #include "llvm/IR/Module.h"
141 #include "llvm/Support/CallSite.h"
142 #include "llvm/Transforms/Utils/Local.h"
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_StoreStrong, ///< objc_storeStrong (derived)
166 IC_CallOrUser, ///< could call objc_release and/or "use" pointers
167 IC_Call, ///< could call objc_release
168 IC_User, ///< could "use" a pointer
169 IC_None ///< anything else
173 /// IsPotentialUse - Test whether the given value is possible a
174 /// reference-counted pointer.
175 static bool IsPotentialUse(const Value *Op) {
176 // Pointers to static or stack storage are not reference-counted pointers.
177 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
179 // Special arguments are not reference-counted.
180 if (const Argument *Arg = dyn_cast<Argument>(Op))
181 if (Arg->hasByValAttr() ||
182 Arg->hasNestAttr() ||
183 Arg->hasStructRetAttr())
185 // Only consider values with pointer types.
186 // It seemes intuitive to exclude function pointer types as well, since
187 // functions are never reference-counted, however clang occasionally
188 // bitcasts reference-counted pointers to function-pointer type
190 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
193 // Conservatively assume anything else is a potential use.
197 /// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind
198 /// of construct CS is.
199 static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
200 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
202 if (IsPotentialUse(*I))
203 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
205 return CS.onlyReadsMemory() ? IC_None : IC_Call;
208 /// GetFunctionClass - Determine if F is one of the special known Functions.
209 /// If it isn't, return IC_CallOrUser.
210 static InstructionClass GetFunctionClass(const Function *F) {
211 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
215 return StringSwitch<InstructionClass>(F->getName())
216 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
217 .Default(IC_CallOrUser);
220 const Argument *A0 = AI++;
222 // Argument is a pointer.
223 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
224 Type *ETy = PTy->getElementType();
226 if (ETy->isIntegerTy(8))
227 return StringSwitch<InstructionClass>(F->getName())
228 .Case("objc_retain", IC_Retain)
229 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
230 .Case("objc_retainBlock", IC_RetainBlock)
231 .Case("objc_release", IC_Release)
232 .Case("objc_autorelease", IC_Autorelease)
233 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
234 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
235 .Case("objc_retainedObject", IC_NoopCast)
236 .Case("objc_unretainedObject", IC_NoopCast)
237 .Case("objc_unretainedPointer", IC_NoopCast)
238 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
239 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
240 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
241 .Default(IC_CallOrUser);
244 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
245 if (Pte->getElementType()->isIntegerTy(8))
246 return StringSwitch<InstructionClass>(F->getName())
247 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
248 .Case("objc_loadWeak", IC_LoadWeak)
249 .Case("objc_destroyWeak", IC_DestroyWeak)
250 .Default(IC_CallOrUser);
253 // Two arguments, first is i8**.
254 const Argument *A1 = AI++;
256 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
257 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
258 if (Pte->getElementType()->isIntegerTy(8))
259 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
260 Type *ETy1 = PTy1->getElementType();
261 // Second argument is i8*
262 if (ETy1->isIntegerTy(8))
263 return StringSwitch<InstructionClass>(F->getName())
264 .Case("objc_storeWeak", IC_StoreWeak)
265 .Case("objc_initWeak", IC_InitWeak)
266 .Case("objc_storeStrong", IC_StoreStrong)
267 .Default(IC_CallOrUser);
268 // Second argument is i8**.
269 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
270 if (Pte1->getElementType()->isIntegerTy(8))
271 return StringSwitch<InstructionClass>(F->getName())
272 .Case("objc_moveWeak", IC_MoveWeak)
273 .Case("objc_copyWeak", IC_CopyWeak)
274 .Default(IC_CallOrUser);
278 return IC_CallOrUser;
281 /// GetInstructionClass - Determine what kind of construct V is.
282 static InstructionClass GetInstructionClass(const Value *V) {
283 if (const Instruction *I = dyn_cast<Instruction>(V)) {
284 // Any instruction other than bitcast and gep with a pointer operand have a
285 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
286 // to a subsequent use, rather than using it themselves, in this sense.
287 // As a short cut, several other opcodes are known to have no pointer
288 // operands of interest. And ret is never followed by a release, so it's
289 // not interesting to examine.
290 switch (I->getOpcode()) {
291 case Instruction::Call: {
292 const CallInst *CI = cast<CallInst>(I);
293 // Check for calls to special functions.
294 if (const Function *F = CI->getCalledFunction()) {
295 InstructionClass Class = GetFunctionClass(F);
296 if (Class != IC_CallOrUser)
299 // None of the intrinsic functions do objc_release. For intrinsics, the
300 // only question is whether or not they may be users.
301 switch (F->getIntrinsicID()) {
302 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
303 case Intrinsic::stacksave: case Intrinsic::stackrestore:
304 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
305 case Intrinsic::objectsize: case Intrinsic::prefetch:
306 case Intrinsic::stackprotector:
307 case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
308 case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
309 case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
310 case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
311 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
312 case Intrinsic::invariant_start: case Intrinsic::invariant_end:
313 // Don't let dbg info affect our results.
314 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
315 // Short cut: Some intrinsics obviously don't use ObjC pointers.
321 return GetCallSiteClass(CI);
323 case Instruction::Invoke:
324 return GetCallSiteClass(cast<InvokeInst>(I));
325 case Instruction::BitCast:
326 case Instruction::GetElementPtr:
327 case Instruction::Select: case Instruction::PHI:
328 case Instruction::Ret: case Instruction::Br:
329 case Instruction::Switch: case Instruction::IndirectBr:
330 case Instruction::Alloca: case Instruction::VAArg:
331 case Instruction::Add: case Instruction::FAdd:
332 case Instruction::Sub: case Instruction::FSub:
333 case Instruction::Mul: case Instruction::FMul:
334 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
335 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
336 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
337 case Instruction::And: case Instruction::Or: case Instruction::Xor:
338 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
339 case Instruction::IntToPtr: case Instruction::FCmp:
340 case Instruction::FPTrunc: case Instruction::FPExt:
341 case Instruction::FPToUI: case Instruction::FPToSI:
342 case Instruction::UIToFP: case Instruction::SIToFP:
343 case Instruction::InsertElement: case Instruction::ExtractElement:
344 case Instruction::ShuffleVector:
345 case Instruction::ExtractValue:
347 case Instruction::ICmp:
348 // Comparing a pointer with null, or any other constant, isn't an
349 // interesting use, because we don't care what the pointer points to, or
350 // about the values of any other dynamic reference-counted pointers.
351 if (IsPotentialUse(I->getOperand(1)))
355 // For anything else, check all the operands.
356 // Note that this includes both operands of a Store: while the first
357 // operand isn't actually being dereferenced, it is being stored to
358 // memory where we can no longer track who might read it and dereference
359 // it, so we have to consider it potentially used.
360 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
362 if (IsPotentialUse(*OI))
367 // Otherwise, it's totally inert for ARC purposes.
371 /// GetBasicInstructionClass - Determine what kind of construct V is. This is
372 /// similar to GetInstructionClass except that it only detects objc runtine
373 /// calls. This allows it to be faster.
374 static InstructionClass GetBasicInstructionClass(const Value *V) {
375 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
376 if (const Function *F = CI->getCalledFunction())
377 return GetFunctionClass(F);
378 // Otherwise, be conservative.
379 return IC_CallOrUser;
382 // Otherwise, be conservative.
383 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
386 /// IsRetain - Test if the given class is objc_retain or
388 static bool IsRetain(InstructionClass Class) {
389 return Class == IC_Retain ||
390 Class == IC_RetainRV;
393 /// IsAutorelease - Test if the given class is objc_autorelease or
395 static bool IsAutorelease(InstructionClass Class) {
396 return Class == IC_Autorelease ||
397 Class == IC_AutoreleaseRV;
400 /// IsForwarding - Test if the given class represents instructions which return
401 /// their argument verbatim.
402 static bool IsForwarding(InstructionClass Class) {
403 // objc_retainBlock technically doesn't always return its argument
404 // verbatim, but it doesn't matter for our purposes here.
405 return Class == IC_Retain ||
406 Class == IC_RetainRV ||
407 Class == IC_Autorelease ||
408 Class == IC_AutoreleaseRV ||
409 Class == IC_RetainBlock ||
410 Class == IC_NoopCast;
413 /// IsNoopOnNull - Test if the given class represents instructions which do
414 /// nothing if passed a null pointer.
415 static bool IsNoopOnNull(InstructionClass Class) {
416 return Class == IC_Retain ||
417 Class == IC_RetainRV ||
418 Class == IC_Release ||
419 Class == IC_Autorelease ||
420 Class == IC_AutoreleaseRV ||
421 Class == IC_RetainBlock;
424 /// IsAlwaysTail - Test if the given class represents instructions which are
425 /// always safe to mark with the "tail" keyword.
426 static bool IsAlwaysTail(InstructionClass Class) {
427 // IC_RetainBlock may be given a stack argument.
428 return Class == IC_Retain ||
429 Class == IC_RetainRV ||
430 Class == IC_AutoreleaseRV;
433 /// \brief Test if the given class represents instructions which are never safe
434 /// to mark with the "tail" keyword.
435 static bool IsNeverTail(InstructionClass Class) {
436 /// It is never safe to tail call objc_autorelease since by tail calling
437 /// objc_autorelease, we also tail call -[NSObject autorelease] which supports
438 /// fast autoreleasing causing our object to be potentially reclaimed from the
439 /// autorelease pool which violates the semantics of __autoreleasing types in
441 return Class == IC_Autorelease;
444 /// IsNoThrow - Test if the given class represents instructions which are always
445 /// safe to mark with the nounwind attribute..
446 static bool IsNoThrow(InstructionClass Class) {
447 // objc_retainBlock is not nounwind because it calls user copy constructors
448 // which could theoretically throw.
449 return Class == IC_Retain ||
450 Class == IC_RetainRV ||
451 Class == IC_Release ||
452 Class == IC_Autorelease ||
453 Class == IC_AutoreleaseRV ||
454 Class == IC_AutoreleasepoolPush ||
455 Class == IC_AutoreleasepoolPop;
458 /// EraseInstruction - Erase the given instruction. Many ObjC calls return their
459 /// argument verbatim, so if it's such a call and the return value has users,
460 /// replace them with the argument value.
461 static void EraseInstruction(Instruction *CI) {
462 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
464 bool Unused = CI->use_empty();
467 // Replace the return value with the argument.
468 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
469 "Can't delete non-forwarding instruction with users!");
470 CI->replaceAllUsesWith(OldArg);
473 CI->eraseFromParent();
476 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
479 /// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
480 /// also knows how to look through objc_retain and objc_autorelease calls, which
481 /// we know to return their argument verbatim.
482 static const Value *GetUnderlyingObjCPtr(const Value *V) {
484 V = GetUnderlyingObject(V);
485 if (!IsForwarding(GetBasicInstructionClass(V)))
487 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 const Value *StripPointerCastsAndObjCCalls(const Value *V) {
498 V = V->stripPointerCasts();
499 if (!IsForwarding(GetBasicInstructionClass(V)))
501 V = cast<CallInst>(V)->getArgOperand(0);
506 /// StripPointerCastsAndObjCCalls - This is a wrapper around
507 /// Value::stripPointerCasts which also knows how to look through objc_retain
508 /// and objc_autorelease calls, which we know to return their argument verbatim.
509 static Value *StripPointerCastsAndObjCCalls(Value *V) {
511 V = V->stripPointerCasts();
512 if (!IsForwarding(GetBasicInstructionClass(V)))
514 V = cast<CallInst>(V)->getArgOperand(0);
519 /// GetObjCArg - Assuming the given instruction is one of the special calls such
520 /// as objc_retain or objc_release, return the argument value, stripped of no-op
521 /// casts and forwarding calls.
522 static Value *GetObjCArg(Value *Inst) {
523 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
526 /// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
527 /// isObjCIdentifiedObject, except that it uses special knowledge of
528 /// ObjC conventions...
529 static bool IsObjCIdentifiedObject(const Value *V) {
530 // Assume that call results and arguments have their own "provenance".
531 // Constants (including GlobalVariables) and Allocas are never
532 // reference-counted.
533 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
534 isa<Argument>(V) || isa<Constant>(V) ||
538 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
539 const Value *Pointer =
540 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
541 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
542 // A constant pointer can't be pointing to an object on the heap. It may
543 // be reference-counted, but it won't be deleted.
544 if (GV->isConstant())
546 StringRef Name = GV->getName();
547 // These special variables are known to hold values which are not
548 // reference-counted pointers.
549 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
550 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
551 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
552 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
553 Name.startswith("\01l_objc_msgSend_fixup_"))
561 /// FindSingleUseIdentifiedObject - This is similar to
562 /// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
563 /// with multiple uses.
564 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
565 if (Arg->hasOneUse()) {
566 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
567 return FindSingleUseIdentifiedObject(BC->getOperand(0));
568 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
569 if (GEP->hasAllZeroIndices())
570 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
571 if (IsForwarding(GetBasicInstructionClass(Arg)))
572 return FindSingleUseIdentifiedObject(
573 cast<CallInst>(Arg)->getArgOperand(0));
574 if (!IsObjCIdentifiedObject(Arg))
579 // If we found an identifiable object but it has multiple uses, but they are
580 // trivial uses, we can still consider this to be a single-use value.
581 if (IsObjCIdentifiedObject(Arg)) {
582 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
585 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
595 /// ModuleHasARC - Test if the given module looks interesting to run ARC
597 static bool ModuleHasARC(const Module &M) {
599 M.getNamedValue("objc_retain") ||
600 M.getNamedValue("objc_release") ||
601 M.getNamedValue("objc_autorelease") ||
602 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
603 M.getNamedValue("objc_retainBlock") ||
604 M.getNamedValue("objc_autoreleaseReturnValue") ||
605 M.getNamedValue("objc_autoreleasePoolPush") ||
606 M.getNamedValue("objc_loadWeakRetained") ||
607 M.getNamedValue("objc_loadWeak") ||
608 M.getNamedValue("objc_destroyWeak") ||
609 M.getNamedValue("objc_storeWeak") ||
610 M.getNamedValue("objc_initWeak") ||
611 M.getNamedValue("objc_moveWeak") ||
612 M.getNamedValue("objc_copyWeak") ||
613 M.getNamedValue("objc_retainedObject") ||
614 M.getNamedValue("objc_unretainedObject") ||
615 M.getNamedValue("objc_unretainedPointer");
618 /// DoesObjCBlockEscape - Test whether the given pointer, which is an
619 /// Objective C block pointer, does not "escape". This differs from regular
620 /// escape analysis in that a use as an argument to a call is not considered
622 static bool DoesObjCBlockEscape(const Value *BlockPtr) {
624 DEBUG(dbgs() << "DoesObjCBlockEscape: Target: " << *BlockPtr << "\n");
626 // Walk the def-use chains.
627 SmallVector<const Value *, 4> Worklist;
628 Worklist.push_back(BlockPtr);
630 // Ensure we do not visit any value twice.
631 SmallPtrSet<const Value *, 4> VisitedSet;
634 const Value *V = Worklist.pop_back_val();
636 DEBUG(dbgs() << "DoesObjCBlockEscape: Visiting: " << *V << "\n");
638 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
640 const User *UUser = *UI;
642 DEBUG(dbgs() << "DoesObjCBlockEscape: User: " << *UUser << "\n");
644 // Special - Use by a call (callee or argument) is not considered
646 switch (GetBasicInstructionClass(UUser)) {
651 case IC_AutoreleaseRV: {
652 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies pointer arguments. "
654 // These special functions make copies of their pointer arguments.
659 // Use by an instruction which copies the value is an escape if the
660 // result is an escape.
661 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
662 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
664 if (!VisitedSet.count(UUser)) {
665 DEBUG(dbgs() << "DoesObjCBlockEscape: User copies value. Escapes if "
666 "result escapes. Adding to list.\n");
667 VisitedSet.insert(V);
668 Worklist.push_back(UUser);
670 DEBUG(dbgs() << "DoesObjCBlockEscape: Already visited node.\n");
674 // Use by a load is not an escape.
675 if (isa<LoadInst>(UUser))
677 // Use by a store is not an escape if the use is the address.
678 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
679 if (V != SI->getValueOperand())
683 // Regular calls and other stuff are not considered escapes.
686 // Otherwise, conservatively assume an escape.
687 DEBUG(dbgs() << "DoesObjCBlockEscape: Assuming block escapes.\n");
690 } while (!Worklist.empty());
693 DEBUG(dbgs() << "DoesObjCBlockEscape: Block does not escape.\n");
697 //===----------------------------------------------------------------------===//
698 // ARC AliasAnalysis.
699 //===----------------------------------------------------------------------===//
701 #include "llvm/Analysis/AliasAnalysis.h"
702 #include "llvm/Analysis/Passes.h"
703 #include "llvm/Pass.h"
706 /// ObjCARCAliasAnalysis - This is a simple alias analysis
707 /// implementation that uses knowledge of ARC constructs to answer queries.
709 /// TODO: This class could be generalized to know about other ObjC-specific
710 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
711 /// even though their offsets are dynamic.
712 class ObjCARCAliasAnalysis : public ImmutablePass,
713 public AliasAnalysis {
715 static char ID; // Class identification, replacement for typeinfo
716 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
717 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
721 virtual void initializePass() {
722 InitializeAliasAnalysis(this);
725 /// getAdjustedAnalysisPointer - This method is used when a pass implements
726 /// an analysis interface through multiple inheritance. If needed, it
727 /// should override this to adjust the this pointer as needed for the
728 /// specified pass info.
729 virtual void *getAdjustedAnalysisPointer(const void *PI) {
730 if (PI == &AliasAnalysis::ID)
731 return static_cast<AliasAnalysis *>(this);
735 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
736 virtual AliasResult alias(const Location &LocA, const Location &LocB);
737 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
738 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
739 virtual ModRefBehavior getModRefBehavior(const Function *F);
740 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
741 const Location &Loc);
742 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
743 ImmutableCallSite CS2);
745 } // End of anonymous namespace
747 // Register this pass...
748 char ObjCARCAliasAnalysis::ID = 0;
749 INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
750 "ObjC-ARC-Based Alias Analysis", false, true, false)
752 ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
753 return new ObjCARCAliasAnalysis();
757 ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
758 AU.setPreservesAll();
759 AliasAnalysis::getAnalysisUsage(AU);
762 AliasAnalysis::AliasResult
763 ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
765 return AliasAnalysis::alias(LocA, LocB);
767 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
768 // precise alias query.
769 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
770 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
772 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
773 Location(SB, LocB.Size, LocB.TBAATag));
774 if (Result != MayAlias)
777 // If that failed, climb to the underlying object, including climbing through
778 // ObjC-specific no-ops, and try making an imprecise alias query.
779 const Value *UA = GetUnderlyingObjCPtr(SA);
780 const Value *UB = GetUnderlyingObjCPtr(SB);
781 if (UA != SA || UB != SB) {
782 Result = AliasAnalysis::alias(Location(UA), Location(UB));
783 // We can't use MustAlias or PartialAlias results here because
784 // GetUnderlyingObjCPtr may return an offsetted pointer value.
785 if (Result == NoAlias)
789 // If that failed, fail. We don't need to chain here, since that's covered
790 // by the earlier precise query.
795 ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
798 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
800 // First, strip off no-ops, including ObjC-specific no-ops, and try making
801 // a precise alias query.
802 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
803 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
807 // If that failed, climb to the underlying object, including climbing through
808 // ObjC-specific no-ops, and try making an imprecise alias query.
809 const Value *U = GetUnderlyingObjCPtr(S);
811 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
813 // If that failed, fail. We don't need to chain here, since that's covered
814 // by the earlier precise query.
818 AliasAnalysis::ModRefBehavior
819 ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
820 // We have nothing to do. Just chain to the next AliasAnalysis.
821 return AliasAnalysis::getModRefBehavior(CS);
824 AliasAnalysis::ModRefBehavior
825 ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
827 return AliasAnalysis::getModRefBehavior(F);
829 switch (GetFunctionClass(F)) {
831 return DoesNotAccessMemory;
836 return AliasAnalysis::getModRefBehavior(F);
839 AliasAnalysis::ModRefResult
840 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
842 return AliasAnalysis::getModRefInfo(CS, Loc);
844 switch (GetBasicInstructionClass(CS.getInstruction())) {
848 case IC_AutoreleaseRV:
850 case IC_AutoreleasepoolPush:
851 case IC_FusedRetainAutorelease:
852 case IC_FusedRetainAutoreleaseRV:
853 // These functions don't access any memory visible to the compiler.
854 // Note that this doesn't include objc_retainBlock, because it updates
855 // pointers when it copies block data.
861 return AliasAnalysis::getModRefInfo(CS, Loc);
864 AliasAnalysis::ModRefResult
865 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
866 ImmutableCallSite CS2) {
867 // TODO: Theoretically we could check for dependencies between objc_* calls
868 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
869 return AliasAnalysis::getModRefInfo(CS1, CS2);
872 //===----------------------------------------------------------------------===//
874 //===----------------------------------------------------------------------===//
876 #include "llvm/Support/InstIterator.h"
877 #include "llvm/Transforms/Scalar.h"
880 /// ObjCARCExpand - Early ARC transformations.
881 class ObjCARCExpand : public FunctionPass {
882 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
883 virtual bool doInitialization(Module &M);
884 virtual bool runOnFunction(Function &F);
886 /// Run - A flag indicating whether this optimization pass should run.
891 ObjCARCExpand() : FunctionPass(ID) {
892 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
897 char ObjCARCExpand::ID = 0;
898 INITIALIZE_PASS(ObjCARCExpand,
899 "objc-arc-expand", "ObjC ARC expansion", false, false)
901 Pass *llvm::createObjCARCExpandPass() {
902 return new ObjCARCExpand();
905 void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
906 AU.setPreservesCFG();
909 bool ObjCARCExpand::doInitialization(Module &M) {
910 Run = ModuleHasARC(M);
914 bool ObjCARCExpand::runOnFunction(Function &F) {
918 // If nothing in the Module uses ARC, don't do anything.
922 bool Changed = false;
924 DEBUG(dbgs() << "ObjCARCExpand: Visiting Function: " << F.getName() << "\n");
926 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
927 Instruction *Inst = &*I;
929 DEBUG(dbgs() << "ObjCARCExpand: Visiting: " << *Inst << "\n");
931 switch (GetBasicInstructionClass(Inst)) {
935 case IC_AutoreleaseRV:
936 case IC_FusedRetainAutorelease:
937 case IC_FusedRetainAutoreleaseRV: {
938 // These calls return their argument verbatim, as a low-level
939 // optimization. However, this makes high-level optimizations
940 // harder. Undo any uses of this optimization that the front-end
941 // emitted here. We'll redo them in the contract pass.
943 Value *Value = cast<CallInst>(Inst)->getArgOperand(0);
944 DEBUG(dbgs() << "ObjCARCExpand: Old = " << *Inst << "\n"
945 " New = " << *Value << "\n");
946 Inst->replaceAllUsesWith(Value);
954 DEBUG(dbgs() << "ObjCARCExpand: Finished List.\n\n");
959 //===----------------------------------------------------------------------===//
960 // ARC autorelease pool elimination.
961 //===----------------------------------------------------------------------===//
963 #include "llvm/ADT/STLExtras.h"
964 #include "llvm/IR/Constants.h"
967 /// ObjCARCAPElim - Autorelease pool elimination.
968 class ObjCARCAPElim : public ModulePass {
969 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
970 virtual bool runOnModule(Module &M);
972 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
973 static bool OptimizeBB(BasicBlock *BB);
977 ObjCARCAPElim() : ModulePass(ID) {
978 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
983 char ObjCARCAPElim::ID = 0;
984 INITIALIZE_PASS(ObjCARCAPElim,
986 "ObjC ARC autorelease pool elimination",
989 Pass *llvm::createObjCARCAPElimPass() {
990 return new ObjCARCAPElim();
993 void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
994 AU.setPreservesCFG();
997 /// MayAutorelease - Interprocedurally determine if calls made by the
998 /// given call site can possibly produce autoreleases.
999 bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
1000 if (const Function *Callee = CS.getCalledFunction()) {
1001 if (Callee->isDeclaration() || Callee->mayBeOverridden())
1003 for (Function::const_iterator I = Callee->begin(), E = Callee->end();
1005 const BasicBlock *BB = I;
1006 for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
1008 if (ImmutableCallSite JCS = ImmutableCallSite(J))
1009 // This recursion depth limit is arbitrary. It's just great
1010 // enough to cover known interesting testcases.
1012 !JCS.onlyReadsMemory() &&
1013 MayAutorelease(JCS, Depth + 1))
1022 bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
1023 bool Changed = false;
1025 Instruction *Push = 0;
1026 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1027 Instruction *Inst = I++;
1028 switch (GetBasicInstructionClass(Inst)) {
1029 case IC_AutoreleasepoolPush:
1032 case IC_AutoreleasepoolPop:
1033 // If this pop matches a push and nothing in between can autorelease,
1035 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
1037 DEBUG(dbgs() << "ObjCARCAPElim::OptimizeBB: Zapping push pop autorelease pair:\n"
1038 << " Pop: " << *Inst << "\n"
1039 << " Push: " << *Push << "\n");
1040 Inst->eraseFromParent();
1041 Push->eraseFromParent();
1046 if (MayAutorelease(ImmutableCallSite(Inst)))
1057 bool ObjCARCAPElim::runOnModule(Module &M) {
1061 // If nothing in the Module uses ARC, don't do anything.
1062 if (!ModuleHasARC(M))
1065 // Find the llvm.global_ctors variable, as the first step in
1066 // identifying the global constructors. In theory, unnecessary autorelease
1067 // pools could occur anywhere, but in practice it's pretty rare. Global
1068 // ctors are a place where autorelease pools get inserted automatically,
1069 // so it's pretty common for them to be unnecessary, and it's pretty
1070 // profitable to eliminate them.
1071 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1075 assert(GV->hasDefinitiveInitializer() &&
1076 "llvm.global_ctors is uncooperative!");
1078 bool Changed = false;
1080 // Dig the constructor functions out of GV's initializer.
1081 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1082 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1085 // llvm.global_ctors is an array of pairs where the second members
1086 // are constructor functions.
1087 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1088 // If the user used a constructor function with the wrong signature and
1089 // it got bitcasted or whatever, look the other way.
1092 // Only look at function definitions.
1093 if (F->isDeclaration())
1095 // Only look at functions with one basic block.
1096 if (llvm::next(F->begin()) != F->end())
1098 // Ok, a single-block constructor function definition. Try to optimize it.
1099 Changed |= OptimizeBB(F->begin());
1105 //===----------------------------------------------------------------------===//
1106 // ARC optimization.
1107 //===----------------------------------------------------------------------===//
1109 // TODO: On code like this:
1112 // stuff_that_cannot_release()
1113 // objc_autorelease(%x)
1114 // stuff_that_cannot_release()
1116 // stuff_that_cannot_release()
1117 // objc_autorelease(%x)
1119 // The second retain and autorelease can be deleted.
1121 // TODO: It should be possible to delete
1122 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
1123 // pairs if nothing is actually autoreleased between them. Also, autorelease
1124 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1125 // after inlining) can be turned into plain release calls.
1127 // TODO: Critical-edge splitting. If the optimial insertion point is
1128 // a critical edge, the current algorithm has to fail, because it doesn't
1129 // know how to split edges. It should be possible to make the optimizer
1130 // think in terms of edges, rather than blocks, and then split critical
1133 // TODO: OptimizeSequences could generalized to be Interprocedural.
1135 // TODO: Recognize that a bunch of other objc runtime calls have
1136 // non-escaping arguments and non-releasing arguments, and may be
1137 // non-autoreleasing.
1139 // TODO: Sink autorelease calls as far as possible. Unfortunately we
1140 // usually can't sink them past other calls, which would be the main
1141 // case where it would be useful.
1143 // TODO: The pointer returned from objc_loadWeakRetained is retained.
1145 // TODO: Delete release+retain pairs (rare).
1147 #include "llvm/ADT/SmallPtrSet.h"
1148 #include "llvm/ADT/Statistic.h"
1149 #include "llvm/IR/LLVMContext.h"
1150 #include "llvm/Support/CFG.h"
1152 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1153 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1154 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1155 STATISTIC(NumRets, "Number of return value forwarding "
1156 "retain+autoreleaes eliminated");
1157 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1158 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1161 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1162 /// uses many of the same techniques, except it uses special ObjC-specific
1163 /// reasoning about pointer relationships.
1164 class ProvenanceAnalysis {
1167 typedef std::pair<const Value *, const Value *> ValuePairTy;
1168 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1169 CachedResultsTy CachedResults;
1171 bool relatedCheck(const Value *A, const Value *B);
1172 bool relatedSelect(const SelectInst *A, const Value *B);
1173 bool relatedPHI(const PHINode *A, const Value *B);
1175 void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1176 ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1179 ProvenanceAnalysis() {}
1181 void setAA(AliasAnalysis *aa) { AA = aa; }
1183 AliasAnalysis *getAA() const { return AA; }
1185 bool related(const Value *A, const Value *B);
1188 CachedResults.clear();
1193 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1194 // If the values are Selects with the same condition, we can do a more precise
1195 // check: just check for relations between the values on corresponding arms.
1196 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
1197 if (A->getCondition() == SB->getCondition())
1198 return related(A->getTrueValue(), SB->getTrueValue()) ||
1199 related(A->getFalseValue(), SB->getFalseValue());
1201 // Check both arms of the Select node individually.
1202 return related(A->getTrueValue(), B) ||
1203 related(A->getFalseValue(), B);
1206 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1207 // If the values are PHIs in the same block, we can do a more precise as well
1208 // as efficient check: just check for relations between the values on
1209 // corresponding edges.
1210 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1211 if (PNB->getParent() == A->getParent()) {
1212 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1213 if (related(A->getIncomingValue(i),
1214 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1219 // Check each unique source of the PHI node against B.
1220 SmallPtrSet<const Value *, 4> UniqueSrc;
1221 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1222 const Value *PV1 = A->getIncomingValue(i);
1223 if (UniqueSrc.insert(PV1) && related(PV1, B))
1227 // All of the arms checked out.
1231 /// isStoredObjCPointer - Test if the value of P, or any value covered by its
1232 /// provenance, is ever stored within the function (not counting callees).
1233 static bool isStoredObjCPointer(const Value *P) {
1234 SmallPtrSet<const Value *, 8> Visited;
1235 SmallVector<const Value *, 8> Worklist;
1236 Worklist.push_back(P);
1239 P = Worklist.pop_back_val();
1240 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1242 const User *Ur = *UI;
1243 if (isa<StoreInst>(Ur)) {
1244 if (UI.getOperandNo() == 0)
1245 // The pointer is stored.
1247 // The pointed is stored through.
1250 if (isa<CallInst>(Ur))
1251 // The pointer is passed as an argument, ignore this.
1253 if (isa<PtrToIntInst>(P))
1254 // Assume the worst.
1256 if (Visited.insert(Ur))
1257 Worklist.push_back(Ur);
1259 } while (!Worklist.empty());
1261 // Everything checked out.
1265 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1266 // Skip past provenance pass-throughs.
1267 A = GetUnderlyingObjCPtr(A);
1268 B = GetUnderlyingObjCPtr(B);
1274 // Ask regular AliasAnalysis, for a first approximation.
1275 switch (AA->alias(A, B)) {
1276 case AliasAnalysis::NoAlias:
1278 case AliasAnalysis::MustAlias:
1279 case AliasAnalysis::PartialAlias:
1281 case AliasAnalysis::MayAlias:
1285 bool AIsIdentified = IsObjCIdentifiedObject(A);
1286 bool BIsIdentified = IsObjCIdentifiedObject(B);
1288 // An ObjC-Identified object can't alias a load if it is never locally stored.
1289 if (AIsIdentified) {
1290 // Check for an obvious escape.
1291 if (isa<LoadInst>(B))
1292 return isStoredObjCPointer(A);
1293 if (BIsIdentified) {
1294 // Check for an obvious escape.
1295 if (isa<LoadInst>(A))
1296 return isStoredObjCPointer(B);
1297 // Both pointers are identified and escapes aren't an evident problem.
1300 } else if (BIsIdentified) {
1301 // Check for an obvious escape.
1302 if (isa<LoadInst>(A))
1303 return isStoredObjCPointer(B);
1306 // Special handling for PHI and Select.
1307 if (const PHINode *PN = dyn_cast<PHINode>(A))
1308 return relatedPHI(PN, B);
1309 if (const PHINode *PN = dyn_cast<PHINode>(B))
1310 return relatedPHI(PN, A);
1311 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1312 return relatedSelect(S, B);
1313 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1314 return relatedSelect(S, A);
1320 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1321 // Begin by inserting a conservative value into the map. If the insertion
1322 // fails, we have the answer already. If it succeeds, leave it there until we
1323 // compute the real answer to guard against recursive queries.
1324 if (A > B) std::swap(A, B);
1325 std::pair<CachedResultsTy::iterator, bool> Pair =
1326 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1328 return Pair.first->second;
1330 bool Result = relatedCheck(A, B);
1331 CachedResults[ValuePairTy(A, B)] = Result;
1336 // Sequence - A sequence of states that a pointer may go through in which an
1337 // objc_retain and objc_release are actually needed.
1340 S_Retain, ///< objc_retain(x)
1341 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1342 S_Use, ///< any use of x
1343 S_Stop, ///< like S_Release, but code motion is stopped
1344 S_Release, ///< objc_release(x)
1345 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1349 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1353 if (A == S_None || B == S_None)
1356 if (A > B) std::swap(A, B);
1358 // Choose the side which is further along in the sequence.
1359 if ((A == S_Retain || A == S_CanRelease) &&
1360 (B == S_CanRelease || B == S_Use))
1363 // Choose the side which is further along in the sequence.
1364 if ((A == S_Use || A == S_CanRelease) &&
1365 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
1367 // If both sides are releases, choose the more conservative one.
1368 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1370 if (A == S_Release && B == S_MovableRelease)
1378 /// RRInfo - Unidirectional information about either a
1379 /// retain-decrement-use-release sequence or release-use-decrement-retain
1380 /// reverese sequence.
1382 /// KnownSafe - After an objc_retain, the reference count of the referenced
1383 /// object is known to be positive. Similarly, before an objc_release, the
1384 /// reference count of the referenced object is known to be positive. If
1385 /// there are retain-release pairs in code regions where the retain count
1386 /// is known to be positive, they can be eliminated, regardless of any side
1387 /// effects between them.
1389 /// Also, a retain+release pair nested within another retain+release
1390 /// pair all on the known same pointer value can be eliminated, regardless
1391 /// of any intervening side effects.
1393 /// KnownSafe is true when either of these conditions is satisfied.
1396 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1397 /// opposed to objc_retain calls).
1400 /// IsTailCallRelease - True of the objc_release calls are all marked
1401 /// with the "tail" keyword.
1402 bool IsTailCallRelease;
1404 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1405 /// a clang.imprecise_release tag, this is the metadata tag.
1406 MDNode *ReleaseMetadata;
1408 /// Calls - For a top-down sequence, the set of objc_retains or
1409 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1410 SmallPtrSet<Instruction *, 2> Calls;
1412 /// ReverseInsertPts - The set of optimal insert positions for
1413 /// moving calls in the opposite sequence.
1414 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1417 KnownSafe(false), IsRetainBlock(false),
1418 IsTailCallRelease(false),
1419 ReleaseMetadata(0) {}
1425 void RRInfo::clear() {
1427 IsRetainBlock = false;
1428 IsTailCallRelease = false;
1429 ReleaseMetadata = 0;
1431 ReverseInsertPts.clear();
1435 /// PtrState - This class summarizes several per-pointer runtime properties
1436 /// which are propogated through the flow graph.
1438 /// KnownPositiveRefCount - True if the reference count is known to
1440 bool KnownPositiveRefCount;
1442 /// Partial - True of we've seen an opportunity for partial RR elimination,
1443 /// such as pushing calls into a CFG triangle or into one side of a
1447 /// Seq - The current position in the sequence.
1451 /// RRI - Unidirectional information about the current sequence.
1452 /// TODO: Encapsulate this better.
1455 PtrState() : KnownPositiveRefCount(false), Partial(false),
1458 void SetKnownPositiveRefCount() {
1459 KnownPositiveRefCount = true;
1462 void ClearRefCount() {
1463 KnownPositiveRefCount = false;
1466 bool IsKnownIncremented() const {
1467 return KnownPositiveRefCount;
1470 void SetSeq(Sequence NewSeq) {
1474 Sequence GetSeq() const {
1478 void ClearSequenceProgress() {
1479 ResetSequenceProgress(S_None);
1482 void ResetSequenceProgress(Sequence NewSeq) {
1488 void Merge(const PtrState &Other, bool TopDown);
1493 PtrState::Merge(const PtrState &Other, bool TopDown) {
1494 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1495 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
1497 // We can't merge a plain objc_retain with an objc_retainBlock.
1498 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1501 // If we're not in a sequence (anymore), drop all associated state.
1502 if (Seq == S_None) {
1505 } else if (Partial || Other.Partial) {
1506 // If we're doing a merge on a path that's previously seen a partial
1507 // merge, conservatively drop the sequence, to avoid doing partial
1508 // RR elimination. If the branch predicates for the two merge differ,
1509 // mixing them is unsafe.
1510 ClearSequenceProgress();
1512 // Conservatively merge the ReleaseMetadata information.
1513 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1514 RRI.ReleaseMetadata = 0;
1516 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
1517 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1518 Other.RRI.IsTailCallRelease;
1519 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1521 // Merge the insert point sets. If there are any differences,
1522 // that makes this a partial merge.
1523 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
1524 for (SmallPtrSet<Instruction *, 2>::const_iterator
1525 I = Other.RRI.ReverseInsertPts.begin(),
1526 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1527 Partial |= RRI.ReverseInsertPts.insert(*I);
1532 /// BBState - Per-BasicBlock state.
1534 /// TopDownPathCount - The number of unique control paths from the entry
1535 /// which can reach this block.
1536 unsigned TopDownPathCount;
1538 /// BottomUpPathCount - The number of unique control paths to exits
1539 /// from this block.
1540 unsigned BottomUpPathCount;
1542 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1543 typedef MapVector<const Value *, PtrState> MapTy;
1545 /// PerPtrTopDown - The top-down traversal uses this to record information
1546 /// known about a pointer at the bottom of each block.
1547 MapTy PerPtrTopDown;
1549 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1550 /// known about a pointer at the top of each block.
1551 MapTy PerPtrBottomUp;
1553 /// Preds, Succs - Effective successors and predecessors of the current
1554 /// block (this ignores ignorable edges and ignored backedges).
1555 SmallVector<BasicBlock *, 2> Preds;
1556 SmallVector<BasicBlock *, 2> Succs;
1559 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1561 typedef MapTy::iterator ptr_iterator;
1562 typedef MapTy::const_iterator ptr_const_iterator;
1564 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1565 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1566 ptr_const_iterator top_down_ptr_begin() const {
1567 return PerPtrTopDown.begin();
1569 ptr_const_iterator top_down_ptr_end() const {
1570 return PerPtrTopDown.end();
1573 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1574 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1575 ptr_const_iterator bottom_up_ptr_begin() const {
1576 return PerPtrBottomUp.begin();
1578 ptr_const_iterator bottom_up_ptr_end() const {
1579 return PerPtrBottomUp.end();
1582 /// SetAsEntry - Mark this block as being an entry block, which has one
1583 /// path from the entry by definition.
1584 void SetAsEntry() { TopDownPathCount = 1; }
1586 /// SetAsExit - Mark this block as being an exit block, which has one
1587 /// path to an exit by definition.
1588 void SetAsExit() { BottomUpPathCount = 1; }
1590 PtrState &getPtrTopDownState(const Value *Arg) {
1591 return PerPtrTopDown[Arg];
1594 PtrState &getPtrBottomUpState(const Value *Arg) {
1595 return PerPtrBottomUp[Arg];
1598 void clearBottomUpPointers() {
1599 PerPtrBottomUp.clear();
1602 void clearTopDownPointers() {
1603 PerPtrTopDown.clear();
1606 void InitFromPred(const BBState &Other);
1607 void InitFromSucc(const BBState &Other);
1608 void MergePred(const BBState &Other);
1609 void MergeSucc(const BBState &Other);
1611 /// GetAllPathCount - Return the number of possible unique paths from an
1612 /// entry to an exit which pass through this block. This is only valid
1613 /// after both the top-down and bottom-up traversals are complete.
1614 unsigned GetAllPathCount() const {
1615 assert(TopDownPathCount != 0);
1616 assert(BottomUpPathCount != 0);
1617 return TopDownPathCount * BottomUpPathCount;
1620 // Specialized CFG utilities.
1621 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
1622 edge_iterator pred_begin() { return Preds.begin(); }
1623 edge_iterator pred_end() { return Preds.end(); }
1624 edge_iterator succ_begin() { return Succs.begin(); }
1625 edge_iterator succ_end() { return Succs.end(); }
1627 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1628 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1630 bool isExit() const { return Succs.empty(); }
1634 void BBState::InitFromPred(const BBState &Other) {
1635 PerPtrTopDown = Other.PerPtrTopDown;
1636 TopDownPathCount = Other.TopDownPathCount;
1639 void BBState::InitFromSucc(const BBState &Other) {
1640 PerPtrBottomUp = Other.PerPtrBottomUp;
1641 BottomUpPathCount = Other.BottomUpPathCount;
1644 /// MergePred - The top-down traversal uses this to merge information about
1645 /// predecessors to form the initial state for a new block.
1646 void BBState::MergePred(const BBState &Other) {
1647 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1648 // loop backedge. Loop backedges are special.
1649 TopDownPathCount += Other.TopDownPathCount;
1651 // Check for overflow. If we have overflow, fall back to conservative behavior.
1652 if (TopDownPathCount < Other.TopDownPathCount) {
1653 clearTopDownPointers();
1657 // For each entry in the other set, if our set has an entry with the same key,
1658 // merge the entries. Otherwise, copy the entry and merge it with an empty
1660 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1661 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1662 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1663 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1667 // For each entry in our set, if the other set doesn't have an entry with the
1668 // same key, force it to merge with an empty entry.
1669 for (ptr_iterator MI = top_down_ptr_begin(),
1670 ME = top_down_ptr_end(); MI != ME; ++MI)
1671 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1672 MI->second.Merge(PtrState(), /*TopDown=*/true);
1675 /// MergeSucc - The bottom-up traversal uses this to merge information about
1676 /// successors to form the initial state for a new block.
1677 void BBState::MergeSucc(const BBState &Other) {
1678 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1679 // loop backedge. Loop backedges are special.
1680 BottomUpPathCount += Other.BottomUpPathCount;
1682 // Check for overflow. If we have overflow, fall back to conservative behavior.
1683 if (BottomUpPathCount < Other.BottomUpPathCount) {
1684 clearBottomUpPointers();
1688 // For each entry in the other set, if our set has an entry with the
1689 // same key, merge the entries. Otherwise, copy the entry and merge
1690 // it with an empty entry.
1691 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1692 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1693 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1694 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1698 // For each entry in our set, if the other set doesn't have an entry
1699 // with the same key, force it to merge with an empty entry.
1700 for (ptr_iterator MI = bottom_up_ptr_begin(),
1701 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1702 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1703 MI->second.Merge(PtrState(), /*TopDown=*/false);
1707 /// ObjCARCOpt - The main ARC optimization pass.
1708 class ObjCARCOpt : public FunctionPass {
1710 ProvenanceAnalysis PA;
1712 /// Run - A flag indicating whether this optimization pass should run.
1715 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1716 /// functions, for use in creating calls to them. These are initialized
1717 /// lazily to avoid cluttering up the Module with unused declarations.
1718 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
1719 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
1721 /// UsedInThisFunciton - Flags which determine whether each of the
1722 /// interesting runtine functions is in fact used in the current function.
1723 unsigned UsedInThisFunction;
1725 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1727 unsigned ImpreciseReleaseMDKind;
1729 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
1731 unsigned CopyOnEscapeMDKind;
1733 /// NoObjCARCExceptionsMDKind - The Metadata Kind for
1734 /// clang.arc.no_objc_arc_exceptions metadata.
1735 unsigned NoObjCARCExceptionsMDKind;
1737 Constant *getRetainRVCallee(Module *M);
1738 Constant *getAutoreleaseRVCallee(Module *M);
1739 Constant *getReleaseCallee(Module *M);
1740 Constant *getRetainCallee(Module *M);
1741 Constant *getRetainBlockCallee(Module *M);
1742 Constant *getAutoreleaseCallee(Module *M);
1744 bool IsRetainBlockOptimizable(const Instruction *Inst);
1746 void OptimizeRetainCall(Function &F, Instruction *Retain);
1747 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1748 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
1749 InstructionClass &Class);
1750 void OptimizeIndividualCalls(Function &F);
1752 void CheckForCFGHazards(const BasicBlock *BB,
1753 DenseMap<const BasicBlock *, BBState> &BBStates,
1754 BBState &MyStates) const;
1755 bool VisitInstructionBottomUp(Instruction *Inst,
1757 MapVector<Value *, RRInfo> &Retains,
1759 bool VisitBottomUp(BasicBlock *BB,
1760 DenseMap<const BasicBlock *, BBState> &BBStates,
1761 MapVector<Value *, RRInfo> &Retains);
1762 bool VisitInstructionTopDown(Instruction *Inst,
1763 DenseMap<Value *, RRInfo> &Releases,
1765 bool VisitTopDown(BasicBlock *BB,
1766 DenseMap<const BasicBlock *, BBState> &BBStates,
1767 DenseMap<Value *, RRInfo> &Releases);
1768 bool Visit(Function &F,
1769 DenseMap<const BasicBlock *, BBState> &BBStates,
1770 MapVector<Value *, RRInfo> &Retains,
1771 DenseMap<Value *, RRInfo> &Releases);
1773 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1774 MapVector<Value *, RRInfo> &Retains,
1775 DenseMap<Value *, RRInfo> &Releases,
1776 SmallVectorImpl<Instruction *> &DeadInsts,
1779 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1780 MapVector<Value *, RRInfo> &Retains,
1781 DenseMap<Value *, RRInfo> &Releases,
1784 void OptimizeWeakCalls(Function &F);
1786 bool OptimizeSequences(Function &F);
1788 void OptimizeReturns(Function &F);
1790 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1791 virtual bool doInitialization(Module &M);
1792 virtual bool runOnFunction(Function &F);
1793 virtual void releaseMemory();
1797 ObjCARCOpt() : FunctionPass(ID) {
1798 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1803 char ObjCARCOpt::ID = 0;
1804 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1805 "objc-arc", "ObjC ARC optimization", false, false)
1806 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1807 INITIALIZE_PASS_END(ObjCARCOpt,
1808 "objc-arc", "ObjC ARC optimization", false, false)
1810 Pass *llvm::createObjCARCOptPass() {
1811 return new ObjCARCOpt();
1814 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1815 AU.addRequired<ObjCARCAliasAnalysis>();
1816 AU.addRequired<AliasAnalysis>();
1817 // ARC optimization doesn't currently split critical edges.
1818 AU.setPreservesCFG();
1821 bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1822 // Without the magic metadata tag, we have to assume this might be an
1823 // objc_retainBlock call inserted to convert a block pointer to an id,
1824 // in which case it really is needed.
1825 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1828 // If the pointer "escapes" (not including being used in a call),
1829 // the copy may be needed.
1830 if (DoesObjCBlockEscape(Inst))
1833 // Otherwise, it's not needed.
1837 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1838 if (!RetainRVCallee) {
1839 LLVMContext &C = M->getContext();
1840 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1841 Type *Params[] = { I8X };
1842 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1843 AttributeSet Attribute =
1844 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1845 Attribute::get(C, Attribute::NoUnwind));
1847 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1850 return RetainRVCallee;
1853 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1854 if (!AutoreleaseRVCallee) {
1855 LLVMContext &C = M->getContext();
1856 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1857 Type *Params[] = { I8X };
1858 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
1859 AttributeSet Attribute =
1860 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1861 Attribute::get(C, Attribute::NoUnwind));
1862 AutoreleaseRVCallee =
1863 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1866 return AutoreleaseRVCallee;
1869 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1870 if (!ReleaseCallee) {
1871 LLVMContext &C = M->getContext();
1872 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1873 AttributeSet Attribute =
1874 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1875 Attribute::get(C, Attribute::NoUnwind));
1877 M->getOrInsertFunction(
1879 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1882 return ReleaseCallee;
1885 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1886 if (!RetainCallee) {
1887 LLVMContext &C = M->getContext();
1888 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1889 AttributeSet Attribute =
1890 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1891 Attribute::get(C, Attribute::NoUnwind));
1893 M->getOrInsertFunction(
1895 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1898 return RetainCallee;
1901 Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1902 if (!RetainBlockCallee) {
1903 LLVMContext &C = M->getContext();
1904 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1905 // objc_retainBlock is not nounwind because it calls user copy constructors
1906 // which could theoretically throw.
1908 M->getOrInsertFunction(
1910 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1913 return RetainBlockCallee;
1916 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1917 if (!AutoreleaseCallee) {
1918 LLVMContext &C = M->getContext();
1919 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
1920 AttributeSet Attribute =
1921 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
1922 Attribute::get(C, Attribute::NoUnwind));
1924 M->getOrInsertFunction(
1926 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1929 return AutoreleaseCallee;
1932 /// IsPotentialUse - Test whether the given value is possible a
1933 /// reference-counted pointer, including tests which utilize AliasAnalysis.
1934 static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
1935 // First make the rudimentary check.
1936 if (!IsPotentialUse(Op))
1939 // Objects in constant memory are not reference-counted.
1940 if (AA.pointsToConstantMemory(Op))
1943 // Pointers in constant memory are not pointing to reference-counted objects.
1944 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1945 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1948 // Otherwise assume the worst.
1952 /// CanAlterRefCount - Test whether the given instruction can result in a
1953 /// reference count modification (positive or negative) for the pointer's
1956 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1957 ProvenanceAnalysis &PA, InstructionClass Class) {
1959 case IC_Autorelease:
1960 case IC_AutoreleaseRV:
1962 // These operations never directly modify a reference count.
1967 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1968 assert(CS && "Only calls can alter reference counts!");
1970 // See if AliasAnalysis can help us with the call.
1971 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1972 if (AliasAnalysis::onlyReadsMemory(MRB))
1974 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1975 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1977 const Value *Op = *I;
1978 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
1984 // Assume the worst.
1988 /// CanUse - Test whether the given instruction can "use" the given pointer's
1989 /// object in a way that requires the reference count to be positive.
1991 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1992 InstructionClass Class) {
1993 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1994 if (Class == IC_Call)
1997 // Consider various instructions which may have pointer arguments which are
1999 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
2000 // Comparing a pointer with null, or any other constant, isn't really a use,
2001 // because we don't care what the pointer points to, or about the values
2002 // of any other dynamic reference-counted pointers.
2003 if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
2005 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
2006 // For calls, just check the arguments (and not the callee operand).
2007 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
2008 OE = CS.arg_end(); OI != OE; ++OI) {
2009 const Value *Op = *OI;
2010 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
2014 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
2015 // Special-case stores, because we don't care about the stored value, just
2016 // the store address.
2017 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
2018 // If we can't tell what the underlying object was, assume there is a
2020 return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
2023 // Check each operand for a match.
2024 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
2026 const Value *Op = *OI;
2027 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
2033 /// CanInterruptRV - Test whether the given instruction can autorelease
2034 /// any pointer or cause an autoreleasepool pop.
2036 CanInterruptRV(InstructionClass Class) {
2038 case IC_AutoreleasepoolPop:
2041 case IC_Autorelease:
2042 case IC_AutoreleaseRV:
2043 case IC_FusedRetainAutorelease:
2044 case IC_FusedRetainAutoreleaseRV:
2052 /// DependenceKind - There are several kinds of dependence-like concepts in
2054 enum DependenceKind {
2055 NeedsPositiveRetainCount,
2056 AutoreleasePoolBoundary,
2057 CanChangeRetainCount,
2058 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
2059 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
2060 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
2064 /// Depends - Test if there can be dependencies on Inst through Arg. This
2065 /// function only tests dependencies relevant for removing pairs of calls.
2067 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2068 ProvenanceAnalysis &PA) {
2069 // If we've reached the definition of Arg, stop.
2074 case NeedsPositiveRetainCount: {
2075 InstructionClass Class = GetInstructionClass(Inst);
2077 case IC_AutoreleasepoolPop:
2078 case IC_AutoreleasepoolPush:
2082 return CanUse(Inst, Arg, PA, Class);
2086 case AutoreleasePoolBoundary: {
2087 InstructionClass Class = GetInstructionClass(Inst);
2089 case IC_AutoreleasepoolPop:
2090 case IC_AutoreleasepoolPush:
2091 // These mark the end and begin of an autorelease pool scope.
2094 // Nothing else does this.
2099 case CanChangeRetainCount: {
2100 InstructionClass Class = GetInstructionClass(Inst);
2102 case IC_AutoreleasepoolPop:
2103 // Conservatively assume this can decrement any count.
2105 case IC_AutoreleasepoolPush:
2109 return CanAlterRefCount(Inst, Arg, PA, Class);
2113 case RetainAutoreleaseDep:
2114 switch (GetBasicInstructionClass(Inst)) {
2115 case IC_AutoreleasepoolPop:
2116 case IC_AutoreleasepoolPush:
2117 // Don't merge an objc_autorelease with an objc_retain inside a different
2118 // autoreleasepool scope.
2122 // Check for a retain of the same pointer for merging.
2123 return GetObjCArg(Inst) == Arg;
2125 // Nothing else matters for objc_retainAutorelease formation.
2129 case RetainAutoreleaseRVDep: {
2130 InstructionClass Class = GetBasicInstructionClass(Inst);
2134 // Check for a retain of the same pointer for merging.
2135 return GetObjCArg(Inst) == Arg;
2137 // Anything that can autorelease interrupts
2138 // retainAutoreleaseReturnValue formation.
2139 return CanInterruptRV(Class);
2144 return CanInterruptRV(GetBasicInstructionClass(Inst));
2147 llvm_unreachable("Invalid dependence flavor");
2150 /// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2151 /// find local and non-local dependencies on Arg.
2152 /// TODO: Cache results?
2154 FindDependencies(DependenceKind Flavor,
2156 BasicBlock *StartBB, Instruction *StartInst,
2157 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2158 SmallPtrSet<const BasicBlock *, 4> &Visited,
2159 ProvenanceAnalysis &PA) {
2160 BasicBlock::iterator StartPos = StartInst;
2162 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2163 Worklist.push_back(std::make_pair(StartBB, StartPos));
2165 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2166 Worklist.pop_back_val();
2167 BasicBlock *LocalStartBB = Pair.first;
2168 BasicBlock::iterator LocalStartPos = Pair.second;
2169 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2171 if (LocalStartPos == StartBBBegin) {
2172 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2174 // If we've reached the function entry, produce a null dependence.
2175 DependingInstructions.insert(0);
2177 // Add the predecessors to the worklist.
2179 BasicBlock *PredBB = *PI;
2180 if (Visited.insert(PredBB))
2181 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2182 } while (++PI != PE);
2186 Instruction *Inst = --LocalStartPos;
2187 if (Depends(Flavor, Inst, Arg, PA)) {
2188 DependingInstructions.insert(Inst);
2192 } while (!Worklist.empty());
2194 // Determine whether the original StartBB post-dominates all of the blocks we
2195 // visited. If not, insert a sentinal indicating that most optimizations are
2197 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2198 E = Visited.end(); I != E; ++I) {
2199 const BasicBlock *BB = *I;
2202 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2203 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2204 const BasicBlock *Succ = *SI;
2205 if (Succ != StartBB && !Visited.count(Succ)) {
2206 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2213 static bool isNullOrUndef(const Value *V) {
2214 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2217 static bool isNoopInstruction(const Instruction *I) {
2218 return isa<BitCastInst>(I) ||
2219 (isa<GetElementPtrInst>(I) &&
2220 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2223 /// OptimizeRetainCall - Turn objc_retain into
2224 /// objc_retainAutoreleasedReturnValue if the operand is a return value.
2226 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
2227 ImmutableCallSite CS(GetObjCArg(Retain));
2228 const Instruction *Call = CS.getInstruction();
2230 if (Call->getParent() != Retain->getParent()) return;
2232 // Check that the call is next to the retain.
2233 BasicBlock::const_iterator I = Call;
2235 while (isNoopInstruction(I)) ++I;
2239 // Turn it to an objc_retainAutoreleasedReturnValue..
2243 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainCall: Transforming "
2244 "objc_retain => objc_retainAutoreleasedReturnValue"
2245 " since the operand is a return value.\n"
2247 << *Retain << "\n");
2249 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2251 DEBUG(dbgs() << " New: "
2252 << *Retain << "\n");
2255 /// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
2256 /// objc_retain if the operand is not a return value. Or, if it can be paired
2257 /// with an objc_autoreleaseReturnValue, delete the pair and return true.
2259 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
2260 // Check for the argument being from an immediately preceding call or invoke.
2261 const Value *Arg = GetObjCArg(RetainRV);
2262 ImmutableCallSite CS(Arg);
2263 if (const Instruction *Call = CS.getInstruction()) {
2264 if (Call->getParent() == RetainRV->getParent()) {
2265 BasicBlock::const_iterator I = Call;
2267 while (isNoopInstruction(I)) ++I;
2268 if (&*I == RetainRV)
2270 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
2271 BasicBlock *RetainRVParent = RetainRV->getParent();
2272 if (II->getNormalDest() == RetainRVParent) {
2273 BasicBlock::const_iterator I = RetainRVParent->begin();
2274 while (isNoopInstruction(I)) ++I;
2275 if (&*I == RetainRV)
2281 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2282 // pointer. In this case, we can delete the pair.
2283 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2285 do --I; while (I != Begin && isNoopInstruction(I));
2286 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2287 GetObjCArg(I) == Arg) {
2291 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Erasing " << *I << "\n"
2292 << " Erasing " << *RetainRV
2295 EraseInstruction(I);
2296 EraseInstruction(RetainRV);
2301 // Turn it to a plain objc_retain.
2305 DEBUG(dbgs() << "ObjCARCOpt::OptimizeRetainRVCall: Transforming "
2306 "objc_retainAutoreleasedReturnValue => "
2307 "objc_retain since the operand is not a return value.\n"
2309 << *RetainRV << "\n");
2311 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2313 DEBUG(dbgs() << " New: "
2314 << *RetainRV << "\n");
2319 /// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2320 /// objc_autorelease if the result is not used as a return value.
2322 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV,
2323 InstructionClass &Class) {
2324 // Check for a return of the pointer value.
2325 const Value *Ptr = GetObjCArg(AutoreleaseRV);
2326 SmallVector<const Value *, 2> Users;
2327 Users.push_back(Ptr);
2329 Ptr = Users.pop_back_val();
2330 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2332 const User *I = *UI;
2333 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2335 if (isa<BitCastInst>(I))
2338 } while (!Users.empty());
2343 DEBUG(dbgs() << "ObjCARCOpt::OptimizeAutoreleaseRVCall: Transforming "
2344 "objc_autoreleaseReturnValue => "
2345 "objc_autorelease since its operand is not used as a return "
2348 << *AutoreleaseRV << "\n");
2350 CallInst *AutoreleaseRVCI = cast<CallInst>(AutoreleaseRV);
2352 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2353 AutoreleaseRVCI->setTailCall(false); // Never tail call objc_autorelease.
2354 Class = IC_Autorelease;
2356 DEBUG(dbgs() << " New: "
2357 << *AutoreleaseRV << "\n");
2361 /// OptimizeIndividualCalls - Visit each call, one at a time, and make
2362 /// simplifications without doing any additional analysis.
2363 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2364 // Reset all the flags in preparation for recomputing them.
2365 UsedInThisFunction = 0;
2367 // Visit all objc_* calls in F.
2368 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2369 Instruction *Inst = &*I++;
2371 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Visiting: " <<
2374 InstructionClass Class = GetBasicInstructionClass(Inst);
2379 // Delete no-op casts. These function calls have special semantics, but
2380 // the semantics are entirely implemented via lowering in the front-end,
2381 // so by the time they reach the optimizer, they are just no-op calls
2382 // which return their argument.
2384 // There are gray areas here, as the ability to cast reference-counted
2385 // pointers to raw void* and back allows code to break ARC assumptions,
2386 // however these are currently considered to be unimportant.
2390 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Erasing no-op cast:"
2391 " " << *Inst << "\n");
2392 EraseInstruction(Inst);
2395 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2398 case IC_LoadWeakRetained:
2400 case IC_DestroyWeak: {
2401 CallInst *CI = cast<CallInst>(Inst);
2402 if (isNullOrUndef(CI->getArgOperand(0))) {
2404 Type *Ty = CI->getArgOperand(0)->getType();
2405 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2406 Constant::getNullValue(Ty),
2408 llvm::Value *NewValue = UndefValue::get(CI->getType());
2409 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2410 "pointer-to-weak-pointer is undefined behavior.\n"
2414 CI->replaceAllUsesWith(NewValue);
2415 CI->eraseFromParent();
2422 CallInst *CI = cast<CallInst>(Inst);
2423 if (isNullOrUndef(CI->getArgOperand(0)) ||
2424 isNullOrUndef(CI->getArgOperand(1))) {
2426 Type *Ty = CI->getArgOperand(0)->getType();
2427 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2428 Constant::getNullValue(Ty),
2431 llvm::Value *NewValue = UndefValue::get(CI->getType());
2432 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: A null "
2433 "pointer-to-weak-pointer is undefined behavior.\n"
2438 CI->replaceAllUsesWith(NewValue);
2439 CI->eraseFromParent();
2445 OptimizeRetainCall(F, Inst);
2448 if (OptimizeRetainRVCall(F, Inst))
2451 case IC_AutoreleaseRV:
2452 OptimizeAutoreleaseRVCall(F, Inst, Class);
2456 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2457 if (IsAutorelease(Class) && Inst->use_empty()) {
2458 CallInst *Call = cast<CallInst>(Inst);
2459 const Value *Arg = Call->getArgOperand(0);
2460 Arg = FindSingleUseIdentifiedObject(Arg);
2465 // Create the declaration lazily.
2466 LLVMContext &C = Inst->getContext();
2468 CallInst::Create(getReleaseCallee(F.getParent()),
2469 Call->getArgOperand(0), "", Call);
2470 NewCall->setMetadata(ImpreciseReleaseMDKind,
2471 MDNode::get(C, ArrayRef<Value *>()));
2473 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Replacing "
2474 "objc_autorelease(x) with objc_release(x) since x is "
2475 "otherwise unused.\n"
2476 " Old: " << *Call <<
2480 EraseInstruction(Call);
2486 // For functions which can never be passed stack arguments, add
2488 if (IsAlwaysTail(Class)) {
2490 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Adding tail keyword"
2491 " to function since it can never be passed stack args: " << *Inst <<
2493 cast<CallInst>(Inst)->setTailCall();
2496 // Ensure that functions that can never have a "tail" keyword due to the
2497 // semantics of ARC truly do not do so.
2498 if (IsNeverTail(Class)) {
2500 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Removing tail keyword"
2501 " from function: " << *Inst <<
2503 cast<CallInst>(Inst)->setTailCall(false);
2506 // Set nounwind as needed.
2507 if (IsNoThrow(Class)) {
2509 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Found no throw"
2510 " class. Setting nounwind on: " << *Inst << "\n");
2511 cast<CallInst>(Inst)->setDoesNotThrow();
2514 if (!IsNoopOnNull(Class)) {
2515 UsedInThisFunction |= 1 << Class;
2519 const Value *Arg = GetObjCArg(Inst);
2521 // ARC calls with null are no-ops. Delete them.
2522 if (isNullOrUndef(Arg)) {
2525 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: ARC calls with "
2526 " null are no-ops. Erasing: " << *Inst << "\n");
2527 EraseInstruction(Inst);
2531 // Keep track of which of retain, release, autorelease, and retain_block
2532 // are actually present in this function.
2533 UsedInThisFunction |= 1 << Class;
2535 // If Arg is a PHI, and one or more incoming values to the
2536 // PHI are null, and the call is control-equivalent to the PHI, and there
2537 // are no relevant side effects between the PHI and the call, the call
2538 // could be pushed up to just those paths with non-null incoming values.
2539 // For now, don't bother splitting critical edges for this.
2540 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2541 Worklist.push_back(std::make_pair(Inst, Arg));
2543 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2547 const PHINode *PN = dyn_cast<PHINode>(Arg);
2550 // Determine if the PHI has any null operands, or any incoming
2552 bool HasNull = false;
2553 bool HasCriticalEdges = false;
2554 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2556 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2557 if (isNullOrUndef(Incoming))
2559 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2560 .getNumSuccessors() != 1) {
2561 HasCriticalEdges = true;
2565 // If we have null operands and no critical edges, optimize.
2566 if (!HasCriticalEdges && HasNull) {
2567 SmallPtrSet<Instruction *, 4> DependingInstructions;
2568 SmallPtrSet<const BasicBlock *, 4> Visited;
2570 // Check that there is nothing that cares about the reference
2571 // count between the call and the phi.
2574 case IC_RetainBlock:
2575 // These can always be moved up.
2578 // These can't be moved across things that care about the retain
2580 FindDependencies(NeedsPositiveRetainCount, Arg,
2581 Inst->getParent(), Inst,
2582 DependingInstructions, Visited, PA);
2584 case IC_Autorelease:
2585 // These can't be moved across autorelease pool scope boundaries.
2586 FindDependencies(AutoreleasePoolBoundary, Arg,
2587 Inst->getParent(), Inst,
2588 DependingInstructions, Visited, PA);
2591 case IC_AutoreleaseRV:
2592 // Don't move these; the RV optimization depends on the autoreleaseRV
2593 // being tail called, and the retainRV being immediately after a call
2594 // (which might still happen if we get lucky with codegen layout, but
2595 // it's not worth taking the chance).
2598 llvm_unreachable("Invalid dependence flavor");
2601 if (DependingInstructions.size() == 1 &&
2602 *DependingInstructions.begin() == PN) {
2605 // Clone the call into each predecessor that has a non-null value.
2606 CallInst *CInst = cast<CallInst>(Inst);
2607 Type *ParamTy = CInst->getArgOperand(0)->getType();
2608 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2610 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2611 if (!isNullOrUndef(Incoming)) {
2612 CallInst *Clone = cast<CallInst>(CInst->clone());
2613 Value *Op = PN->getIncomingValue(i);
2614 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2615 if (Op->getType() != ParamTy)
2616 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2617 Clone->setArgOperand(0, Op);
2618 Clone->insertBefore(InsertPos);
2620 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Cloning "
2623 "clone at " << *InsertPos << "\n");
2624 Worklist.push_back(std::make_pair(Clone, Incoming));
2627 // Erase the original call.
2628 DEBUG(dbgs() << "Erasing: " << *CInst << "\n");
2629 EraseInstruction(CInst);
2633 } while (!Worklist.empty());
2635 DEBUG(dbgs() << "ObjCARCOpt::OptimizeIndividualCalls: Finished List.\n");
2638 /// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2639 /// control flow, or other CFG structures where moving code across the edge
2640 /// would result in it being executed more.
2642 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2643 DenseMap<const BasicBlock *, BBState> &BBStates,
2644 BBState &MyStates) const {
2645 // If any top-down local-use or possible-dec has a succ which is earlier in
2646 // the sequence, forget it.
2647 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
2648 E = MyStates.top_down_ptr_end(); I != E; ++I)
2649 switch (I->second.GetSeq()) {
2652 const Value *Arg = I->first;
2653 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2654 bool SomeSuccHasSame = false;
2655 bool AllSuccsHaveSame = true;
2656 PtrState &S = I->second;
2657 succ_const_iterator SI(TI), SE(TI, false);
2659 // If the terminator is an invoke marked with the
2660 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2661 // ignored, for ARC purposes.
2662 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
2663 DEBUG(dbgs() << "ObjCARCOpt::CheckForCFGHazards: Found an invoke "
2664 "terminator marked with "
2665 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
2670 for (; SI != SE; ++SI) {
2671 Sequence SuccSSeq = S_None;
2672 bool SuccSRRIKnownSafe = false;
2673 // If VisitBottomUp has pointer information for this successor, take
2674 // what we know about it.
2675 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2677 assert(BBI != BBStates.end());
2678 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2679 SuccSSeq = SuccS.GetSeq();
2680 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2683 case S_CanRelease: {
2684 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2685 S.ClearSequenceProgress();
2691 SomeSuccHasSame = true;
2695 case S_MovableRelease:
2696 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2697 AllSuccsHaveSame = false;
2700 llvm_unreachable("bottom-up pointer in retain state!");
2703 // If the state at the other end of any of the successor edges
2704 // matches the current state, require all edges to match. This
2705 // guards against loops in the middle of a sequence.
2706 if (SomeSuccHasSame && !AllSuccsHaveSame)
2707 S.ClearSequenceProgress();
2710 case S_CanRelease: {
2711 const Value *Arg = I->first;
2712 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2713 bool SomeSuccHasSame = false;
2714 bool AllSuccsHaveSame = true;
2715 PtrState &S = I->second;
2716 succ_const_iterator SI(TI), SE(TI, false);
2718 // If the terminator is an invoke marked with the
2719 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2720 // ignored, for ARC purposes.
2721 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
2722 DEBUG(dbgs() << "ObjCARCOpt::CheckForCFGHazards: Found an invoke "
2723 "terminator marked with "
2724 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
2729 for (; SI != SE; ++SI) {
2730 Sequence SuccSSeq = S_None;
2731 bool SuccSRRIKnownSafe = false;
2732 // If VisitBottomUp has pointer information for this successor, take
2733 // what we know about it.
2734 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2736 assert(BBI != BBStates.end());
2737 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2738 SuccSSeq = SuccS.GetSeq();
2739 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2742 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
2743 S.ClearSequenceProgress();
2749 SomeSuccHasSame = true;
2753 case S_MovableRelease:
2755 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
2756 AllSuccsHaveSame = false;
2759 llvm_unreachable("bottom-up pointer in retain state!");
2762 // If the state at the other end of any of the successor edges
2763 // matches the current state, require all edges to match. This
2764 // guards against loops in the middle of a sequence.
2765 if (SomeSuccHasSame && !AllSuccsHaveSame)
2766 S.ClearSequenceProgress();
2773 ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
2775 MapVector<Value *, RRInfo> &Retains,
2776 BBState &MyStates) {
2777 bool NestingDetected = false;
2778 InstructionClass Class = GetInstructionClass(Inst);
2779 const Value *Arg = 0;
2783 Arg = GetObjCArg(Inst);
2785 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2787 // If we see two releases in a row on the same pointer. If so, make
2788 // a note, and we'll cicle back to revisit it after we've
2789 // hopefully eliminated the second release, which may allow us to
2790 // eliminate the first release too.
2791 // Theoretically we could implement removal of nested retain+release
2792 // pairs by making PtrState hold a stack of states, but this is
2793 // simple and avoids adding overhead for the non-nested case.
2794 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease) {
2795 DEBUG(dbgs() << "ObjCARCOpt::VisitInstructionBottomUp: Found nested "
2796 "releases (i.e. a release pair)\n");
2797 NestingDetected = true;
2800 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2801 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
2802 S.RRI.ReleaseMetadata = ReleaseMetadata;
2803 S.RRI.KnownSafe = S.IsKnownIncremented();
2804 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2805 S.RRI.Calls.insert(Inst);
2807 S.SetKnownPositiveRefCount();
2810 case IC_RetainBlock:
2811 // An objc_retainBlock call with just a use may need to be kept,
2812 // because it may be copying a block from the stack to the heap.
2813 if (!IsRetainBlockOptimizable(Inst))
2818 Arg = GetObjCArg(Inst);
2820 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2821 S.SetKnownPositiveRefCount();
2823 switch (S.GetSeq()) {
2826 case S_MovableRelease:
2828 S.RRI.ReverseInsertPts.clear();
2831 // Don't do retain+release tracking for IC_RetainRV, because it's
2832 // better to let it remain as the first instruction after a call.
2833 if (Class != IC_RetainRV) {
2834 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2835 Retains[Inst] = S.RRI;
2837 S.ClearSequenceProgress();
2842 llvm_unreachable("bottom-up pointer in retain state!");
2844 return NestingDetected;
2846 case IC_AutoreleasepoolPop:
2847 // Conservatively, clear MyStates for all known pointers.
2848 MyStates.clearBottomUpPointers();
2849 return NestingDetected;
2850 case IC_AutoreleasepoolPush:
2852 // These are irrelevant.
2853 return NestingDetected;
2858 // Consider any other possible effects of this instruction on each
2859 // pointer being tracked.
2860 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2861 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2862 const Value *Ptr = MI->first;
2864 continue; // Handled above.
2865 PtrState &S = MI->second;
2866 Sequence Seq = S.GetSeq();
2868 // Check for possible releases.
2869 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2873 S.SetSeq(S_CanRelease);
2877 case S_MovableRelease:
2882 llvm_unreachable("bottom-up pointer in retain state!");
2886 // Check for possible direct uses.
2889 case S_MovableRelease:
2890 if (CanUse(Inst, Ptr, PA, Class)) {
2891 assert(S.RRI.ReverseInsertPts.empty());
2892 // If this is an invoke instruction, we're scanning it as part of
2893 // one of its successor blocks, since we can't insert code after it
2894 // in its own block, and we don't want to split critical edges.
2895 if (isa<InvokeInst>(Inst))
2896 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2898 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2900 } else if (Seq == S_Release &&
2901 (Class == IC_User || Class == IC_CallOrUser)) {
2902 // Non-movable releases depend on any possible objc pointer use.
2904 assert(S.RRI.ReverseInsertPts.empty());
2905 // As above; handle invoke specially.
2906 if (isa<InvokeInst>(Inst))
2907 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2909 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
2913 if (CanUse(Inst, Ptr, PA, Class))
2921 llvm_unreachable("bottom-up pointer in retain state!");
2925 return NestingDetected;
2929 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2930 DenseMap<const BasicBlock *, BBState> &BBStates,
2931 MapVector<Value *, RRInfo> &Retains) {
2932 bool NestingDetected = false;
2933 BBState &MyStates = BBStates[BB];
2935 // Merge the states from each successor to compute the initial state
2936 // for the current block.
2937 BBState::edge_iterator SI(MyStates.succ_begin()),
2938 SE(MyStates.succ_end());
2940 const BasicBlock *Succ = *SI;
2941 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2942 assert(I != BBStates.end());
2943 MyStates.InitFromSucc(I->second);
2945 for (; SI != SE; ++SI) {
2947 I = BBStates.find(Succ);
2948 assert(I != BBStates.end());
2949 MyStates.MergeSucc(I->second);
2953 // Visit all the instructions, bottom-up.
2954 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2955 Instruction *Inst = llvm::prior(I);
2957 // Invoke instructions are visited as part of their successors (below).
2958 if (isa<InvokeInst>(Inst))
2961 DEBUG(dbgs() << "ObjCARCOpt::VisitButtonUp: Visiting " << *Inst << "\n");
2963 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2966 // If there's a predecessor with an invoke, visit the invoke as if it were
2967 // part of this block, since we can't insert code after an invoke in its own
2968 // block, and we don't want to split critical edges.
2969 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2970 PE(MyStates.pred_end()); PI != PE; ++PI) {
2971 BasicBlock *Pred = *PI;
2972 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2973 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
2976 return NestingDetected;
2980 ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2981 DenseMap<Value *, RRInfo> &Releases,
2982 BBState &MyStates) {
2983 bool NestingDetected = false;
2984 InstructionClass Class = GetInstructionClass(Inst);
2985 const Value *Arg = 0;
2988 case IC_RetainBlock:
2989 // An objc_retainBlock call with just a use may need to be kept,
2990 // because it may be copying a block from the stack to the heap.
2991 if (!IsRetainBlockOptimizable(Inst))
2996 Arg = GetObjCArg(Inst);
2998 PtrState &S = MyStates.getPtrTopDownState(Arg);
3000 // Don't do retain+release tracking for IC_RetainRV, because it's
3001 // better to let it remain as the first instruction after a call.
3002 if (Class != IC_RetainRV) {
3003 // If we see two retains in a row on the same pointer. If so, make
3004 // a note, and we'll cicle back to revisit it after we've
3005 // hopefully eliminated the second retain, which may allow us to
3006 // eliminate the first retain too.
3007 // Theoretically we could implement removal of nested retain+release
3008 // pairs by making PtrState hold a stack of states, but this is
3009 // simple and avoids adding overhead for the non-nested case.
3010 if (S.GetSeq() == S_Retain)
3011 NestingDetected = true;
3013 S.ResetSequenceProgress(S_Retain);
3014 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
3015 S.RRI.KnownSafe = S.IsKnownIncremented();
3016 S.RRI.Calls.insert(Inst);
3019 S.SetKnownPositiveRefCount();
3021 // A retain can be a potential use; procede to the generic checking
3026 Arg = GetObjCArg(Inst);
3028 PtrState &S = MyStates.getPtrTopDownState(Arg);
3031 switch (S.GetSeq()) {
3034 S.RRI.ReverseInsertPts.clear();
3037 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
3038 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
3039 Releases[Inst] = S.RRI;
3040 S.ClearSequenceProgress();
3046 case S_MovableRelease:
3047 llvm_unreachable("top-down pointer in release state!");
3051 case IC_AutoreleasepoolPop:
3052 // Conservatively, clear MyStates for all known pointers.
3053 MyStates.clearTopDownPointers();
3054 return NestingDetected;
3055 case IC_AutoreleasepoolPush:
3057 // These are irrelevant.
3058 return NestingDetected;
3063 // Consider any other possible effects of this instruction on each
3064 // pointer being tracked.
3065 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
3066 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
3067 const Value *Ptr = MI->first;
3069 continue; // Handled above.
3070 PtrState &S = MI->second;
3071 Sequence Seq = S.GetSeq();
3073 // Check for possible releases.
3074 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
3078 S.SetSeq(S_CanRelease);
3079 assert(S.RRI.ReverseInsertPts.empty());
3080 S.RRI.ReverseInsertPts.insert(Inst);
3082 // One call can't cause a transition from S_Retain to S_CanRelease
3083 // and S_CanRelease to S_Use. If we've made the first transition,
3092 case S_MovableRelease:
3093 llvm_unreachable("top-down pointer in release state!");
3097 // Check for possible direct uses.
3100 if (CanUse(Inst, Ptr, PA, Class))
3109 case S_MovableRelease:
3110 llvm_unreachable("top-down pointer in release state!");
3114 return NestingDetected;
3118 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
3119 DenseMap<const BasicBlock *, BBState> &BBStates,
3120 DenseMap<Value *, RRInfo> &Releases) {
3121 bool NestingDetected = false;
3122 BBState &MyStates = BBStates[BB];
3124 // Merge the states from each predecessor to compute the initial state
3125 // for the current block.
3126 BBState::edge_iterator PI(MyStates.pred_begin()),
3127 PE(MyStates.pred_end());
3129 const BasicBlock *Pred = *PI;
3130 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
3131 assert(I != BBStates.end());
3132 MyStates.InitFromPred(I->second);
3134 for (; PI != PE; ++PI) {
3136 I = BBStates.find(Pred);
3137 assert(I != BBStates.end());
3138 MyStates.MergePred(I->second);
3142 // Visit all the instructions, top-down.
3143 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
3144 Instruction *Inst = I;
3146 DEBUG(dbgs() << "ObjCARCOpt::VisitTopDown: Visiting " << *Inst << "\n");
3148 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
3151 CheckForCFGHazards(BB, BBStates, MyStates);
3152 return NestingDetected;
3156 ComputePostOrders(Function &F,
3157 SmallVectorImpl<BasicBlock *> &PostOrder,
3158 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
3159 unsigned NoObjCARCExceptionsMDKind,
3160 DenseMap<const BasicBlock *, BBState> &BBStates) {
3161 /// Visited - The visited set, for doing DFS walks.
3162 SmallPtrSet<BasicBlock *, 16> Visited;
3164 // Do DFS, computing the PostOrder.
3165 SmallPtrSet<BasicBlock *, 16> OnStack;
3166 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
3168 // Functions always have exactly one entry block, and we don't have
3169 // any other block that we treat like an entry block.
3170 BasicBlock *EntryBB = &F.getEntryBlock();
3171 BBState &MyStates = BBStates[EntryBB];
3172 MyStates.SetAsEntry();
3173 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
3174 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
3175 Visited.insert(EntryBB);
3176 OnStack.insert(EntryBB);
3179 BasicBlock *CurrBB = SuccStack.back().first;
3180 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3181 succ_iterator SE(TI, false);
3183 // If the terminator is an invoke marked with the
3184 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
3185 // ignored, for ARC purposes.
3186 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind)) {
3187 DEBUG(dbgs() << "ObjCARCOpt::ComputePostOrders: Found an invoke "
3188 "terminator marked with "
3189 "clang.arc.no_objc_arc_exceptions. Ignoring unwind "
3194 while (SuccStack.back().second != SE) {
3195 BasicBlock *SuccBB = *SuccStack.back().second++;
3196 if (Visited.insert(SuccBB)) {
3197 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3198 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
3199 BBStates[CurrBB].addSucc(SuccBB);
3200 BBState &SuccStates = BBStates[SuccBB];
3201 SuccStates.addPred(CurrBB);
3202 OnStack.insert(SuccBB);
3206 if (!OnStack.count(SuccBB)) {
3207 BBStates[CurrBB].addSucc(SuccBB);
3208 BBStates[SuccBB].addPred(CurrBB);
3211 OnStack.erase(CurrBB);
3212 PostOrder.push_back(CurrBB);
3213 SuccStack.pop_back();
3214 } while (!SuccStack.empty());
3218 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
3219 // Functions may have many exits, and there also blocks which we treat
3220 // as exits due to ignored edges.
3221 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3222 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3223 BasicBlock *ExitBB = I;
3224 BBState &MyStates = BBStates[ExitBB];
3225 if (!MyStates.isExit())
3228 MyStates.SetAsExit();
3230 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
3231 Visited.insert(ExitBB);
3232 while (!PredStack.empty()) {
3233 reverse_dfs_next_succ:
3234 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3235 while (PredStack.back().second != PE) {
3236 BasicBlock *BB = *PredStack.back().second++;
3237 if (Visited.insert(BB)) {
3238 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
3239 goto reverse_dfs_next_succ;
3242 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3247 // Visit - Visit the function both top-down and bottom-up.
3249 ObjCARCOpt::Visit(Function &F,
3250 DenseMap<const BasicBlock *, BBState> &BBStates,
3251 MapVector<Value *, RRInfo> &Retains,
3252 DenseMap<Value *, RRInfo> &Releases) {
3254 // Use reverse-postorder traversals, because we magically know that loops
3255 // will be well behaved, i.e. they won't repeatedly call retain on a single
3256 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3257 // class here because we want the reverse-CFG postorder to consider each
3258 // function exit point, and we want to ignore selected cycle edges.
3259 SmallVector<BasicBlock *, 16> PostOrder;
3260 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
3261 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3262 NoObjCARCExceptionsMDKind,
3265 // Use reverse-postorder on the reverse CFG for bottom-up.
3266 bool BottomUpNestingDetected = false;
3267 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3268 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3270 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
3272 // Use reverse-postorder for top-down.
3273 bool TopDownNestingDetected = false;
3274 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3275 PostOrder.rbegin(), E = PostOrder.rend();
3277 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
3279 return TopDownNestingDetected && BottomUpNestingDetected;
3282 /// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
3283 void ObjCARCOpt::MoveCalls(Value *Arg,
3284 RRInfo &RetainsToMove,
3285 RRInfo &ReleasesToMove,
3286 MapVector<Value *, RRInfo> &Retains,
3287 DenseMap<Value *, RRInfo> &Releases,
3288 SmallVectorImpl<Instruction *> &DeadInsts,
3290 Type *ArgTy = Arg->getType();
3291 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
3293 // Insert the new retain and release calls.
3294 for (SmallPtrSet<Instruction *, 2>::const_iterator
3295 PI = ReleasesToMove.ReverseInsertPts.begin(),
3296 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3297 Instruction *InsertPt = *PI;
3298 Value *MyArg = ArgTy == ParamTy ? Arg :
3299 new BitCastInst(Arg, ParamTy, "", InsertPt);
3301 CallInst::Create(RetainsToMove.IsRetainBlock ?
3302 getRetainBlockCallee(M) : getRetainCallee(M),
3303 MyArg, "", InsertPt);
3304 Call->setDoesNotThrow();
3305 if (RetainsToMove.IsRetainBlock)
3306 Call->setMetadata(CopyOnEscapeMDKind,
3307 MDNode::get(M->getContext(), ArrayRef<Value *>()));
3309 Call->setTailCall();
3311 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Release: " << *Call
3313 " At insertion point: " << *InsertPt
3316 for (SmallPtrSet<Instruction *, 2>::const_iterator
3317 PI = RetainsToMove.ReverseInsertPts.begin(),
3318 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3319 Instruction *InsertPt = *PI;
3320 Value *MyArg = ArgTy == ParamTy ? Arg :
3321 new BitCastInst(Arg, ParamTy, "", InsertPt);
3322 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3324 // Attach a clang.imprecise_release metadata tag, if appropriate.
3325 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3326 Call->setMetadata(ImpreciseReleaseMDKind, M);
3327 Call->setDoesNotThrow();
3328 if (ReleasesToMove.IsTailCallRelease)
3329 Call->setTailCall();
3331 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Inserting new Retain: " << *Call
3333 " At insertion point: " << *InsertPt
3337 // Delete the original retain and release calls.
3338 for (SmallPtrSet<Instruction *, 2>::const_iterator
3339 AI = RetainsToMove.Calls.begin(),
3340 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3341 Instruction *OrigRetain = *AI;
3342 Retains.blot(OrigRetain);
3343 DeadInsts.push_back(OrigRetain);
3344 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting retain: " << *OrigRetain <<
3347 for (SmallPtrSet<Instruction *, 2>::const_iterator
3348 AI = ReleasesToMove.Calls.begin(),
3349 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3350 Instruction *OrigRelease = *AI;
3351 Releases.erase(OrigRelease);
3352 DeadInsts.push_back(OrigRelease);
3353 DEBUG(dbgs() << "ObjCARCOpt::MoveCalls: Deleting release: " << *OrigRelease
3358 /// PerformCodePlacement - Identify pairings between the retains and releases,
3359 /// and delete and/or move them.
3361 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3363 MapVector<Value *, RRInfo> &Retains,
3364 DenseMap<Value *, RRInfo> &Releases,
3366 bool AnyPairsCompletelyEliminated = false;
3367 RRInfo RetainsToMove;
3368 RRInfo ReleasesToMove;
3369 SmallVector<Instruction *, 4> NewRetains;
3370 SmallVector<Instruction *, 4> NewReleases;
3371 SmallVector<Instruction *, 8> DeadInsts;
3373 // Visit each retain.
3374 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
3375 E = Retains.end(); I != E; ++I) {
3376 Value *V = I->first;
3377 if (!V) continue; // blotted
3379 Instruction *Retain = cast<Instruction>(V);
3381 DEBUG(dbgs() << "ObjCARCOpt::PerformCodePlacement: Visiting: " << *Retain
3384 Value *Arg = GetObjCArg(Retain);
3386 // If the object being released is in static or stack storage, we know it's
3387 // not being managed by ObjC reference counting, so we can delete pairs
3388 // regardless of what possible decrements or uses lie between them.
3389 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
3391 // A constant pointer can't be pointing to an object on the heap. It may
3392 // be reference-counted, but it won't be deleted.
3393 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3394 if (const GlobalVariable *GV =
3395 dyn_cast<GlobalVariable>(
3396 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3397 if (GV->isConstant())
3400 // If a pair happens in a region where it is known that the reference count
3401 // is already incremented, we can similarly ignore possible decrements.
3402 bool KnownSafeTD = true, KnownSafeBU = true;
3404 // Connect the dots between the top-down-collected RetainsToMove and
3405 // bottom-up-collected ReleasesToMove to form sets of related calls.
3406 // This is an iterative process so that we connect multiple releases
3407 // to multiple retains if needed.
3408 unsigned OldDelta = 0;
3409 unsigned NewDelta = 0;
3410 unsigned OldCount = 0;
3411 unsigned NewCount = 0;
3412 bool FirstRelease = true;
3413 bool FirstRetain = true;
3414 NewRetains.push_back(Retain);
3416 for (SmallVectorImpl<Instruction *>::const_iterator
3417 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3418 Instruction *NewRetain = *NI;
3419 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3420 assert(It != Retains.end());
3421 const RRInfo &NewRetainRRI = It->second;
3422 KnownSafeTD &= NewRetainRRI.KnownSafe;
3423 for (SmallPtrSet<Instruction *, 2>::const_iterator
3424 LI = NewRetainRRI.Calls.begin(),
3425 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3426 Instruction *NewRetainRelease = *LI;
3427 DenseMap<Value *, RRInfo>::const_iterator Jt =
3428 Releases.find(NewRetainRelease);
3429 if (Jt == Releases.end())
3431 const RRInfo &NewRetainReleaseRRI = Jt->second;
3432 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3433 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3435 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3437 // Merge the ReleaseMetadata and IsTailCallRelease values.
3439 ReleasesToMove.ReleaseMetadata =
3440 NewRetainReleaseRRI.ReleaseMetadata;
3441 ReleasesToMove.IsTailCallRelease =
3442 NewRetainReleaseRRI.IsTailCallRelease;
3443 FirstRelease = false;
3445 if (ReleasesToMove.ReleaseMetadata !=
3446 NewRetainReleaseRRI.ReleaseMetadata)
3447 ReleasesToMove.ReleaseMetadata = 0;
3448 if (ReleasesToMove.IsTailCallRelease !=
3449 NewRetainReleaseRRI.IsTailCallRelease)
3450 ReleasesToMove.IsTailCallRelease = false;
3453 // Collect the optimal insertion points.
3455 for (SmallPtrSet<Instruction *, 2>::const_iterator
3456 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3457 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3459 Instruction *RIP = *RI;
3460 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3461 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3463 NewReleases.push_back(NewRetainRelease);
3468 if (NewReleases.empty()) break;
3470 // Back the other way.
3471 for (SmallVectorImpl<Instruction *>::const_iterator
3472 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3473 Instruction *NewRelease = *NI;
3474 DenseMap<Value *, RRInfo>::const_iterator It =
3475 Releases.find(NewRelease);
3476 assert(It != Releases.end());
3477 const RRInfo &NewReleaseRRI = It->second;
3478 KnownSafeBU &= NewReleaseRRI.KnownSafe;
3479 for (SmallPtrSet<Instruction *, 2>::const_iterator
3480 LI = NewReleaseRRI.Calls.begin(),
3481 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3482 Instruction *NewReleaseRetain = *LI;
3483 MapVector<Value *, RRInfo>::const_iterator Jt =
3484 Retains.find(NewReleaseRetain);
3485 if (Jt == Retains.end())
3487 const RRInfo &NewReleaseRetainRRI = Jt->second;
3488 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3489 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3490 unsigned PathCount =
3491 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3492 OldDelta += PathCount;
3493 OldCount += PathCount;
3495 // Merge the IsRetainBlock values.
3497 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3498 FirstRetain = false;
3499 } else if (ReleasesToMove.IsRetainBlock !=
3500 NewReleaseRetainRRI.IsRetainBlock)
3501 // It's not possible to merge the sequences if one uses
3502 // objc_retain and the other uses objc_retainBlock.
3505 // Collect the optimal insertion points.
3507 for (SmallPtrSet<Instruction *, 2>::const_iterator
3508 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3509 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3511 Instruction *RIP = *RI;
3512 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3513 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3514 NewDelta += PathCount;
3515 NewCount += PathCount;
3518 NewRetains.push_back(NewReleaseRetain);
3522 NewReleases.clear();
3523 if (NewRetains.empty()) break;
3526 // If the pointer is known incremented or nested, we can safely delete the
3527 // pair regardless of what's between them.
3528 if (KnownSafeTD || KnownSafeBU) {
3529 RetainsToMove.ReverseInsertPts.clear();
3530 ReleasesToMove.ReverseInsertPts.clear();
3533 // Determine whether the new insertion points we computed preserve the
3534 // balance of retain and release calls through the program.
3535 // TODO: If the fully aggressive solution isn't valid, try to find a
3536 // less aggressive solution which is.
3541 // Determine whether the original call points are balanced in the retain and
3542 // release calls through the program. If not, conservatively don't touch
3544 // TODO: It's theoretically possible to do code motion in this case, as
3545 // long as the existing imbalances are maintained.
3549 // Ok, everything checks out and we're all set. Let's move some code!
3551 assert(OldCount != 0 && "Unreachable code?");
3552 AnyPairsCompletelyEliminated = NewCount == 0;
3553 NumRRs += OldCount - NewCount;
3554 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3555 Retains, Releases, DeadInsts, M);
3558 NewReleases.clear();
3560 RetainsToMove.clear();
3561 ReleasesToMove.clear();
3564 // Now that we're done moving everything, we can delete the newly dead
3565 // instructions, as we no longer need them as insert points.
3566 while (!DeadInsts.empty())
3567 EraseInstruction(DeadInsts.pop_back_val());
3569 return AnyPairsCompletelyEliminated;
3572 /// OptimizeWeakCalls - Weak pointer optimizations.
3573 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3574 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3575 // itself because it uses AliasAnalysis and we need to do provenance
3577 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3578 Instruction *Inst = &*I++;
3580 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Visiting: " << *Inst <<
3583 InstructionClass Class = GetBasicInstructionClass(Inst);
3584 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3587 // Delete objc_loadWeak calls with no users.
3588 if (Class == IC_LoadWeak && Inst->use_empty()) {
3589 Inst->eraseFromParent();
3593 // TODO: For now, just look for an earlier available version of this value
3594 // within the same block. Theoretically, we could do memdep-style non-local
3595 // analysis too, but that would want caching. A better approach would be to
3596 // use the technique that EarlyCSE uses.
3597 inst_iterator Current = llvm::prior(I);
3598 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3599 for (BasicBlock::iterator B = CurrentBB->begin(),
3600 J = Current.getInstructionIterator();
3602 Instruction *EarlierInst = &*llvm::prior(J);
3603 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3604 switch (EarlierClass) {
3606 case IC_LoadWeakRetained: {
3607 // If this is loading from the same pointer, replace this load's value
3609 CallInst *Call = cast<CallInst>(Inst);
3610 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3611 Value *Arg = Call->getArgOperand(0);
3612 Value *EarlierArg = EarlierCall->getArgOperand(0);
3613 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3614 case AliasAnalysis::MustAlias:
3616 // If the load has a builtin retain, insert a plain retain for it.
3617 if (Class == IC_LoadWeakRetained) {
3619 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3623 // Zap the fully redundant load.
3624 Call->replaceAllUsesWith(EarlierCall);
3625 Call->eraseFromParent();
3627 case AliasAnalysis::MayAlias:
3628 case AliasAnalysis::PartialAlias:
3630 case AliasAnalysis::NoAlias:
3637 // If this is storing to the same pointer and has the same size etc.
3638 // replace this load's value with the stored value.
3639 CallInst *Call = cast<CallInst>(Inst);
3640 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3641 Value *Arg = Call->getArgOperand(0);
3642 Value *EarlierArg = EarlierCall->getArgOperand(0);
3643 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3644 case AliasAnalysis::MustAlias:
3646 // If the load has a builtin retain, insert a plain retain for it.
3647 if (Class == IC_LoadWeakRetained) {
3649 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3653 // Zap the fully redundant load.
3654 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3655 Call->eraseFromParent();
3657 case AliasAnalysis::MayAlias:
3658 case AliasAnalysis::PartialAlias:
3660 case AliasAnalysis::NoAlias:
3667 // TOOD: Grab the copied value.
3669 case IC_AutoreleasepoolPush:
3672 // Weak pointers are only modified through the weak entry points
3673 // (and arbitrary calls, which could call the weak entry points).
3676 // Anything else could modify the weak pointer.
3683 // Then, for each destroyWeak with an alloca operand, check to see if
3684 // the alloca and all its users can be zapped.
3685 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3686 Instruction *Inst = &*I++;
3687 InstructionClass Class = GetBasicInstructionClass(Inst);
3688 if (Class != IC_DestroyWeak)
3691 CallInst *Call = cast<CallInst>(Inst);
3692 Value *Arg = Call->getArgOperand(0);
3693 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3694 for (Value::use_iterator UI = Alloca->use_begin(),
3695 UE = Alloca->use_end(); UI != UE; ++UI) {
3696 const Instruction *UserInst = cast<Instruction>(*UI);
3697 switch (GetBasicInstructionClass(UserInst)) {
3700 case IC_DestroyWeak:
3707 for (Value::use_iterator UI = Alloca->use_begin(),
3708 UE = Alloca->use_end(); UI != UE; ) {
3709 CallInst *UserInst = cast<CallInst>(*UI++);
3710 switch (GetBasicInstructionClass(UserInst)) {
3713 // These functions return their second argument.
3714 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3716 case IC_DestroyWeak:
3720 llvm_unreachable("alloca really is used!");
3722 UserInst->eraseFromParent();
3724 Alloca->eraseFromParent();
3729 DEBUG(dbgs() << "ObjCARCOpt::OptimizeWeakCalls: Finished List.\n\n");
3733 /// OptimizeSequences - Identify program paths which execute sequences of
3734 /// retains and releases which can be eliminated.
3735 bool ObjCARCOpt::OptimizeSequences(Function &F) {
3736 /// Releases, Retains - These are used to store the results of the main flow
3737 /// analysis. These use Value* as the key instead of Instruction* so that the
3738 /// map stays valid when we get around to rewriting code and calls get
3739 /// replaced by arguments.
3740 DenseMap<Value *, RRInfo> Releases;
3741 MapVector<Value *, RRInfo> Retains;
3743 /// BBStates, This is used during the traversal of the function to track the
3744 /// states for each identified object at each block.
3745 DenseMap<const BasicBlock *, BBState> BBStates;
3747 // Analyze the CFG of the function, and all instructions.
3748 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3751 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3755 /// OptimizeReturns - Look for this pattern:
3757 /// %call = call i8* @something(...)
3758 /// %2 = call i8* @objc_retain(i8* %call)
3759 /// %3 = call i8* @objc_autorelease(i8* %2)
3762 /// And delete the retain and autorelease.
3764 /// Otherwise if it's just this:
3766 /// %3 = call i8* @objc_autorelease(i8* %2)
3769 /// convert the autorelease to autoreleaseRV.
3770 void ObjCARCOpt::OptimizeReturns(Function &F) {
3771 if (!F.getReturnType()->isPointerTy())
3774 SmallPtrSet<Instruction *, 4> DependingInstructions;
3775 SmallPtrSet<const BasicBlock *, 4> Visited;
3776 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3777 BasicBlock *BB = FI;
3778 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3780 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Visiting: " << *Ret << "\n");
3784 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3785 FindDependencies(NeedsPositiveRetainCount, Arg,
3786 BB, Ret, DependingInstructions, Visited, PA);
3787 if (DependingInstructions.size() != 1)
3791 CallInst *Autorelease =
3792 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3795 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
3796 if (!IsAutorelease(AutoreleaseClass))
3798 if (GetObjCArg(Autorelease) != Arg)
3801 DependingInstructions.clear();
3804 // Check that there is nothing that can affect the reference
3805 // count between the autorelease and the retain.
3806 FindDependencies(CanChangeRetainCount, Arg,
3807 BB, Autorelease, DependingInstructions, Visited, PA);
3808 if (DependingInstructions.size() != 1)
3813 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3815 // Check that we found a retain with the same argument.
3817 !IsRetain(GetBasicInstructionClass(Retain)) ||
3818 GetObjCArg(Retain) != Arg)
3821 DependingInstructions.clear();
3824 // Convert the autorelease to an autoreleaseRV, since it's
3825 // returning the value.
3826 if (AutoreleaseClass == IC_Autorelease) {
3827 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Converting autorelease "
3828 "=> autoreleaseRV since it's returning a value.\n"
3829 " In: " << *Autorelease
3831 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3832 DEBUG(dbgs() << " Out: " << *Autorelease
3834 Autorelease->setTailCall(); // Always tail call autoreleaseRV.
3835 AutoreleaseClass = IC_AutoreleaseRV;
3838 // Check that there is nothing that can affect the reference
3839 // count between the retain and the call.
3840 // Note that Retain need not be in BB.
3841 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
3842 DependingInstructions, Visited, PA);
3843 if (DependingInstructions.size() != 1)
3848 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3850 // Check that the pointer is the return value of the call.
3851 if (!Call || Arg != Call)
3854 // Check that the call is a regular call.
3855 InstructionClass Class = GetBasicInstructionClass(Call);
3856 if (Class != IC_CallOrUser && Class != IC_Call)
3859 // If so, we can zap the retain and autorelease.
3862 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Erasing: " << *Retain
3864 << *Autorelease << "\n");
3865 EraseInstruction(Retain);
3866 EraseInstruction(Autorelease);
3872 DependingInstructions.clear();
3876 DEBUG(dbgs() << "ObjCARCOpt::OptimizeReturns: Finished List.\n\n");
3880 bool ObjCARCOpt::doInitialization(Module &M) {
3884 // If nothing in the Module uses ARC, don't do anything.
3885 Run = ModuleHasARC(M);
3889 // Identify the imprecise release metadata kind.
3890 ImpreciseReleaseMDKind =
3891 M.getContext().getMDKindID("clang.imprecise_release");
3892 CopyOnEscapeMDKind =
3893 M.getContext().getMDKindID("clang.arc.copy_on_escape");
3894 NoObjCARCExceptionsMDKind =
3895 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
3897 // Intuitively, objc_retain and others are nocapture, however in practice
3898 // they are not, because they return their argument value. And objc_release
3899 // calls finalizers which can have arbitrary side effects.
3901 // These are initialized lazily.
3903 AutoreleaseRVCallee = 0;
3906 RetainBlockCallee = 0;
3907 AutoreleaseCallee = 0;
3912 bool ObjCARCOpt::runOnFunction(Function &F) {
3916 // If nothing in the Module uses ARC, don't do anything.
3922 DEBUG(dbgs() << "ObjCARCOpt: Visiting Function: " << F.getName() << "\n");
3924 PA.setAA(&getAnalysis<AliasAnalysis>());
3926 // This pass performs several distinct transformations. As a compile-time aid
3927 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3928 // library functions aren't declared.
3930 // Preliminary optimizations. This also computs UsedInThisFunction.
3931 OptimizeIndividualCalls(F);
3933 // Optimizations for weak pointers.
3934 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3935 (1 << IC_LoadWeakRetained) |
3936 (1 << IC_StoreWeak) |
3937 (1 << IC_InitWeak) |
3938 (1 << IC_CopyWeak) |
3939 (1 << IC_MoveWeak) |
3940 (1 << IC_DestroyWeak)))
3941 OptimizeWeakCalls(F);
3943 // Optimizations for retain+release pairs.
3944 if (UsedInThisFunction & ((1 << IC_Retain) |
3945 (1 << IC_RetainRV) |
3946 (1 << IC_RetainBlock)))
3947 if (UsedInThisFunction & (1 << IC_Release))
3948 // Run OptimizeSequences until it either stops making changes or
3949 // no retain+release pair nesting is detected.
3950 while (OptimizeSequences(F)) {}
3952 // Optimizations if objc_autorelease is used.
3953 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3954 (1 << IC_AutoreleaseRV)))
3957 DEBUG(dbgs() << "\n");
3962 void ObjCARCOpt::releaseMemory() {
3966 //===----------------------------------------------------------------------===//
3968 //===----------------------------------------------------------------------===//
3970 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
3971 // dominated by single calls.
3973 #include "llvm/Analysis/Dominators.h"
3974 #include "llvm/IR/InlineAsm.h"
3975 #include "llvm/IR/Operator.h"
3977 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3980 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3981 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3982 class ObjCARCContract : public FunctionPass {
3986 ProvenanceAnalysis PA;
3988 /// Run - A flag indicating whether this optimization pass should run.
3991 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3992 /// functions, for use in creating calls to them. These are initialized
3993 /// lazily to avoid cluttering up the Module with unused declarations.
3994 Constant *StoreStrongCallee,
3995 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3997 /// RetainRVMarker - The inline asm string to insert between calls and
3998 /// RetainRV calls to make the optimization work on targets which need it.
3999 const MDString *RetainRVMarker;
4001 /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
4002 /// at the end of walking the function we have found no alloca
4003 /// instructions, these calls can be marked "tail".
4004 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
4006 Constant *getStoreStrongCallee(Module *M);
4007 Constant *getRetainAutoreleaseCallee(Module *M);
4008 Constant *getRetainAutoreleaseRVCallee(Module *M);
4010 bool ContractAutorelease(Function &F, Instruction *Autorelease,
4011 InstructionClass Class,
4012 SmallPtrSet<Instruction *, 4>
4013 &DependingInstructions,
4014 SmallPtrSet<const BasicBlock *, 4>
4017 void ContractRelease(Instruction *Release,
4018 inst_iterator &Iter);
4020 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
4021 virtual bool doInitialization(Module &M);
4022 virtual bool runOnFunction(Function &F);
4026 ObjCARCContract() : FunctionPass(ID) {
4027 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
4032 char ObjCARCContract::ID = 0;
4033 INITIALIZE_PASS_BEGIN(ObjCARCContract,
4034 "objc-arc-contract", "ObjC ARC contraction", false, false)
4035 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
4036 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
4037 INITIALIZE_PASS_END(ObjCARCContract,
4038 "objc-arc-contract", "ObjC ARC contraction", false, false)
4040 Pass *llvm::createObjCARCContractPass() {
4041 return new ObjCARCContract();
4044 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
4045 AU.addRequired<AliasAnalysis>();
4046 AU.addRequired<DominatorTree>();
4047 AU.setPreservesCFG();
4050 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
4051 if (!StoreStrongCallee) {
4052 LLVMContext &C = M->getContext();
4053 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4054 Type *I8XX = PointerType::getUnqual(I8X);
4055 Type *Params[] = { I8XX, I8X };
4057 AttributeSet Attribute = AttributeSet()
4058 .addAttr(M->getContext(), AttributeSet::FunctionIndex,
4059 Attribute::get(C, Attribute::NoUnwind))
4060 .addAttr(M->getContext(), 1, Attribute::get(C, Attribute::NoCapture));
4063 M->getOrInsertFunction(
4065 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
4068 return StoreStrongCallee;
4071 Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
4072 if (!RetainAutoreleaseCallee) {
4073 LLVMContext &C = M->getContext();
4074 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4075 Type *Params[] = { I8X };
4076 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
4077 AttributeSet Attribute =
4078 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
4079 Attribute::get(C, Attribute::NoUnwind));
4080 RetainAutoreleaseCallee =
4081 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
4083 return RetainAutoreleaseCallee;
4086 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
4087 if (!RetainAutoreleaseRVCallee) {
4088 LLVMContext &C = M->getContext();
4089 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4090 Type *Params[] = { I8X };
4091 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
4092 AttributeSet Attribute =
4093 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
4094 Attribute::get(C, Attribute::NoUnwind));
4095 RetainAutoreleaseRVCallee =
4096 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
4099 return RetainAutoreleaseRVCallee;
4102 /// ContractAutorelease - Merge an autorelease with a retain into a fused call.
4104 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
4105 InstructionClass Class,
4106 SmallPtrSet<Instruction *, 4>
4107 &DependingInstructions,
4108 SmallPtrSet<const BasicBlock *, 4>
4110 const Value *Arg = GetObjCArg(Autorelease);
4112 // Check that there are no instructions between the retain and the autorelease
4113 // (such as an autorelease_pop) which may change the count.
4114 CallInst *Retain = 0;
4115 if (Class == IC_AutoreleaseRV)
4116 FindDependencies(RetainAutoreleaseRVDep, Arg,
4117 Autorelease->getParent(), Autorelease,
4118 DependingInstructions, Visited, PA);
4120 FindDependencies(RetainAutoreleaseDep, Arg,
4121 Autorelease->getParent(), Autorelease,
4122 DependingInstructions, Visited, PA);
4125 if (DependingInstructions.size() != 1) {
4126 DependingInstructions.clear();
4130 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
4131 DependingInstructions.clear();
4134 GetBasicInstructionClass(Retain) != IC_Retain ||
4135 GetObjCArg(Retain) != Arg)
4141 DEBUG(dbgs() << "ObjCARCContract::ContractAutorelease: Fusing "
4142 "retain/autorelease. Erasing: " << *Autorelease << "\n"
4144 << *Retain << "\n");
4146 if (Class == IC_AutoreleaseRV)
4147 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
4149 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
4151 DEBUG(dbgs() << " New Retain: "
4152 << *Retain << "\n");
4154 EraseInstruction(Autorelease);
4158 /// ContractRelease - Attempt to merge an objc_release with a store, load, and
4159 /// objc_retain to form an objc_storeStrong. This can be a little tricky because
4160 /// the instructions don't always appear in order, and there may be unrelated
4161 /// intervening instructions.
4162 void ObjCARCContract::ContractRelease(Instruction *Release,
4163 inst_iterator &Iter) {
4164 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
4165 if (!Load || !Load->isSimple()) return;
4167 // For now, require everything to be in one basic block.
4168 BasicBlock *BB = Release->getParent();
4169 if (Load->getParent() != BB) return;
4171 // Walk down to find the store and the release, which may be in either order.
4172 BasicBlock::iterator I = Load, End = BB->end();
4174 AliasAnalysis::Location Loc = AA->getLocation(Load);
4175 StoreInst *Store = 0;
4176 bool SawRelease = false;
4177 for (; !Store || !SawRelease; ++I) {
4181 Instruction *Inst = I;
4182 if (Inst == Release) {
4187 InstructionClass Class = GetBasicInstructionClass(Inst);
4189 // Unrelated retains are harmless.
4190 if (IsRetain(Class))
4194 // The store is the point where we're going to put the objc_storeStrong,
4195 // so make sure there are no uses after it.
4196 if (CanUse(Inst, Load, PA, Class))
4198 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
4199 // We are moving the load down to the store, so check for anything
4200 // else which writes to the memory between the load and the store.
4201 Store = dyn_cast<StoreInst>(Inst);
4202 if (!Store || !Store->isSimple()) return;
4203 if (Store->getPointerOperand() != Loc.Ptr) return;
4207 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
4209 // Walk up to find the retain.
4211 BasicBlock::iterator Begin = BB->begin();
4212 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
4214 Instruction *Retain = I;
4215 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
4216 if (GetObjCArg(Retain) != New) return;
4221 LLVMContext &C = Release->getContext();
4222 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4223 Type *I8XX = PointerType::getUnqual(I8X);
4225 Value *Args[] = { Load->getPointerOperand(), New };
4226 if (Args[0]->getType() != I8XX)
4227 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
4228 if (Args[1]->getType() != I8X)
4229 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
4230 CallInst *StoreStrong =
4231 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
4233 StoreStrong->setDoesNotThrow();
4234 StoreStrong->setDebugLoc(Store->getDebugLoc());
4236 // We can't set the tail flag yet, because we haven't yet determined
4237 // whether there are any escaping allocas. Remember this call, so that
4238 // we can set the tail flag once we know it's safe.
4239 StoreStrongCalls.insert(StoreStrong);
4241 if (&*Iter == Store) ++Iter;
4242 Store->eraseFromParent();
4243 Release->eraseFromParent();
4244 EraseInstruction(Retain);
4245 if (Load->use_empty())
4246 Load->eraseFromParent();
4249 bool ObjCARCContract::doInitialization(Module &M) {
4250 // If nothing in the Module uses ARC, don't do anything.
4251 Run = ModuleHasARC(M);
4255 // These are initialized lazily.
4256 StoreStrongCallee = 0;
4257 RetainAutoreleaseCallee = 0;
4258 RetainAutoreleaseRVCallee = 0;
4260 // Initialize RetainRVMarker.
4262 if (NamedMDNode *NMD =
4263 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4264 if (NMD->getNumOperands() == 1) {
4265 const MDNode *N = NMD->getOperand(0);
4266 if (N->getNumOperands() == 1)
4267 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4274 bool ObjCARCContract::runOnFunction(Function &F) {
4278 // If nothing in the Module uses ARC, don't do anything.
4283 AA = &getAnalysis<AliasAnalysis>();
4284 DT = &getAnalysis<DominatorTree>();
4286 PA.setAA(&getAnalysis<AliasAnalysis>());
4288 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4289 // keyword. Be conservative if the function has variadic arguments.
4290 // It seems that functions which "return twice" are also unsafe for the
4291 // "tail" argument, because they are setjmp, which could need to
4292 // return to an earlier stack state.
4293 bool TailOkForStoreStrongs = !F.isVarArg() &&
4294 !F.callsFunctionThatReturnsTwice();
4296 // For ObjC library calls which return their argument, replace uses of the
4297 // argument with uses of the call return value, if it dominates the use. This
4298 // reduces register pressure.
4299 SmallPtrSet<Instruction *, 4> DependingInstructions;
4300 SmallPtrSet<const BasicBlock *, 4> Visited;
4301 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4302 Instruction *Inst = &*I++;
4304 DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
4306 // Only these library routines return their argument. In particular,
4307 // objc_retainBlock does not necessarily return its argument.
4308 InstructionClass Class = GetBasicInstructionClass(Inst);
4311 case IC_FusedRetainAutorelease:
4312 case IC_FusedRetainAutoreleaseRV:
4314 case IC_Autorelease:
4315 case IC_AutoreleaseRV:
4316 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4320 // If we're compiling for a target which needs a special inline-asm
4321 // marker to do the retainAutoreleasedReturnValue optimization,
4323 if (!RetainRVMarker)
4325 BasicBlock::iterator BBI = Inst;
4326 BasicBlock *InstParent = Inst->getParent();
4328 // Step up to see if the call immediately precedes the RetainRV call.
4329 // If it's an invoke, we have to cross a block boundary. And we have
4330 // to carefully dodge no-op instructions.
4332 if (&*BBI == InstParent->begin()) {
4333 BasicBlock *Pred = InstParent->getSinglePredecessor();
4335 goto decline_rv_optimization;
4336 BBI = Pred->getTerminator();
4340 } while (isNoopInstruction(BBI));
4342 if (&*BBI == GetObjCArg(Inst)) {
4343 DEBUG(dbgs() << "ObjCARCContract: Adding inline asm marker for "
4344 "retainAutoreleasedReturnValue optimization.\n");
4347 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4348 /*isVarArg=*/false),
4349 RetainRVMarker->getString(),
4350 /*Constraints=*/"", /*hasSideEffects=*/true);
4351 CallInst::Create(IA, "", Inst);
4353 decline_rv_optimization:
4357 // objc_initWeak(p, null) => *p = null
4358 CallInst *CI = cast<CallInst>(Inst);
4359 if (isNullOrUndef(CI->getArgOperand(1))) {
4361 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4363 new StoreInst(Null, CI->getArgOperand(0), CI);
4365 DEBUG(dbgs() << "OBJCARCContract: Old = " << *CI << "\n"
4366 << " New = " << *Null << "\n");
4368 CI->replaceAllUsesWith(Null);
4369 CI->eraseFromParent();
4374 ContractRelease(Inst, I);
4377 // Be conservative if the function has any alloca instructions.
4378 // Technically we only care about escaping alloca instructions,
4379 // but this is sufficient to handle some interesting cases.
4380 if (isa<AllocaInst>(Inst))
4381 TailOkForStoreStrongs = false;
4387 DEBUG(dbgs() << "ObjCARCContract: Finished List.\n\n");
4389 // Don't use GetObjCArg because we don't want to look through bitcasts
4390 // and such; to do the replacement, the argument must have type i8*.
4391 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4393 // If we're compiling bugpointed code, don't get in trouble.
4394 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4396 // Look through the uses of the pointer.
4397 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4399 Use &U = UI.getUse();
4400 unsigned OperandNo = UI.getOperandNo();
4401 ++UI; // Increment UI now, because we may unlink its element.
4403 // If the call's return value dominates a use of the call's argument
4404 // value, rewrite the use to use the return value. We check for
4405 // reachability here because an unreachable call is considered to
4406 // trivially dominate itself, which would lead us to rewriting its
4407 // argument in terms of its return value, which would lead to
4408 // infinite loops in GetObjCArg.
4409 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
4411 Instruction *Replacement = Inst;
4412 Type *UseTy = U.get()->getType();
4413 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
4414 // For PHI nodes, insert the bitcast in the predecessor block.
4415 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4416 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
4417 if (Replacement->getType() != UseTy)
4418 Replacement = new BitCastInst(Replacement, UseTy, "",
4420 // While we're here, rewrite all edges for this PHI, rather
4421 // than just one use at a time, to minimize the number of
4422 // bitcasts we emit.
4423 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
4424 if (PHI->getIncomingBlock(i) == BB) {
4425 // Keep the UI iterator valid.
4426 if (&PHI->getOperandUse(
4427 PHINode::getOperandNumForIncomingValue(i)) ==
4430 PHI->setIncomingValue(i, Replacement);
4433 if (Replacement->getType() != UseTy)
4434 Replacement = new BitCastInst(Replacement, UseTy, "",
4435 cast<Instruction>(U.getUser()));
4441 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
4442 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4443 Arg = BI->getOperand(0);
4444 else if (isa<GEPOperator>(Arg) &&
4445 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4446 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4447 else if (isa<GlobalAlias>(Arg) &&
4448 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4449 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4455 // If this function has no escaping allocas or suspicious vararg usage,
4456 // objc_storeStrong calls can be marked with the "tail" keyword.
4457 if (TailOkForStoreStrongs)
4458 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
4459 E = StoreStrongCalls.end(); I != E; ++I)
4460 (*I)->setTailCall();
4461 StoreStrongCalls.clear();