1 //===- ObjCARC.cpp - ObjC ARC Optimization --------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines ObjC ARC optimizations. ARC stands for
11 // Automatic Reference Counting and is a system for managing reference counts
12 // for objects in Objective C.
14 // The optimizations performed include elimination of redundant, partially
15 // redundant, and inconsequential reference count operations, elimination of
16 // redundant weak pointer operations, pattern-matching and replacement of
17 // low-level operations into higher-level operations, and numerous minor
20 // This file also defines a simple ARC-aware AliasAnalysis.
22 // WARNING: This file knows about certain library functions. It recognizes them
23 // by name, and hardwires knowedge of their semantics.
25 // WARNING: This file knows about how certain Objective-C library functions are
26 // used. Naive LLVM IR transformations which would otherwise be
27 // behavior-preserving may break these assumptions.
29 //===----------------------------------------------------------------------===//
31 #define DEBUG_TYPE "objc-arc"
32 #include "llvm/Function.h"
33 #include "llvm/Intrinsics.h"
34 #include "llvm/GlobalVariable.h"
35 #include "llvm/DerivedTypes.h"
36 #include "llvm/Analysis/ValueTracking.h"
37 #include "llvm/Transforms/Utils/Local.h"
38 #include "llvm/Support/CallSite.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/ADT/StringSwitch.h"
41 #include "llvm/ADT/DenseMap.h"
42 #include "llvm/ADT/STLExtras.h"
45 // A handy option to enable/disable all optimizations in this file.
46 static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
48 //===----------------------------------------------------------------------===//
50 //===----------------------------------------------------------------------===//
53 /// MapVector - An associative container with fast insertion-order
54 /// (deterministic) iteration over its elements. Plus the special
56 template<class KeyT, class ValueT>
58 /// Map - Map keys to indices in Vector.
59 typedef DenseMap<KeyT, size_t> MapTy;
62 /// Vector - Keys and values.
63 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
67 typedef typename VectorTy::iterator iterator;
68 typedef typename VectorTy::const_iterator const_iterator;
69 iterator begin() { return Vector.begin(); }
70 iterator end() { return Vector.end(); }
71 const_iterator begin() const { return Vector.begin(); }
72 const_iterator end() const { return Vector.end(); }
76 assert(Vector.size() >= Map.size()); // May differ due to blotting.
77 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
79 assert(I->second < Vector.size());
80 assert(Vector[I->second].first == I->first);
82 for (typename VectorTy::const_iterator I = Vector.begin(),
83 E = Vector.end(); I != E; ++I)
85 (Map.count(I->first) &&
86 Map[I->first] == size_t(I - Vector.begin())));
90 ValueT &operator[](KeyT Arg) {
91 std::pair<typename MapTy::iterator, bool> Pair =
92 Map.insert(std::make_pair(Arg, size_t(0)));
94 Pair.first->second = Vector.size();
95 Vector.push_back(std::make_pair(Arg, ValueT()));
96 return Vector.back().second;
98 return Vector[Pair.first->second].second;
101 std::pair<iterator, bool>
102 insert(const std::pair<KeyT, ValueT> &InsertPair) {
103 std::pair<typename MapTy::iterator, bool> Pair =
104 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
106 Pair.first->second = Vector.size();
107 Vector.push_back(InsertPair);
108 return std::make_pair(llvm::prior(Vector.end()), true);
110 return std::make_pair(Vector.begin() + Pair.first->second, false);
113 const_iterator find(KeyT Key) const {
114 typename MapTy::const_iterator It = Map.find(Key);
115 if (It == Map.end()) return Vector.end();
116 return Vector.begin() + It->second;
119 /// blot - This is similar to erase, but instead of removing the element
120 /// from the vector, it just zeros out the key in the vector. This leaves
121 /// iterators intact, but clients must be prepared for zeroed-out keys when
123 void blot(KeyT Key) {
124 typename MapTy::iterator It = Map.find(Key);
125 if (It == Map.end()) return;
126 Vector[It->second].first = KeyT();
137 //===----------------------------------------------------------------------===//
139 //===----------------------------------------------------------------------===//
142 /// InstructionClass - A simple classification for instructions.
143 enum InstructionClass {
144 IC_Retain, ///< objc_retain
145 IC_RetainRV, ///< objc_retainAutoreleasedReturnValue
146 IC_RetainBlock, ///< objc_retainBlock
147 IC_Release, ///< objc_release
148 IC_Autorelease, ///< objc_autorelease
149 IC_AutoreleaseRV, ///< objc_autoreleaseReturnValue
150 IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
151 IC_AutoreleasepoolPop, ///< objc_autoreleasePoolPop
152 IC_NoopCast, ///< objc_retainedObject, etc.
153 IC_FusedRetainAutorelease, ///< objc_retainAutorelease
154 IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
155 IC_LoadWeakRetained, ///< objc_loadWeakRetained (primitive)
156 IC_StoreWeak, ///< objc_storeWeak (primitive)
157 IC_InitWeak, ///< objc_initWeak (derived)
158 IC_LoadWeak, ///< objc_loadWeak (derived)
159 IC_MoveWeak, ///< objc_moveWeak (derived)
160 IC_CopyWeak, ///< objc_copyWeak (derived)
161 IC_DestroyWeak, ///< objc_destroyWeak (derived)
162 IC_CallOrUser, ///< could call objc_release and/or "use" pointers
163 IC_Call, ///< could call objc_release
164 IC_User, ///< could "use" a pointer
165 IC_None ///< anything else
169 /// IsPotentialUse - Test whether the given value is possible a
170 /// reference-counted pointer.
171 static bool IsPotentialUse(const Value *Op) {
172 // Pointers to static or stack storage are not reference-counted pointers.
173 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
175 // Special arguments are not reference-counted.
176 if (const Argument *Arg = dyn_cast<Argument>(Op))
177 if (Arg->hasByValAttr() ||
178 Arg->hasNestAttr() ||
179 Arg->hasStructRetAttr())
181 // Only consider values with pointer types, and not function pointers.
182 const PointerType *Ty = dyn_cast<PointerType>(Op->getType());
183 if (!Ty || isa<FunctionType>(Ty->getElementType()))
185 // Conservatively assume anything else is a potential use.
189 /// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind
190 /// of construct CS is.
191 static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
192 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
194 if (IsPotentialUse(*I))
195 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
197 return CS.onlyReadsMemory() ? IC_None : IC_Call;
200 /// GetFunctionClass - Determine if F is one of the special known Functions.
201 /// If it isn't, return IC_CallOrUser.
202 static InstructionClass GetFunctionClass(const Function *F) {
203 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
207 return StringSwitch<InstructionClass>(F->getName())
208 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
209 .Default(IC_CallOrUser);
212 const Argument *A0 = AI++;
214 // Argument is a pointer.
215 if (const PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
216 const Type *ETy = PTy->getElementType();
218 if (ETy->isIntegerTy(8))
219 return StringSwitch<InstructionClass>(F->getName())
220 .Case("objc_retain", IC_Retain)
221 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
222 .Case("objc_retainBlock", IC_RetainBlock)
223 .Case("objc_release", IC_Release)
224 .Case("objc_autorelease", IC_Autorelease)
225 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
226 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
227 .Case("objc_retainedObject", IC_NoopCast)
228 .Case("objc_unretainedObject", IC_NoopCast)
229 .Case("objc_unretainedPointer", IC_NoopCast)
230 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
231 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
232 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
233 .Default(IC_CallOrUser);
236 if (const PointerType *Pte = dyn_cast<PointerType>(ETy))
237 if (Pte->getElementType()->isIntegerTy(8))
238 return StringSwitch<InstructionClass>(F->getName())
239 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
240 .Case("objc_loadWeak", IC_LoadWeak)
241 .Case("objc_destroyWeak", IC_DestroyWeak)
242 .Default(IC_CallOrUser);
245 // Two arguments, first is i8**.
246 const Argument *A1 = AI++;
248 if (const PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
249 if (const PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
250 if (Pte->getElementType()->isIntegerTy(8))
251 if (const PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
252 const Type *ETy1 = PTy1->getElementType();
253 // Second argument is i8*
254 if (ETy1->isIntegerTy(8))
255 return StringSwitch<InstructionClass>(F->getName())
256 .Case("objc_storeWeak", IC_StoreWeak)
257 .Case("objc_initWeak", IC_InitWeak)
258 .Default(IC_CallOrUser);
259 // Second argument is i8**.
260 if (const PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
261 if (Pte1->getElementType()->isIntegerTy(8))
262 return StringSwitch<InstructionClass>(F->getName())
263 .Case("objc_moveWeak", IC_MoveWeak)
264 .Case("objc_copyWeak", IC_CopyWeak)
265 .Default(IC_CallOrUser);
269 return IC_CallOrUser;
272 /// GetInstructionClass - Determine what kind of construct V is.
273 static InstructionClass GetInstructionClass(const Value *V) {
274 if (const Instruction *I = dyn_cast<Instruction>(V)) {
275 // Any instruction other than bitcast and gep with a pointer operand have a
276 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
277 // to a subsequent use, rather than using it themselves, in this sense.
278 // As a short cut, several other opcodes are known to have no pointer
279 // operands of interest. And ret is never followed by a release, so it's
280 // not interesting to examine.
281 switch (I->getOpcode()) {
282 case Instruction::Call: {
283 const CallInst *CI = cast<CallInst>(I);
284 // Check for calls to special functions.
285 if (const Function *F = CI->getCalledFunction()) {
286 InstructionClass Class = GetFunctionClass(F);
287 if (Class != IC_CallOrUser)
290 // None of the intrinsic functions do objc_release. For intrinsics, the
291 // only question is whether or not they may be users.
292 switch (F->getIntrinsicID()) {
294 case Intrinsic::bswap: case Intrinsic::ctpop:
295 case Intrinsic::ctlz: case Intrinsic::cttz:
296 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
297 case Intrinsic::stacksave: case Intrinsic::stackrestore:
298 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
299 // Don't let dbg info affect our results.
300 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
301 // Short cut: Some intrinsics obviously don't use ObjC pointers.
304 for (Function::const_arg_iterator AI = F->arg_begin(),
305 AE = F->arg_end(); AI != AE; ++AI)
306 if (IsPotentialUse(AI))
311 return GetCallSiteClass(CI);
313 case Instruction::Invoke:
314 return GetCallSiteClass(cast<InvokeInst>(I));
315 case Instruction::BitCast:
316 case Instruction::GetElementPtr:
317 case Instruction::Select: case Instruction::PHI:
318 case Instruction::Ret: case Instruction::Br:
319 case Instruction::Switch: case Instruction::IndirectBr:
320 case Instruction::Alloca: case Instruction::VAArg:
321 case Instruction::Add: case Instruction::FAdd:
322 case Instruction::Sub: case Instruction::FSub:
323 case Instruction::Mul: case Instruction::FMul:
324 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
325 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
326 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
327 case Instruction::And: case Instruction::Or: case Instruction::Xor:
328 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
329 case Instruction::IntToPtr: case Instruction::FCmp:
330 case Instruction::FPTrunc: case Instruction::FPExt:
331 case Instruction::FPToUI: case Instruction::FPToSI:
332 case Instruction::UIToFP: case Instruction::SIToFP:
333 case Instruction::InsertElement: case Instruction::ExtractElement:
334 case Instruction::ShuffleVector:
335 case Instruction::ExtractValue:
337 case Instruction::ICmp:
338 // Comparing a pointer with null, or any other constant, isn't an
339 // interesting use, because we don't care what the pointer points to, or
340 // about the values of any other dynamic reference-counted pointers.
341 if (IsPotentialUse(I->getOperand(1)))
345 // For anything else, check all the operands.
346 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
348 if (IsPotentialUse(*OI))
353 // Otherwise, it's totally inert for ARC purposes.
357 /// GetBasicInstructionClass - Determine what kind of construct V is. This is
358 /// similar to GetInstructionClass except that it only detects objc runtine
359 /// calls. This allows it to be faster.
360 static InstructionClass GetBasicInstructionClass(const Value *V) {
361 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
362 if (const Function *F = CI->getCalledFunction())
363 return GetFunctionClass(F);
364 // Otherwise, be conservative.
365 return IC_CallOrUser;
368 // Otherwise, be conservative.
372 /// IsRetain - Test if the the given class is objc_retain or
374 static bool IsRetain(InstructionClass Class) {
375 return Class == IC_Retain ||
376 Class == IC_RetainRV;
379 /// IsAutorelease - Test if the the given class is objc_autorelease or
381 static bool IsAutorelease(InstructionClass Class) {
382 return Class == IC_Autorelease ||
383 Class == IC_AutoreleaseRV;
386 /// IsForwarding - Test if the given class represents instructions which return
387 /// their argument verbatim.
388 static bool IsForwarding(InstructionClass Class) {
389 // objc_retainBlock technically doesn't always return its argument
390 // verbatim, but it doesn't matter for our purposes here.
391 return Class == IC_Retain ||
392 Class == IC_RetainRV ||
393 Class == IC_Autorelease ||
394 Class == IC_AutoreleaseRV ||
395 Class == IC_RetainBlock ||
396 Class == IC_NoopCast;
399 /// IsNoopOnNull - Test if the given class represents instructions which do
400 /// nothing if passed a null pointer.
401 static bool IsNoopOnNull(InstructionClass Class) {
402 return Class == IC_Retain ||
403 Class == IC_RetainRV ||
404 Class == IC_Release ||
405 Class == IC_Autorelease ||
406 Class == IC_AutoreleaseRV ||
407 Class == IC_RetainBlock;
410 /// IsAlwaysTail - Test if the given class represents instructions which are
411 /// always safe to mark with the "tail" keyword.
412 static bool IsAlwaysTail(InstructionClass Class) {
413 // IC_RetainBlock may be given a stack argument.
414 return Class == IC_Retain ||
415 Class == IC_RetainRV ||
416 Class == IC_Autorelease ||
417 Class == IC_AutoreleaseRV;
420 /// IsNoThrow - Test if the given class represents instructions which are always
421 /// safe to mark with the nounwind attribute..
422 static bool IsNoThrow(InstructionClass Class) {
423 return Class == IC_Retain ||
424 Class == IC_RetainRV ||
425 Class == IC_RetainBlock ||
426 Class == IC_Release ||
427 Class == IC_Autorelease ||
428 Class == IC_AutoreleaseRV ||
429 Class == IC_AutoreleasepoolPush ||
430 Class == IC_AutoreleasepoolPop;
433 /// EraseInstruction - Erase the given instruction. ObjC calls return their
434 /// argument verbatim, so if it's such a call and the return value has users,
435 /// replace them with the argument value.
436 static void EraseInstruction(Instruction *CI) {
437 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
439 bool Unused = CI->use_empty();
442 // Replace the return value with the argument.
443 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
444 "Can't delete non-forwarding instruction with users!");
445 CI->replaceAllUsesWith(OldArg);
448 CI->eraseFromParent();
451 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
454 /// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
455 /// also knows how to look through objc_retain and objc_autorelease calls, which
456 /// we know to return their argument verbatim.
457 static const Value *GetUnderlyingObjCPtr(const Value *V) {
459 V = GetUnderlyingObject(V);
460 if (!IsForwarding(GetBasicInstructionClass(V)))
462 V = cast<CallInst>(V)->getArgOperand(0);
468 /// StripPointerCastsAndObjCCalls - This is a wrapper around
469 /// Value::stripPointerCasts which also knows how to look through objc_retain
470 /// and objc_autorelease calls, which we know to return their argument verbatim.
471 static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
473 V = V->stripPointerCasts();
474 if (!IsForwarding(GetBasicInstructionClass(V)))
476 V = cast<CallInst>(V)->getArgOperand(0);
481 /// StripPointerCastsAndObjCCalls - This is a wrapper around
482 /// Value::stripPointerCasts which also knows how to look through objc_retain
483 /// and objc_autorelease calls, which we know to return their argument verbatim.
484 static Value *StripPointerCastsAndObjCCalls(Value *V) {
486 V = V->stripPointerCasts();
487 if (!IsForwarding(GetBasicInstructionClass(V)))
489 V = cast<CallInst>(V)->getArgOperand(0);
494 /// GetObjCArg - Assuming the given instruction is one of the special calls such
495 /// as objc_retain or objc_release, return the argument value, stripped of no-op
496 /// casts and forwarding calls.
497 static Value *GetObjCArg(Value *Inst) {
498 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
501 /// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
502 /// isObjCIdentifiedObject, except that it uses special knowledge of
503 /// ObjC conventions...
504 static bool IsObjCIdentifiedObject(const Value *V) {
505 // Assume that call results and arguments have their own "provenance".
506 // Constants (including GlobalVariables) and Allocas are never
507 // reference-counted.
508 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
509 isa<Argument>(V) || isa<Constant>(V) ||
513 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
514 const Value *Pointer =
515 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
516 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
517 StringRef Name = GV->getName();
518 // These special variables are known to hold values which are not
519 // reference-counted pointers.
520 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
521 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
522 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
523 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
524 Name.startswith("\01l_objc_msgSend_fixup_"))
532 /// FindSingleUseIdentifiedObject - This is similar to
533 /// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
534 /// with multiple uses.
535 static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
536 if (Arg->hasOneUse()) {
537 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
538 return FindSingleUseIdentifiedObject(BC->getOperand(0));
539 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
540 if (GEP->hasAllZeroIndices())
541 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
542 if (IsForwarding(GetBasicInstructionClass(Arg)))
543 return FindSingleUseIdentifiedObject(
544 cast<CallInst>(Arg)->getArgOperand(0));
545 if (!IsObjCIdentifiedObject(Arg))
550 // If we found an identifiable object but it has multiple uses, but they
551 // are trivial uses, we can still consider this to be a single-use
553 if (IsObjCIdentifiedObject(Arg)) {
554 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
557 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
567 //===----------------------------------------------------------------------===//
568 // ARC AliasAnalysis.
569 //===----------------------------------------------------------------------===//
571 #include "llvm/Pass.h"
572 #include "llvm/Analysis/AliasAnalysis.h"
573 #include "llvm/Analysis/Passes.h"
576 /// ObjCARCAliasAnalysis - This is a simple alias analysis
577 /// implementation that uses knowledge of ARC constructs to answer queries.
579 /// TODO: This class could be generalized to know about other ObjC-specific
580 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
581 /// even though their offsets are dynamic.
582 class ObjCARCAliasAnalysis : public ImmutablePass,
583 public AliasAnalysis {
585 static char ID; // Class identification, replacement for typeinfo
586 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
587 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
591 virtual void initializePass() {
592 InitializeAliasAnalysis(this);
595 /// getAdjustedAnalysisPointer - This method is used when a pass implements
596 /// an analysis interface through multiple inheritance. If needed, it
597 /// should override this to adjust the this pointer as needed for the
598 /// specified pass info.
599 virtual void *getAdjustedAnalysisPointer(const void *PI) {
600 if (PI == &AliasAnalysis::ID)
601 return (AliasAnalysis*)this;
605 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
606 virtual AliasResult alias(const Location &LocA, const Location &LocB);
607 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
608 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
609 virtual ModRefBehavior getModRefBehavior(const Function *F);
610 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
611 const Location &Loc);
612 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
613 ImmutableCallSite CS2);
615 } // End of anonymous namespace
617 // Register this pass...
618 char ObjCARCAliasAnalysis::ID = 0;
619 INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
620 "ObjC-ARC-Based Alias Analysis", false, true, false)
622 ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
623 return new ObjCARCAliasAnalysis();
627 ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
628 AU.setPreservesAll();
629 AliasAnalysis::getAnalysisUsage(AU);
632 AliasAnalysis::AliasResult
633 ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
635 return AliasAnalysis::alias(LocA, LocB);
637 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
638 // precise alias query.
639 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
640 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
642 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
643 Location(SB, LocB.Size, LocB.TBAATag));
644 if (Result != MayAlias)
647 // If that failed, climb to the underlying object, including climbing through
648 // ObjC-specific no-ops, and try making an imprecise alias query.
649 const Value *UA = GetUnderlyingObjCPtr(SA);
650 const Value *UB = GetUnderlyingObjCPtr(SB);
651 if (UA != SA || UB != SB) {
652 Result = AliasAnalysis::alias(Location(UA), Location(UB));
653 // We can't use MustAlias or PartialAlias results here because
654 // GetUnderlyingObjCPtr may return an offsetted pointer value.
655 if (Result == NoAlias)
659 // If that failed, fail. We don't need to chain here, since that's covered
660 // by the earlier precise query.
665 ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
668 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
670 // First, strip off no-ops, including ObjC-specific no-ops, and try making
671 // a precise alias query.
672 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
673 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
677 // If that failed, climb to the underlying object, including climbing through
678 // ObjC-specific no-ops, and try making an imprecise alias query.
679 const Value *U = GetUnderlyingObjCPtr(S);
681 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
683 // If that failed, fail. We don't need to chain here, since that's covered
684 // by the earlier precise query.
688 AliasAnalysis::ModRefBehavior
689 ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
690 // We have nothing to do. Just chain to the next AliasAnalysis.
691 return AliasAnalysis::getModRefBehavior(CS);
694 AliasAnalysis::ModRefBehavior
695 ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
697 return AliasAnalysis::getModRefBehavior(F);
699 switch (GetFunctionClass(F)) {
701 return DoesNotAccessMemory;
706 return AliasAnalysis::getModRefBehavior(F);
709 AliasAnalysis::ModRefResult
710 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
712 return AliasAnalysis::getModRefInfo(CS, Loc);
714 switch (GetBasicInstructionClass(CS.getInstruction())) {
719 case IC_AutoreleaseRV:
721 case IC_AutoreleasepoolPush:
722 case IC_FusedRetainAutorelease:
723 case IC_FusedRetainAutoreleaseRV:
724 // These functions don't access any memory visible to the compiler.
730 return AliasAnalysis::getModRefInfo(CS, Loc);
733 AliasAnalysis::ModRefResult
734 ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
735 ImmutableCallSite CS2) {
736 // TODO: Theoretically we could check for dependencies between objc_* calls
737 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
738 return AliasAnalysis::getModRefInfo(CS1, CS2);
741 //===----------------------------------------------------------------------===//
743 //===----------------------------------------------------------------------===//
745 #include "llvm/Support/InstIterator.h"
746 #include "llvm/Transforms/Scalar.h"
749 /// ObjCARCExpand - Early ARC transformations.
750 class ObjCARCExpand : public FunctionPass {
751 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
752 virtual bool runOnFunction(Function &F);
756 ObjCARCExpand() : FunctionPass(ID) {
757 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
762 char ObjCARCExpand::ID = 0;
763 INITIALIZE_PASS(ObjCARCExpand,
764 "objc-arc-expand", "ObjC ARC expansion", false, false)
766 Pass *llvm::createObjCARCExpandPass() {
767 return new ObjCARCExpand();
770 void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
771 AU.setPreservesCFG();
774 bool ObjCARCExpand::runOnFunction(Function &F) {
778 bool Changed = false;
780 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
781 Instruction *Inst = &*I;
783 switch (GetBasicInstructionClass(Inst)) {
787 case IC_AutoreleaseRV:
788 case IC_FusedRetainAutorelease:
789 case IC_FusedRetainAutoreleaseRV:
790 // These calls return their argument verbatim, as a low-level
791 // optimization. However, this makes high-level optimizations
792 // harder. Undo any uses of this optimization that the front-end
793 // emitted here. We'll redo them in a later pass.
795 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
805 //===----------------------------------------------------------------------===//
807 //===----------------------------------------------------------------------===//
809 // TODO: On code like this:
812 // stuff_that_cannot_release()
813 // objc_autorelease(%x)
814 // stuff_that_cannot_release()
816 // stuff_that_cannot_release()
817 // objc_autorelease(%x)
819 // The second retain and autorelease can be deleted.
821 // TODO: It should be possible to delete
822 // objc_autoreleasePoolPush and objc_autoreleasePoolPop
823 // pairs if nothing is actually autoreleased between them. Also, autorelease
824 // calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
825 // after inlining) can be turned into plain release calls.
827 // TODO: Critical-edge splitting. If the optimial insertion point is
828 // a critical edge, the current algorithm has to fail, because it doesn't
829 // know how to split edges. It should be possible to make the optimizer
830 // think in terms of edges, rather than blocks, and then split critical
833 // TODO: OptimizeSequences could generalized to be Interprocedural.
835 // TODO: Recognize that a bunch of other objc runtime calls have
836 // non-escaping arguments and non-releasing arguments, and may be
837 // non-autoreleasing.
839 // TODO: Sink autorelease calls as far as possible. Unfortunately we
840 // usually can't sink them past other calls, which would be the main
841 // case where it would be useful.
843 #include "llvm/GlobalAlias.h"
844 #include "llvm/Module.h"
845 #include "llvm/Constants.h"
846 #include "llvm/LLVMContext.h"
847 #include "llvm/Support/ErrorHandling.h"
848 #include "llvm/Support/CFG.h"
849 #include "llvm/ADT/PostOrderIterator.h"
850 #include "llvm/ADT/Statistic.h"
852 STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
853 STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
854 STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
855 STATISTIC(NumRets, "Number of return value forwarding "
856 "retain+autoreleaes eliminated");
857 STATISTIC(NumRRs, "Number of retain+release paths eliminated");
858 STATISTIC(NumPeeps, "Number of calls peephole-optimized");
861 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
862 /// uses many of the same techniques, except it uses special ObjC-specific
863 /// reasoning about pointer relationships.
864 class ProvenanceAnalysis {
867 typedef std::pair<const Value *, const Value *> ValuePairTy;
868 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
869 CachedResultsTy CachedResults;
871 bool relatedCheck(const Value *A, const Value *B);
872 bool relatedSelect(const SelectInst *A, const Value *B);
873 bool relatedPHI(const PHINode *A, const Value *B);
876 void operator=(const ProvenanceAnalysis &);
877 ProvenanceAnalysis(const ProvenanceAnalysis &);
880 ProvenanceAnalysis() {}
882 void setAA(AliasAnalysis *aa) { AA = aa; }
884 AliasAnalysis *getAA() const { return AA; }
886 bool related(const Value *A, const Value *B);
889 CachedResults.clear();
894 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
895 // If the values are Selects with the same condition, we can do a more precise
896 // check: just check for relations between the values on corresponding arms.
897 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
898 if (A->getCondition() == SB->getCondition()) {
899 if (related(A->getTrueValue(), SB->getTrueValue()))
901 if (related(A->getFalseValue(), SB->getFalseValue()))
906 // Check both arms of the Select node individually.
907 if (related(A->getTrueValue(), B))
909 if (related(A->getFalseValue(), B))
912 // The arms both checked out.
916 bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
917 // If the values are PHIs in the same block, we can do a more precise as well
918 // as efficient check: just check for relations between the values on
919 // corresponding edges.
920 if (const PHINode *PNB = dyn_cast<PHINode>(B))
921 if (PNB->getParent() == A->getParent()) {
922 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
923 if (related(A->getIncomingValue(i),
924 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
929 // Check each unique source of the PHI node against B.
930 SmallPtrSet<const Value *, 4> UniqueSrc;
931 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
932 const Value *PV1 = A->getIncomingValue(i);
933 if (UniqueSrc.insert(PV1) && related(PV1, B))
937 // All of the arms checked out.
941 /// isStoredObjCPointer - Test if the value of P, or any value covered by its
942 /// provenance, is ever stored within the function (not counting callees).
943 static bool isStoredObjCPointer(const Value *P) {
944 SmallPtrSet<const Value *, 8> Visited;
945 SmallVector<const Value *, 8> Worklist;
946 Worklist.push_back(P);
949 P = Worklist.pop_back_val();
950 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
952 const User *Ur = *UI;
953 if (isa<StoreInst>(Ur)) {
954 if (UI.getOperandNo() == 0)
955 // The pointer is stored.
957 // The pointed is stored through.
960 if (isa<CallInst>(Ur))
961 // The pointer is passed as an argument, ignore this.
963 if (isa<PtrToIntInst>(P))
966 if (Visited.insert(Ur))
967 Worklist.push_back(Ur);
969 } while (!Worklist.empty());
971 // Everything checked out.
975 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
976 // Skip past provenance pass-throughs.
977 A = GetUnderlyingObjCPtr(A);
978 B = GetUnderlyingObjCPtr(B);
984 // Ask regular AliasAnalysis, for a first approximation.
985 switch (AA->alias(A, B)) {
986 case AliasAnalysis::NoAlias:
988 case AliasAnalysis::MustAlias:
989 case AliasAnalysis::PartialAlias:
991 case AliasAnalysis::MayAlias:
995 bool AIsIdentified = IsObjCIdentifiedObject(A);
996 bool BIsIdentified = IsObjCIdentifiedObject(B);
998 // An ObjC-Identified object can't alias a load if it is never locally stored.
1000 if (BIsIdentified) {
1001 // If both pointers have provenance, they can be directly compared.
1005 if (isa<LoadInst>(B))
1006 return isStoredObjCPointer(A);
1009 if (BIsIdentified && isa<LoadInst>(A))
1010 return isStoredObjCPointer(B);
1013 // Special handling for PHI and Select.
1014 if (const PHINode *PN = dyn_cast<PHINode>(A))
1015 return relatedPHI(PN, B);
1016 if (const PHINode *PN = dyn_cast<PHINode>(B))
1017 return relatedPHI(PN, A);
1018 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1019 return relatedSelect(S, B);
1020 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1021 return relatedSelect(S, A);
1027 bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1028 // Begin by inserting a conservative value into the map. If the insertion
1029 // fails, we have the answer already. If it succeeds, leave it there until we
1030 // compute the real answer to guard against recursive queries.
1031 if (A > B) std::swap(A, B);
1032 std::pair<CachedResultsTy::iterator, bool> Pair =
1033 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1035 return Pair.first->second;
1037 bool Result = relatedCheck(A, B);
1038 CachedResults[ValuePairTy(A, B)] = Result;
1043 // Sequence - A sequence of states that a pointer may go through in which an
1044 // objc_retain and objc_release are actually needed.
1047 S_Retain, ///< objc_retain(x)
1048 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1049 S_Use, ///< any use of x
1050 S_Stop, ///< like S_Release, but code motion is stopped
1051 S_Release, ///< objc_release(x)
1052 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1056 static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1060 if (A == S_None || B == S_None)
1063 // Note that we can't merge S_CanRelease and S_Use.
1064 if (A > B) std::swap(A, B);
1066 // Choose the side which is further along in the sequence.
1067 if (A == S_Retain && (B == S_CanRelease || B == S_Use))
1070 // Choose the side which is further along in the sequence.
1071 if ((A == S_Use || A == S_CanRelease) &&
1072 (B == S_Release || B == S_Stop || B == S_MovableRelease))
1074 // If both sides are releases, choose the more conservative one.
1075 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1077 if (A == S_Release && B == S_MovableRelease)
1085 /// RRInfo - Unidirectional information about either a
1086 /// retain-decrement-use-release sequence or release-use-decrement-retain
1087 /// reverese sequence.
1089 /// KnownIncremented - After an objc_retain, the reference count of the
1090 /// referenced object is known to be positive. Similarly, before an
1091 /// objc_release, the reference count of the referenced object is known to
1092 /// be positive. If there are retain-release pairs in code regions where the
1093 /// retain count is known to be positive, they can be eliminated, regardless
1094 /// of any side effects between them.
1095 bool KnownIncremented;
1097 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1098 /// opposed to objc_retain calls).
1101 /// IsTailCallRelease - True of the objc_release calls are all marked
1102 /// with the "tail" keyword.
1103 bool IsTailCallRelease;
1105 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1106 /// a clang.imprecise_release tag, this is the metadata tag.
1107 MDNode *ReleaseMetadata;
1109 /// Calls - For a top-down sequence, the set of objc_retains or
1110 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1111 SmallPtrSet<Instruction *, 2> Calls;
1113 /// ReverseInsertPts - The set of optimal insert positions for
1114 /// moving calls in the opposite sequence.
1115 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1118 KnownIncremented(false), IsRetainBlock(false), IsTailCallRelease(false),
1119 ReleaseMetadata(0) {}
1125 void RRInfo::clear() {
1126 KnownIncremented = false;
1127 IsRetainBlock = false;
1128 IsTailCallRelease = false;
1129 ReleaseMetadata = 0;
1131 ReverseInsertPts.clear();
1135 /// PtrState - This class summarizes several per-pointer runtime properties
1136 /// which are propogated through the flow graph.
1138 /// RefCount - The known minimum number of reference count increments.
1141 /// Seq - The current position in the sequence.
1145 /// RRI - Unidirectional information about the current sequence.
1146 /// TODO: Encapsulate this better.
1149 PtrState() : RefCount(0), Seq(S_None) {}
1151 void IncrementRefCount() {
1152 if (RefCount != UINT_MAX) ++RefCount;
1155 void DecrementRefCount() {
1156 if (RefCount != 0) --RefCount;
1159 void ClearRefCount() {
1163 bool IsKnownIncremented() const {
1164 return RefCount > 0;
1167 void SetSeq(Sequence NewSeq) {
1171 void SetSeqToRelease(MDNode *M) {
1172 if (Seq == S_None || Seq == S_Use) {
1173 Seq = M ? S_MovableRelease : S_Release;
1174 RRI.ReleaseMetadata = M;
1175 } else if (Seq != S_MovableRelease || RRI.ReleaseMetadata != M) {
1177 RRI.ReleaseMetadata = 0;
1181 Sequence GetSeq() const {
1185 void ClearSequenceProgress() {
1190 void Merge(const PtrState &Other, bool TopDown);
1195 PtrState::Merge(const PtrState &Other, bool TopDown) {
1196 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1197 RefCount = std::min(RefCount, Other.RefCount);
1199 // We can't merge a plain objc_retain with an objc_retainBlock.
1200 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1203 if (Seq == S_None) {
1206 // Conservatively merge the ReleaseMetadata information.
1207 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1208 RRI.ReleaseMetadata = 0;
1210 RRI.KnownIncremented = RRI.KnownIncremented && Other.RRI.KnownIncremented;
1211 RRI.IsTailCallRelease = RRI.IsTailCallRelease && Other.RRI.IsTailCallRelease;
1212 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
1213 RRI.ReverseInsertPts.insert(Other.RRI.ReverseInsertPts.begin(),
1214 Other.RRI.ReverseInsertPts.end());
1219 /// BBState - Per-BasicBlock state.
1221 /// TopDownPathCount - The number of unique control paths from the entry
1222 /// which can reach this block.
1223 unsigned TopDownPathCount;
1225 /// BottomUpPathCount - The number of unique control paths to exits
1226 /// from this block.
1227 unsigned BottomUpPathCount;
1229 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1230 typedef MapVector<const Value *, PtrState> MapTy;
1232 /// PerPtrTopDown - The top-down traversal uses this to record information
1233 /// known about a pointer at the bottom of each block.
1234 MapTy PerPtrTopDown;
1236 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1237 /// known about a pointer at the top of each block.
1238 MapTy PerPtrBottomUp;
1241 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1243 typedef MapTy::iterator ptr_iterator;
1244 typedef MapTy::const_iterator ptr_const_iterator;
1246 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1247 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1248 ptr_const_iterator top_down_ptr_begin() const {
1249 return PerPtrTopDown.begin();
1251 ptr_const_iterator top_down_ptr_end() const {
1252 return PerPtrTopDown.end();
1255 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1256 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1257 ptr_const_iterator bottom_up_ptr_begin() const {
1258 return PerPtrBottomUp.begin();
1260 ptr_const_iterator bottom_up_ptr_end() const {
1261 return PerPtrBottomUp.end();
1264 /// SetAsEntry - Mark this block as being an entry block, which has one
1265 /// path from the entry by definition.
1266 void SetAsEntry() { TopDownPathCount = 1; }
1268 /// SetAsExit - Mark this block as being an exit block, which has one
1269 /// path to an exit by definition.
1270 void SetAsExit() { BottomUpPathCount = 1; }
1272 PtrState &getPtrTopDownState(const Value *Arg) {
1273 return PerPtrTopDown[Arg];
1276 PtrState &getPtrBottomUpState(const Value *Arg) {
1277 return PerPtrBottomUp[Arg];
1280 void clearBottomUpPointers() {
1281 PerPtrTopDown.clear();
1284 void clearTopDownPointers() {
1285 PerPtrTopDown.clear();
1288 void InitFromPred(const BBState &Other);
1289 void InitFromSucc(const BBState &Other);
1290 void MergePred(const BBState &Other);
1291 void MergeSucc(const BBState &Other);
1293 /// GetAllPathCount - Return the number of possible unique paths from an
1294 /// entry to an exit which pass through this block. This is only valid
1295 /// after both the top-down and bottom-up traversals are complete.
1296 unsigned GetAllPathCount() const {
1297 return TopDownPathCount * BottomUpPathCount;
1302 void BBState::InitFromPred(const BBState &Other) {
1303 PerPtrTopDown = Other.PerPtrTopDown;
1304 TopDownPathCount = Other.TopDownPathCount;
1307 void BBState::InitFromSucc(const BBState &Other) {
1308 PerPtrBottomUp = Other.PerPtrBottomUp;
1309 BottomUpPathCount = Other.BottomUpPathCount;
1312 /// MergePred - The top-down traversal uses this to merge information about
1313 /// predecessors to form the initial state for a new block.
1314 void BBState::MergePred(const BBState &Other) {
1315 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1316 // loop backedge. Loop backedges are special.
1317 TopDownPathCount += Other.TopDownPathCount;
1319 // For each entry in the other set, if our set has an entry with the same key,
1320 // merge the entries. Otherwise, copy the entry and merge it with an empty
1322 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1323 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1324 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1325 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1329 // For each entry in our set, if the other set doens't have an entry with the
1330 // same key, force it to merge with an empty entry.
1331 for (ptr_iterator MI = top_down_ptr_begin(),
1332 ME = top_down_ptr_end(); MI != ME; ++MI)
1333 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1334 MI->second.Merge(PtrState(), /*TopDown=*/true);
1337 /// MergeSucc - The bottom-up traversal uses this to merge information about
1338 /// successors to form the initial state for a new block.
1339 void BBState::MergeSucc(const BBState &Other) {
1340 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1341 // loop backedge. Loop backedges are special.
1342 BottomUpPathCount += Other.BottomUpPathCount;
1344 // For each entry in the other set, if our set has an entry with the
1345 // same key, merge the entries. Otherwise, copy the entry and merge
1346 // it with an empty entry.
1347 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1348 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1349 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1350 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1354 // For each entry in our set, if the other set doens't have an entry
1355 // with the same key, force it to merge with an empty entry.
1356 for (ptr_iterator MI = bottom_up_ptr_begin(),
1357 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1358 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1359 MI->second.Merge(PtrState(), /*TopDown=*/false);
1363 /// ObjCARCOpt - The main ARC optimization pass.
1364 class ObjCARCOpt : public FunctionPass {
1366 ProvenanceAnalysis PA;
1368 /// RetainFunc, RelaseFunc - Declarations for objc_retain,
1369 /// objc_retainBlock, and objc_release.
1370 Function *RetainFunc, *RetainBlockFunc, *RetainRVFunc, *ReleaseFunc,
1373 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1374 /// functions, for use in creating calls to them. These are initialized
1375 /// lazily to avoid cluttering up the Module with unused declarations.
1376 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
1377 *RetainCallee, *AutoreleaseCallee;
1379 /// UsedInThisFunciton - Flags which determine whether each of the
1380 /// interesting runtine functions is in fact used in the current function.
1381 unsigned UsedInThisFunction;
1383 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1385 unsigned ImpreciseReleaseMDKind;
1387 Constant *getRetainRVCallee(Module *M);
1388 Constant *getAutoreleaseRVCallee(Module *M);
1389 Constant *getReleaseCallee(Module *M);
1390 Constant *getRetainCallee(Module *M);
1391 Constant *getAutoreleaseCallee(Module *M);
1393 void OptimizeRetainCall(Function &F, Instruction *Retain);
1394 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1395 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1396 void OptimizeIndividualCalls(Function &F);
1398 void CheckForCFGHazards(const BasicBlock *BB,
1399 DenseMap<const BasicBlock *, BBState> &BBStates,
1400 BBState &MyStates) const;
1401 bool VisitBottomUp(BasicBlock *BB,
1402 DenseMap<const BasicBlock *, BBState> &BBStates,
1403 MapVector<Value *, RRInfo> &Retains);
1404 bool VisitTopDown(BasicBlock *BB,
1405 DenseMap<const BasicBlock *, BBState> &BBStates,
1406 DenseMap<Value *, RRInfo> &Releases);
1407 bool Visit(Function &F,
1408 DenseMap<const BasicBlock *, BBState> &BBStates,
1409 MapVector<Value *, RRInfo> &Retains,
1410 DenseMap<Value *, RRInfo> &Releases);
1412 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1413 MapVector<Value *, RRInfo> &Retains,
1414 DenseMap<Value *, RRInfo> &Releases,
1415 SmallVectorImpl<Instruction *> &DeadInsts);
1417 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1418 MapVector<Value *, RRInfo> &Retains,
1419 DenseMap<Value *, RRInfo> &Releases);
1421 void OptimizeWeakCalls(Function &F);
1423 bool OptimizeSequences(Function &F);
1425 void OptimizeReturns(Function &F);
1427 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1428 virtual bool doInitialization(Module &M);
1429 virtual bool runOnFunction(Function &F);
1430 virtual void releaseMemory();
1434 ObjCARCOpt() : FunctionPass(ID) {
1435 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1440 char ObjCARCOpt::ID = 0;
1441 INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1442 "objc-arc", "ObjC ARC optimization", false, false)
1443 INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1444 INITIALIZE_PASS_END(ObjCARCOpt,
1445 "objc-arc", "ObjC ARC optimization", false, false)
1447 Pass *llvm::createObjCARCOptPass() {
1448 return new ObjCARCOpt();
1451 void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1452 AU.addRequired<ObjCARCAliasAnalysis>();
1453 AU.addRequired<AliasAnalysis>();
1454 // ARC optimization doesn't currently split critical edges.
1455 AU.setPreservesCFG();
1458 Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1459 if (!RetainRVCallee) {
1460 LLVMContext &C = M->getContext();
1461 const Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1462 std::vector<const Type *> Params;
1463 Params.push_back(I8X);
1464 const FunctionType *FTy =
1465 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1466 AttrListPtr Attributes;
1467 Attributes.addAttr(~0u, Attribute::NoUnwind);
1469 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1472 return RetainRVCallee;
1475 Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1476 if (!AutoreleaseRVCallee) {
1477 LLVMContext &C = M->getContext();
1478 const Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1479 std::vector<const Type *> Params;
1480 Params.push_back(I8X);
1481 const FunctionType *FTy =
1482 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1483 AttrListPtr Attributes;
1484 Attributes.addAttr(~0u, Attribute::NoUnwind);
1485 AutoreleaseRVCallee =
1486 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1489 return AutoreleaseRVCallee;
1492 Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1493 if (!ReleaseCallee) {
1494 LLVMContext &C = M->getContext();
1495 std::vector<const Type *> Params;
1496 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1497 AttrListPtr Attributes;
1498 Attributes.addAttr(~0u, Attribute::NoUnwind);
1500 M->getOrInsertFunction(
1502 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1505 return ReleaseCallee;
1508 Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1509 if (!RetainCallee) {
1510 LLVMContext &C = M->getContext();
1511 std::vector<const Type *> Params;
1512 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1513 AttrListPtr Attributes;
1514 Attributes.addAttr(~0u, Attribute::NoUnwind);
1516 M->getOrInsertFunction(
1518 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1521 return RetainCallee;
1524 Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1525 if (!AutoreleaseCallee) {
1526 LLVMContext &C = M->getContext();
1527 std::vector<const Type *> Params;
1528 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1529 AttrListPtr Attributes;
1530 Attributes.addAttr(~0u, Attribute::NoUnwind);
1532 M->getOrInsertFunction(
1534 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1537 return AutoreleaseCallee;
1540 /// CanAlterRefCount - Test whether the given instruction can result in a
1541 /// reference count modification (positive or negative) for the pointer's
1544 CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1545 ProvenanceAnalysis &PA, InstructionClass Class) {
1547 case IC_Autorelease:
1548 case IC_AutoreleaseRV:
1550 // These operations never directly modify a reference count.
1555 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1556 assert(CS && "Only calls can alter reference counts!");
1558 // See if AliasAnalysis can help us with the call.
1559 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1560 if (AliasAnalysis::onlyReadsMemory(MRB))
1562 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1563 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1565 const Value *Op = *I;
1566 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1572 // Assume the worst.
1576 /// CanUse - Test whether the given instruction can "use" the given pointer's
1577 /// object in a way that requires the reference count to be positive.
1579 CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1580 InstructionClass Class) {
1581 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1582 if (Class == IC_Call)
1585 // Consider various instructions which may have pointer arguments which are
1587 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1588 // Comparing a pointer with null, or any other constant, isn't really a use,
1589 // because we don't care what the pointer points to, or about the values
1590 // of any other dynamic reference-counted pointers.
1591 if (!IsPotentialUse(ICI->getOperand(1)))
1593 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1594 // For calls, just check the arguments (and not the callee operand).
1595 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1596 OE = CS.arg_end(); OI != OE; ++OI) {
1597 const Value *Op = *OI;
1598 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1602 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1603 // Special-case stores, because we don't care about the stored value, just
1604 // the store address.
1605 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1606 // If we can't tell what the underlying object was, assume there is a
1608 return IsPotentialUse(Op) && PA.related(Op, Ptr);
1611 // Check each operand for a match.
1612 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1614 const Value *Op = *OI;
1615 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1621 /// CanInterruptRV - Test whether the given instruction can autorelease
1622 /// any pointer or cause an autoreleasepool pop.
1624 CanInterruptRV(InstructionClass Class) {
1626 case IC_AutoreleasepoolPop:
1629 case IC_Autorelease:
1630 case IC_AutoreleaseRV:
1631 case IC_FusedRetainAutorelease:
1632 case IC_FusedRetainAutoreleaseRV:
1640 /// DependenceKind - There are several kinds of dependence-like concepts in
1642 enum DependenceKind {
1643 NeedsPositiveRetainCount,
1644 CanChangeRetainCount,
1645 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1646 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1647 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1651 /// Depends - Test if there can be dependencies on Inst through Arg. This
1652 /// function only tests dependencies relevant for removing pairs of calls.
1654 Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1655 ProvenanceAnalysis &PA) {
1656 // If we've reached the definition of Arg, stop.
1661 case NeedsPositiveRetainCount: {
1662 InstructionClass Class = GetInstructionClass(Inst);
1664 case IC_AutoreleasepoolPop:
1665 case IC_AutoreleasepoolPush:
1669 return CanUse(Inst, Arg, PA, Class);
1673 case CanChangeRetainCount: {
1674 InstructionClass Class = GetInstructionClass(Inst);
1676 case IC_AutoreleasepoolPop:
1677 // Conservatively assume this can decrement any count.
1679 case IC_AutoreleasepoolPush:
1683 return CanAlterRefCount(Inst, Arg, PA, Class);
1687 case RetainAutoreleaseDep:
1688 switch (GetBasicInstructionClass(Inst)) {
1689 case IC_AutoreleasepoolPop:
1690 // Don't merge an objc_autorelease with an objc_retain inside a different
1691 // autoreleasepool scope.
1695 // Check for a retain of the same pointer for merging.
1696 return GetObjCArg(Inst) == Arg;
1698 // Nothing else matters for objc_retainAutorelease formation.
1703 case RetainAutoreleaseRVDep: {
1704 InstructionClass Class = GetBasicInstructionClass(Inst);
1708 // Check for a retain of the same pointer for merging.
1709 return GetObjCArg(Inst) == Arg;
1711 // Anything that can autorelease interrupts
1712 // retainAutoreleaseReturnValue formation.
1713 return CanInterruptRV(Class);
1719 return CanInterruptRV(GetBasicInstructionClass(Inst));
1722 llvm_unreachable("Invalid dependence flavor");
1726 /// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
1727 /// find local and non-local dependencies on Arg.
1728 /// TODO: Cache results?
1730 FindDependencies(DependenceKind Flavor,
1732 BasicBlock *StartBB, Instruction *StartInst,
1733 SmallPtrSet<Instruction *, 4> &DependingInstructions,
1734 SmallPtrSet<const BasicBlock *, 4> &Visited,
1735 ProvenanceAnalysis &PA) {
1736 BasicBlock::iterator StartPos = StartInst;
1738 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
1739 Worklist.push_back(std::make_pair(StartBB, StartPos));
1741 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
1742 Worklist.pop_back_val();
1743 BasicBlock *LocalStartBB = Pair.first;
1744 BasicBlock::iterator LocalStartPos = Pair.second;
1745 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
1747 if (LocalStartPos == StartBBBegin) {
1748 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
1750 // If we've reached the function entry, produce a null dependence.
1751 DependingInstructions.insert(0);
1753 // Add the predecessors to the worklist.
1755 BasicBlock *PredBB = *PI;
1756 if (Visited.insert(PredBB))
1757 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
1758 } while (++PI != PE);
1762 Instruction *Inst = --LocalStartPos;
1763 if (Depends(Flavor, Inst, Arg, PA)) {
1764 DependingInstructions.insert(Inst);
1768 } while (!Worklist.empty());
1770 // Determine whether the original StartBB post-dominates all of the blocks we
1771 // visited. If not, insert a sentinal indicating that most optimizations are
1773 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
1774 E = Visited.end(); I != E; ++I) {
1775 const BasicBlock *BB = *I;
1778 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
1779 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
1780 const BasicBlock *Succ = *SI;
1781 if (Succ != StartBB && !Visited.count(Succ)) {
1782 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
1789 static bool isNullOrUndef(const Value *V) {
1790 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
1793 static bool isNoopInstruction(const Instruction *I) {
1794 return isa<BitCastInst>(I) ||
1795 (isa<GetElementPtrInst>(I) &&
1796 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
1799 /// OptimizeRetainCall - Turn objc_retain into
1800 /// objc_retainAutoreleasedReturnValue if the operand is a return value.
1802 ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
1803 CallSite CS(GetObjCArg(Retain));
1804 Instruction *Call = CS.getInstruction();
1806 if (Call->getParent() != Retain->getParent()) return;
1808 // Check that the call is next to the retain.
1809 BasicBlock::iterator I = Call;
1811 while (isNoopInstruction(I)) ++I;
1815 // Turn it to an objc_retainAutoreleasedReturnValue..
1818 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
1821 /// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
1822 /// objc_retain if the operand is not a return value. Or, if it can be
1823 /// paired with an objc_autoreleaseReturnValue, delete the pair and
1826 ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
1827 // Check for the argument being from an immediately preceding call.
1828 Value *Arg = GetObjCArg(RetainRV);
1830 if (Instruction *Call = CS.getInstruction())
1831 if (Call->getParent() == RetainRV->getParent()) {
1832 BasicBlock::iterator I = Call;
1834 while (isNoopInstruction(I)) ++I;
1835 if (&*I == RetainRV)
1839 // Check for being preceded by an objc_autoreleaseReturnValue on the same
1840 // pointer. In this case, we can delete the pair.
1841 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
1843 do --I; while (I != Begin && isNoopInstruction(I));
1844 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
1845 GetObjCArg(I) == Arg) {
1848 EraseInstruction(I);
1849 EraseInstruction(RetainRV);
1854 // Turn it to a plain objc_retain.
1857 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
1861 /// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
1862 /// objc_autorelease if the result is not used as a return value.
1864 ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
1865 // Check for a return of the pointer value.
1866 const Value *Ptr = GetObjCArg(AutoreleaseRV);
1867 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
1869 const User *I = *UI;
1870 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
1876 cast<CallInst>(AutoreleaseRV)->
1877 setCalledFunction(getAutoreleaseCallee(F.getParent()));
1880 /// OptimizeIndividualCalls - Visit each call, one at a time, and make
1881 /// simplifications without doing any additional analysis.
1882 void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
1883 // Reset all the flags in preparation for recomputing them.
1884 UsedInThisFunction = 0;
1886 // Visit all objc_* calls in F.
1887 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
1888 Instruction *Inst = &*I++;
1889 InstructionClass Class = GetBasicInstructionClass(Inst);
1894 // Delete no-op casts. These function calls have special semantics, but
1895 // the semantics are entirely implemented via lowering in the front-end,
1896 // so by the time they reach the optimizer, they are just no-op calls
1897 // which return their argument.
1899 // There are gray areas here, as the ability to cast reference-counted
1900 // pointers to raw void* and back allows code to break ARC assumptions,
1901 // however these are currently considered to be unimportant.
1905 EraseInstruction(Inst);
1908 // If the pointer-to-weak-pointer is null, it's undefined behavior.
1911 case IC_LoadWeakRetained:
1913 case IC_DestroyWeak: {
1914 CallInst *CI = cast<CallInst>(Inst);
1915 if (isNullOrUndef(CI->getArgOperand(0))) {
1916 const Type *Ty = CI->getArgOperand(0)->getType();
1917 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1918 Constant::getNullValue(Ty),
1920 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
1921 CI->eraseFromParent();
1928 CallInst *CI = cast<CallInst>(Inst);
1929 if (isNullOrUndef(CI->getArgOperand(0)) ||
1930 isNullOrUndef(CI->getArgOperand(1))) {
1931 const Type *Ty = CI->getArgOperand(0)->getType();
1932 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
1933 Constant::getNullValue(Ty),
1935 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
1936 CI->eraseFromParent();
1942 OptimizeRetainCall(F, Inst);
1945 if (OptimizeRetainRVCall(F, Inst))
1948 case IC_AutoreleaseRV:
1949 OptimizeAutoreleaseRVCall(F, Inst);
1953 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
1954 if (IsAutorelease(Class) && Inst->use_empty()) {
1955 CallInst *Call = cast<CallInst>(Inst);
1956 const Value *Arg = Call->getArgOperand(0);
1957 Arg = FindSingleUseIdentifiedObject(Arg);
1962 // Create the declaration lazily.
1963 LLVMContext &C = Inst->getContext();
1965 CallInst::Create(getReleaseCallee(F.getParent()),
1966 Call->getArgOperand(0), "", Call);
1967 NewCall->setMetadata(ImpreciseReleaseMDKind,
1968 MDNode::get(C, ArrayRef<Value *>()));
1969 EraseInstruction(Call);
1975 // For functions which can never be passed stack arguments, add
1977 if (IsAlwaysTail(Class)) {
1979 cast<CallInst>(Inst)->setTailCall();
1982 // Set nounwind as needed.
1983 if (IsNoThrow(Class)) {
1985 cast<CallInst>(Inst)->setDoesNotThrow();
1988 if (!IsNoopOnNull(Class)) {
1989 UsedInThisFunction |= 1 << Class;
1993 const Value *Arg = GetObjCArg(Inst);
1995 // ARC calls with null are no-ops. Delete them.
1996 if (isNullOrUndef(Arg)) {
1999 EraseInstruction(Inst);
2003 // Keep track of which of retain, release, autorelease, and retain_block
2004 // are actually present in this function.
2005 UsedInThisFunction |= 1 << Class;
2007 // If Arg is a PHI, and one or more incoming values to the
2008 // PHI are null, and the call is control-equivalent to the PHI, and there
2009 // are no relevant side effects between the PHI and the call, the call
2010 // could be pushed up to just those paths with non-null incoming values.
2011 // For now, don't bother splitting critical edges for this.
2012 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2013 Worklist.push_back(std::make_pair(Inst, Arg));
2015 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2019 const PHINode *PN = dyn_cast<PHINode>(Arg);
2022 // Determine if the PHI has any null operands, or any incoming
2024 bool HasNull = false;
2025 bool HasCriticalEdges = false;
2026 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2028 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2029 if (isNullOrUndef(Incoming))
2031 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2032 .getNumSuccessors() != 1) {
2033 HasCriticalEdges = true;
2037 // If we have null operands and no critical edges, optimize.
2038 if (!HasCriticalEdges && HasNull) {
2039 SmallPtrSet<Instruction *, 4> DependingInstructions;
2040 SmallPtrSet<const BasicBlock *, 4> Visited;
2042 // Check that there is nothing that cares about the reference
2043 // count between the call and the phi.
2044 FindDependencies(NeedsPositiveRetainCount, Arg,
2045 Inst->getParent(), Inst,
2046 DependingInstructions, Visited, PA);
2047 if (DependingInstructions.size() == 1 &&
2048 *DependingInstructions.begin() == PN) {
2051 // Clone the call into each predecessor that has a non-null value.
2052 CallInst *CInst = cast<CallInst>(Inst);
2053 const Type *ParamTy = CInst->getArgOperand(0)->getType();
2054 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2056 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2057 if (!isNullOrUndef(Incoming)) {
2058 CallInst *Clone = cast<CallInst>(CInst->clone());
2059 Value *Op = PN->getIncomingValue(i);
2060 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2061 if (Op->getType() != ParamTy)
2062 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2063 Clone->setArgOperand(0, Op);
2064 Clone->insertBefore(InsertPos);
2065 Worklist.push_back(std::make_pair(Clone, Incoming));
2068 // Erase the original call.
2069 EraseInstruction(CInst);
2073 } while (!Worklist.empty());
2077 /// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2078 /// control flow, or other CFG structures where moving code across the edge
2079 /// would result in it being executed more.
2081 ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2082 DenseMap<const BasicBlock *, BBState> &BBStates,
2083 BBState &MyStates) const {
2084 // If any top-down local-use or possible-dec has a succ which is earlier in
2085 // the sequence, forget it.
2086 for (BBState::ptr_const_iterator I = MyStates.top_down_ptr_begin(),
2087 E = MyStates.top_down_ptr_end(); I != E; ++I)
2088 switch (I->second.GetSeq()) {
2091 const Value *Arg = I->first;
2092 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2093 bool SomeSuccHasSame = false;
2094 bool AllSuccsHaveSame = true;
2095 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI)
2096 switch (BBStates[*SI].getPtrBottomUpState(Arg).GetSeq()) {
2099 MyStates.getPtrTopDownState(Arg).ClearSequenceProgress();
2100 SomeSuccHasSame = false;
2103 SomeSuccHasSame = true;
2107 case S_MovableRelease:
2108 AllSuccsHaveSame = false;
2111 llvm_unreachable("bottom-up pointer in retain state!");
2113 // If the state at the other end of any of the successor edges
2114 // matches the current state, require all edges to match. This
2115 // guards against loops in the middle of a sequence.
2116 if (SomeSuccHasSame && !AllSuccsHaveSame)
2117 MyStates.getPtrTopDownState(Arg).ClearSequenceProgress();
2119 case S_CanRelease: {
2120 const Value *Arg = I->first;
2121 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2122 bool SomeSuccHasSame = false;
2123 bool AllSuccsHaveSame = true;
2124 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI)
2125 switch (BBStates[*SI].getPtrBottomUpState(Arg).GetSeq()) {
2127 MyStates.getPtrTopDownState(Arg).ClearSequenceProgress();
2128 SomeSuccHasSame = false;
2131 SomeSuccHasSame = true;
2135 case S_MovableRelease:
2137 AllSuccsHaveSame = false;
2140 llvm_unreachable("bottom-up pointer in retain state!");
2142 // If the state at the other end of any of the successor edges
2143 // matches the current state, require all edges to match. This
2144 // guards against loops in the middle of a sequence.
2145 if (SomeSuccHasSame && !AllSuccsHaveSame)
2146 MyStates.getPtrTopDownState(Arg).ClearSequenceProgress();
2152 ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2153 DenseMap<const BasicBlock *, BBState> &BBStates,
2154 MapVector<Value *, RRInfo> &Retains) {
2155 bool NestingDetected = false;
2156 BBState &MyStates = BBStates[BB];
2158 // Merge the states from each successor to compute the initial state
2159 // for the current block.
2160 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2161 succ_const_iterator SI(TI), SE(TI, false);
2163 MyStates.SetAsExit();
2166 const BasicBlock *Succ = *SI++;
2169 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2170 if (I == BBStates.end())
2172 MyStates.InitFromSucc(I->second);
2176 I = BBStates.find(Succ);
2177 if (I != BBStates.end())
2178 MyStates.MergeSucc(I->second);
2184 // Visit all the instructions, bottom-up.
2185 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2186 Instruction *Inst = llvm::prior(I);
2187 InstructionClass Class = GetInstructionClass(Inst);
2188 const Value *Arg = 0;
2192 Arg = GetObjCArg(Inst);
2194 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2196 // If we see two releases in a row on the same pointer. If so, make
2197 // a note, and we'll cicle back to revisit it after we've
2198 // hopefully eliminated the second release, which may allow us to
2199 // eliminate the first release too.
2200 // Theoretically we could implement removal of nested retain+release
2201 // pairs by making PtrState hold a stack of states, but this is
2202 // simple and avoids adding overhead for the non-nested case.
2203 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2204 NestingDetected = true;
2206 S.SetSeqToRelease(Inst->getMetadata(ImpreciseReleaseMDKind));
2208 S.RRI.KnownIncremented = S.IsKnownIncremented();
2209 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2210 S.RRI.Calls.insert(Inst);
2212 S.IncrementRefCount();
2215 case IC_RetainBlock:
2218 Arg = GetObjCArg(Inst);
2220 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2221 S.DecrementRefCount();
2223 switch (S.GetSeq()) {
2226 case S_MovableRelease:
2228 S.RRI.ReverseInsertPts.clear();
2231 // Don't do retain+release tracking for IC_RetainRV, because it's
2232 // better to let it remain as the first instruction after a call.
2233 if (Class != IC_RetainRV) {
2234 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2235 Retains[Inst] = S.RRI;
2237 S.ClearSequenceProgress();
2242 llvm_unreachable("bottom-up pointer in retain state!");
2246 case IC_AutoreleasepoolPop:
2247 // Conservatively, clear MyStates for all known pointers.
2248 MyStates.clearBottomUpPointers();
2250 case IC_AutoreleasepoolPush:
2252 // These are irrelevant.
2258 // Consider any other possible effects of this instruction on each
2259 // pointer being tracked.
2260 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2261 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2262 const Value *Ptr = MI->first;
2264 continue; // Handled above.
2265 PtrState &S = MI->second;
2266 Sequence Seq = S.GetSeq();
2268 // Check for possible retains and releases.
2269 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2270 // Check for a retain (we're going bottom-up here).
2271 S.DecrementRefCount();
2273 // Check for a release.
2274 if (!IsRetain(Class) && Class != IC_RetainBlock)
2277 S.SetSeq(S_CanRelease);
2281 case S_MovableRelease:
2286 llvm_unreachable("bottom-up pointer in retain state!");
2290 // Check for possible direct uses.
2293 case S_MovableRelease:
2294 if (CanUse(Inst, Ptr, PA, Class)) {
2295 S.RRI.ReverseInsertPts.clear();
2296 S.RRI.ReverseInsertPts.insert(Inst);
2298 } else if (Seq == S_Release &&
2299 (Class == IC_User || Class == IC_CallOrUser)) {
2300 // Non-movable releases depend on any possible objc pointer use.
2302 S.RRI.ReverseInsertPts.clear();
2303 S.RRI.ReverseInsertPts.insert(Inst);
2307 if (CanUse(Inst, Ptr, PA, Class))
2315 llvm_unreachable("bottom-up pointer in retain state!");
2320 return NestingDetected;
2324 ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2325 DenseMap<const BasicBlock *, BBState> &BBStates,
2326 DenseMap<Value *, RRInfo> &Releases) {
2327 bool NestingDetected = false;
2328 BBState &MyStates = BBStates[BB];
2330 // Merge the states from each predecessor to compute the initial state
2331 // for the current block.
2332 const_pred_iterator PI(BB), PE(BB, false);
2334 MyStates.SetAsEntry();
2337 const BasicBlock *Pred = *PI++;
2340 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2341 if (I == BBStates.end())
2343 MyStates.InitFromPred(I->second);
2347 I = BBStates.find(Pred);
2348 if (I != BBStates.end())
2349 MyStates.MergePred(I->second);
2355 // Visit all the instructions, top-down.
2356 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2357 Instruction *Inst = I;
2358 InstructionClass Class = GetInstructionClass(Inst);
2359 const Value *Arg = 0;
2362 case IC_RetainBlock:
2365 Arg = GetObjCArg(Inst);
2367 PtrState &S = MyStates.getPtrTopDownState(Arg);
2369 // Don't do retain+release tracking for IC_RetainRV, because it's
2370 // better to let it remain as the first instruction after a call.
2371 if (Class != IC_RetainRV) {
2372 // If we see two retains in a row on the same pointer. If so, make
2373 // a note, and we'll cicle back to revisit it after we've
2374 // hopefully eliminated the second retain, which may allow us to
2375 // eliminate the first retain too.
2376 // Theoretically we could implement removal of nested retain+release
2377 // pairs by making PtrState hold a stack of states, but this is
2378 // simple and avoids adding overhead for the non-nested case.
2379 if (S.GetSeq() == S_Retain)
2380 NestingDetected = true;
2384 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2385 S.RRI.KnownIncremented = S.IsKnownIncremented();
2386 S.RRI.Calls.insert(Inst);
2389 S.IncrementRefCount();
2393 Arg = GetObjCArg(Inst);
2395 PtrState &S = MyStates.getPtrTopDownState(Arg);
2396 S.DecrementRefCount();
2398 switch (S.GetSeq()) {
2401 S.RRI.ReverseInsertPts.clear();
2404 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2405 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2406 Releases[Inst] = S.RRI;
2407 S.ClearSequenceProgress();
2413 case S_MovableRelease:
2414 llvm_unreachable("top-down pointer in release state!");
2418 case IC_AutoreleasepoolPop:
2419 // Conservatively, clear MyStates for all known pointers.
2420 MyStates.clearTopDownPointers();
2422 case IC_AutoreleasepoolPush:
2424 // These are irrelevant.
2430 // Consider any other possible effects of this instruction on each
2431 // pointer being tracked.
2432 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2433 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2434 const Value *Ptr = MI->first;
2436 continue; // Handled above.
2437 PtrState &S = MI->second;
2438 Sequence Seq = S.GetSeq();
2440 // Check for possible releases.
2441 if (!IsRetain(Class) && Class != IC_RetainBlock &&
2442 CanAlterRefCount(Inst, Ptr, PA, Class)) {
2443 // Check for a release.
2444 S.DecrementRefCount();
2446 // Check for a release.
2449 S.SetSeq(S_CanRelease);
2450 S.RRI.ReverseInsertPts.clear();
2451 S.RRI.ReverseInsertPts.insert(Inst);
2453 // One call can't cause a transition from S_Retain to S_CanRelease
2454 // and S_CanRelease to S_Use. If we've made the first transition,
2463 case S_MovableRelease:
2464 llvm_unreachable("top-down pointer in release state!");
2468 // Check for possible direct uses.
2471 if (CanUse(Inst, Ptr, PA, Class))
2480 case S_MovableRelease:
2481 llvm_unreachable("top-down pointer in release state!");
2486 CheckForCFGHazards(BB, BBStates, MyStates);
2487 return NestingDetected;
2490 // Visit - Visit the function both top-down and bottom-up.
2492 ObjCARCOpt::Visit(Function &F,
2493 DenseMap<const BasicBlock *, BBState> &BBStates,
2494 MapVector<Value *, RRInfo> &Retains,
2495 DenseMap<Value *, RRInfo> &Releases) {
2496 // Use postorder for bottom-up, and reverse-postorder for top-down, because we
2497 // magically know that loops will be well behaved, i.e. they won't repeatedly
2498 // call retain on a single pointer without doing a release.
2499 bool BottomUpNestingDetected = false;
2500 SmallVector<BasicBlock *, 8> PostOrder;
2501 for (po_iterator<Function *> I = po_begin(&F), E = po_end(&F); I != E; ++I) {
2502 BasicBlock *BB = *I;
2503 PostOrder.push_back(BB);
2505 BottomUpNestingDetected |= VisitBottomUp(BB, BBStates, Retains);
2508 // Iterate through the post-order in reverse order, achieving a
2509 // reverse-postorder traversal. We don't use the ReversePostOrderTraversal
2510 // class here because it works by computing its own full postorder iteration,
2511 // recording the sequence, and playing it back in reverse. Since we're already
2512 // doing a full iteration above, we can just record the sequence manually and
2513 // avoid the cost of having ReversePostOrderTraversal compute it.
2514 bool TopDownNestingDetected = false;
2515 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator
2516 RI = PostOrder.rbegin(), RE = PostOrder.rend(); RI != RE; ++RI)
2517 TopDownNestingDetected |= VisitTopDown(*RI, BBStates, Releases);
2519 return TopDownNestingDetected && BottomUpNestingDetected;
2522 /// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
2523 void ObjCARCOpt::MoveCalls(Value *Arg,
2524 RRInfo &RetainsToMove,
2525 RRInfo &ReleasesToMove,
2526 MapVector<Value *, RRInfo> &Retains,
2527 DenseMap<Value *, RRInfo> &Releases,
2528 SmallVectorImpl<Instruction *> &DeadInsts) {
2529 const Type *ArgTy = Arg->getType();
2530 const Type *ParamTy =
2531 (RetainRVFunc ? RetainRVFunc :
2532 RetainFunc ? RetainFunc :
2533 RetainBlockFunc)->arg_begin()->getType();
2535 // Insert the new retain and release calls.
2536 for (SmallPtrSet<Instruction *, 2>::const_iterator
2537 PI = ReleasesToMove.ReverseInsertPts.begin(),
2538 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2539 Instruction *InsertPt = *PI;
2540 Value *MyArg = ArgTy == ParamTy ? Arg :
2541 new BitCastInst(Arg, ParamTy, "", InsertPt);
2543 CallInst::Create(RetainsToMove.IsRetainBlock ?
2544 RetainBlockFunc : RetainFunc,
2545 MyArg, "", InsertPt);
2546 Call->setDoesNotThrow();
2547 if (!RetainsToMove.IsRetainBlock)
2548 Call->setTailCall();
2550 for (SmallPtrSet<Instruction *, 2>::const_iterator
2551 PI = RetainsToMove.ReverseInsertPts.begin(),
2552 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
2553 Instruction *LastUse = *PI;
2554 Instruction *InsertPts[] = { 0, 0, 0 };
2555 if (InvokeInst *II = dyn_cast<InvokeInst>(LastUse)) {
2556 // We can't insert code immediately after an invoke instruction, so
2557 // insert code at the beginning of both successor blocks instead.
2558 // The invoke's return value isn't available in the unwind block,
2559 // but our releases will never depend on it, because they must be
2560 // paired with retains from before the invoke.
2561 InsertPts[0] = II->getNormalDest()->getFirstNonPHI();
2562 InsertPts[1] = II->getUnwindDest()->getFirstNonPHI();
2564 // Insert code immediately after the last use.
2565 InsertPts[0] = llvm::next(BasicBlock::iterator(LastUse));
2568 for (Instruction **I = InsertPts; *I; ++I) {
2569 Instruction *InsertPt = *I;
2570 Value *MyArg = ArgTy == ParamTy ? Arg :
2571 new BitCastInst(Arg, ParamTy, "", InsertPt);
2572 CallInst *Call = CallInst::Create(ReleaseFunc, MyArg, "", InsertPt);
2573 // Attach a clang.imprecise_release metadata tag, if appropriate.
2574 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
2575 Call->setMetadata(ImpreciseReleaseMDKind, M);
2576 Call->setDoesNotThrow();
2577 if (ReleasesToMove.IsTailCallRelease)
2578 Call->setTailCall();
2582 // Delete the original retain and release calls.
2583 for (SmallPtrSet<Instruction *, 2>::const_iterator
2584 AI = RetainsToMove.Calls.begin(),
2585 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
2586 Instruction *OrigRetain = *AI;
2587 Retains.blot(OrigRetain);
2588 DeadInsts.push_back(OrigRetain);
2590 for (SmallPtrSet<Instruction *, 2>::const_iterator
2591 AI = ReleasesToMove.Calls.begin(),
2592 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
2593 Instruction *OrigRelease = *AI;
2594 Releases.erase(OrigRelease);
2595 DeadInsts.push_back(OrigRelease);
2600 ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
2602 MapVector<Value *, RRInfo> &Retains,
2603 DenseMap<Value *, RRInfo> &Releases) {
2604 bool AnyPairsCompletelyEliminated = false;
2605 RRInfo RetainsToMove;
2606 RRInfo ReleasesToMove;
2607 SmallVector<Instruction *, 4> NewRetains;
2608 SmallVector<Instruction *, 4> NewReleases;
2609 SmallVector<Instruction *, 8> DeadInsts;
2611 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
2612 E = Retains.end(); I != E; ) {
2613 Value *V = (I++)->first;
2614 if (!V) continue; // blotted
2616 Instruction *Retain = cast<Instruction>(V);
2617 Value *Arg = GetObjCArg(Retain);
2619 // If the object being released is in static or stack storage, we know it's
2620 // not being managed by ObjC reference counting, so we can delete pairs
2621 // regardless of what possible decrements or uses lie between them.
2622 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
2624 // If a pair happens in a region where it is known that the reference count
2625 // is already incremented, we can similarly ignore possible decrements.
2626 bool KnownIncrementedTD = true, KnownIncrementedBU = true;
2628 // Connect the dots between the top-down-collected RetainsToMove and
2629 // bottom-up-collected ReleasesToMove to form sets of related calls.
2630 // This is an iterative process so that we connect multiple releases
2631 // to multiple retains if needed.
2632 unsigned OldDelta = 0;
2633 unsigned NewDelta = 0;
2634 unsigned OldCount = 0;
2635 unsigned NewCount = 0;
2636 bool FirstRelease = true;
2637 bool FirstRetain = true;
2638 NewRetains.push_back(Retain);
2640 for (SmallVectorImpl<Instruction *>::const_iterator
2641 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
2642 Instruction *NewRetain = *NI;
2643 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
2644 assert(It != Retains.end());
2645 const RRInfo &NewRetainRRI = It->second;
2646 KnownIncrementedTD &= NewRetainRRI.KnownIncremented;
2647 for (SmallPtrSet<Instruction *, 2>::const_iterator
2648 LI = NewRetainRRI.Calls.begin(),
2649 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
2650 Instruction *NewRetainRelease = *LI;
2651 DenseMap<Value *, RRInfo>::const_iterator Jt =
2652 Releases.find(NewRetainRelease);
2653 if (Jt == Releases.end())
2655 const RRInfo &NewRetainReleaseRRI = Jt->second;
2656 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
2657 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
2659 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
2661 // Merge the ReleaseMetadata and IsTailCallRelease values.
2663 ReleasesToMove.ReleaseMetadata =
2664 NewRetainReleaseRRI.ReleaseMetadata;
2665 ReleasesToMove.IsTailCallRelease =
2666 NewRetainReleaseRRI.IsTailCallRelease;
2667 FirstRelease = false;
2669 if (ReleasesToMove.ReleaseMetadata !=
2670 NewRetainReleaseRRI.ReleaseMetadata)
2671 ReleasesToMove.ReleaseMetadata = 0;
2672 if (ReleasesToMove.IsTailCallRelease !=
2673 NewRetainReleaseRRI.IsTailCallRelease)
2674 ReleasesToMove.IsTailCallRelease = false;
2677 // Collect the optimal insertion points.
2679 for (SmallPtrSet<Instruction *, 2>::const_iterator
2680 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
2681 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
2683 Instruction *RIP = *RI;
2684 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
2685 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
2687 NewReleases.push_back(NewRetainRelease);
2692 if (NewReleases.empty()) break;
2694 // Back the other way.
2695 for (SmallVectorImpl<Instruction *>::const_iterator
2696 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
2697 Instruction *NewRelease = *NI;
2698 DenseMap<Value *, RRInfo>::const_iterator It =
2699 Releases.find(NewRelease);
2700 assert(It != Releases.end());
2701 const RRInfo &NewReleaseRRI = It->second;
2702 KnownIncrementedBU &= NewReleaseRRI.KnownIncremented;
2703 for (SmallPtrSet<Instruction *, 2>::const_iterator
2704 LI = NewReleaseRRI.Calls.begin(),
2705 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
2706 Instruction *NewReleaseRetain = *LI;
2707 MapVector<Value *, RRInfo>::const_iterator Jt =
2708 Retains.find(NewReleaseRetain);
2709 if (Jt == Retains.end())
2711 const RRInfo &NewReleaseRetainRRI = Jt->second;
2712 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
2713 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
2714 unsigned PathCount =
2715 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
2716 OldDelta += PathCount;
2717 OldCount += PathCount;
2719 // Merge the IsRetainBlock values.
2721 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
2722 FirstRetain = false;
2723 } else if (ReleasesToMove.IsRetainBlock !=
2724 NewReleaseRetainRRI.IsRetainBlock)
2725 // It's not possible to merge the sequences if one uses
2726 // objc_retain and the other uses objc_retainBlock.
2729 // Collect the optimal insertion points.
2731 for (SmallPtrSet<Instruction *, 2>::const_iterator
2732 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
2733 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
2735 Instruction *RIP = *RI;
2736 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
2737 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
2738 NewDelta += PathCount;
2739 NewCount += PathCount;
2742 NewRetains.push_back(NewReleaseRetain);
2746 NewReleases.clear();
2747 if (NewRetains.empty()) break;
2750 // If the pointer is known incremented, we can safely delete the pair
2751 // regardless of what's between them.
2752 if (KnownIncrementedTD || KnownIncrementedBU) {
2753 RetainsToMove.ReverseInsertPts.clear();
2754 ReleasesToMove.ReverseInsertPts.clear();
2758 // Determine whether the original call points are balanced in the retain and
2759 // release calls through the program. If not, conservatively don't touch
2761 // TODO: It's theoretically possible to do code motion in this case, as
2762 // long as the existing imbalances are maintained.
2766 // Determine whether the new insertion points we computed preserve the
2767 // balance of retain and release calls through the program.
2768 // TODO: If the fully aggressive solution isn't valid, try to find a
2769 // less aggressive solution which is.
2773 // Ok, everything checks out and we're all set. Let's move some code!
2775 AnyPairsCompletelyEliminated = NewCount == 0;
2776 NumRRs += OldCount - NewCount;
2777 MoveCalls(Arg, RetainsToMove, ReleasesToMove, Retains, Releases, DeadInsts);
2780 NewReleases.clear();
2782 RetainsToMove.clear();
2783 ReleasesToMove.clear();
2786 // Now that we're done moving everything, we can delete the newly dead
2787 // instructions, as we no longer need them as insert points.
2788 while (!DeadInsts.empty())
2789 EraseInstruction(DeadInsts.pop_back_val());
2791 return AnyPairsCompletelyEliminated;
2794 /// OptimizeWeakCalls - Weak pointer optimizations.
2795 void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
2796 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
2797 // itself because it uses AliasAnalysis and we need to do provenance
2799 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2800 Instruction *Inst = &*I++;
2801 InstructionClass Class = GetBasicInstructionClass(Inst);
2802 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
2805 // Delete objc_loadWeak calls with no users.
2806 if (Class == IC_LoadWeak && Inst->use_empty()) {
2807 Inst->eraseFromParent();
2811 // TODO: For now, just look for an earlier available version of this value
2812 // within the same block. Theoretically, we could do memdep-style non-local
2813 // analysis too, but that would want caching. A better approach would be to
2814 // use the technique that EarlyCSE uses.
2815 inst_iterator Current = llvm::prior(I);
2816 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
2817 for (BasicBlock::iterator B = CurrentBB->begin(),
2818 J = Current.getInstructionIterator();
2820 Instruction *EarlierInst = &*llvm::prior(J);
2821 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
2822 switch (EarlierClass) {
2824 case IC_LoadWeakRetained: {
2825 // If this is loading from the same pointer, replace this load's value
2827 CallInst *Call = cast<CallInst>(Inst);
2828 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2829 Value *Arg = Call->getArgOperand(0);
2830 Value *EarlierArg = EarlierCall->getArgOperand(0);
2831 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2832 case AliasAnalysis::MustAlias:
2834 // If the load has a builtin retain, insert a plain retain for it.
2835 if (Class == IC_LoadWeakRetained) {
2837 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2841 // Zap the fully redundant load.
2842 Call->replaceAllUsesWith(EarlierCall);
2843 Call->eraseFromParent();
2845 case AliasAnalysis::MayAlias:
2846 case AliasAnalysis::PartialAlias:
2848 case AliasAnalysis::NoAlias:
2855 // If this is storing to the same pointer and has the same size etc.
2856 // replace this load's value with the stored value.
2857 CallInst *Call = cast<CallInst>(Inst);
2858 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
2859 Value *Arg = Call->getArgOperand(0);
2860 Value *EarlierArg = EarlierCall->getArgOperand(0);
2861 switch (PA.getAA()->alias(Arg, EarlierArg)) {
2862 case AliasAnalysis::MustAlias:
2864 // If the load has a builtin retain, insert a plain retain for it.
2865 if (Class == IC_LoadWeakRetained) {
2867 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
2871 // Zap the fully redundant load.
2872 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
2873 Call->eraseFromParent();
2875 case AliasAnalysis::MayAlias:
2876 case AliasAnalysis::PartialAlias:
2878 case AliasAnalysis::NoAlias:
2885 // TOOD: Grab the copied value.
2887 case IC_AutoreleasepoolPush:
2890 // Weak pointers are only modified through the weak entry points
2891 // (and arbitrary calls, which could call the weak entry points).
2894 // Anything else could modify the weak pointer.
2901 // Then, for each destroyWeak with an alloca operand, check to see if
2902 // the alloca and all its users can be zapped.
2903 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2904 Instruction *Inst = &*I++;
2905 InstructionClass Class = GetBasicInstructionClass(Inst);
2906 if (Class != IC_DestroyWeak)
2909 CallInst *Call = cast<CallInst>(Inst);
2910 Value *Arg = Call->getArgOperand(0);
2911 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
2912 for (Value::use_iterator UI = Alloca->use_begin(),
2913 UE = Alloca->use_end(); UI != UE; ++UI) {
2914 Instruction *UserInst = cast<Instruction>(*UI);
2915 switch (GetBasicInstructionClass(UserInst)) {
2918 case IC_DestroyWeak:
2925 for (Value::use_iterator UI = Alloca->use_begin(),
2926 UE = Alloca->use_end(); UI != UE; ) {
2927 CallInst *UserInst = cast<CallInst>(*UI++);
2928 if (!UserInst->use_empty())
2929 UserInst->replaceAllUsesWith(UserInst->getOperand(1));
2930 UserInst->eraseFromParent();
2932 Alloca->eraseFromParent();
2938 /// OptimizeSequences - Identify program paths which execute sequences of
2939 /// retains and releases which can be eliminated.
2940 bool ObjCARCOpt::OptimizeSequences(Function &F) {
2941 /// Releases, Retains - These are used to store the results of the main flow
2942 /// analysis. These use Value* as the key instead of Instruction* so that the
2943 /// map stays valid when we get around to rewriting code and calls get
2944 /// replaced by arguments.
2945 DenseMap<Value *, RRInfo> Releases;
2946 MapVector<Value *, RRInfo> Retains;
2948 /// BBStates, This is used during the traversal of the function to track the
2949 /// states for each identified object at each block.
2950 DenseMap<const BasicBlock *, BBState> BBStates;
2952 // Analyze the CFG of the function, and all instructions.
2953 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
2956 return PerformCodePlacement(BBStates, Retains, Releases) && NestingDetected;
2959 /// OptimizeReturns - Look for this pattern:
2961 /// %call = call i8* @something(...)
2962 /// %2 = call i8* @objc_retain(i8* %call)
2963 /// %3 = call i8* @objc_autorelease(i8* %2)
2966 /// And delete the retain and autorelease.
2968 /// Otherwise if it's just this:
2970 /// %3 = call i8* @objc_autorelease(i8* %2)
2973 /// convert the autorelease to autoreleaseRV.
2974 void ObjCARCOpt::OptimizeReturns(Function &F) {
2975 if (!F.getReturnType()->isPointerTy())
2978 SmallPtrSet<Instruction *, 4> DependingInstructions;
2979 SmallPtrSet<const BasicBlock *, 4> Visited;
2980 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
2981 BasicBlock *BB = FI;
2982 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
2985 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
2986 FindDependencies(NeedsPositiveRetainCount, Arg,
2987 BB, Ret, DependingInstructions, Visited, PA);
2988 if (DependingInstructions.size() != 1)
2992 CallInst *Autorelease =
2993 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
2996 InstructionClass AutoreleaseClass =
2997 GetBasicInstructionClass(Autorelease);
2998 if (!IsAutorelease(AutoreleaseClass))
3000 if (GetObjCArg(Autorelease) != Arg)
3003 DependingInstructions.clear();
3006 // Check that there is nothing that can affect the reference
3007 // count between the autorelease and the retain.
3008 FindDependencies(CanChangeRetainCount, Arg,
3009 BB, Autorelease, DependingInstructions, Visited, PA);
3010 if (DependingInstructions.size() != 1)
3015 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3017 // Check that we found a retain with the same argument.
3019 !IsRetain(GetBasicInstructionClass(Retain)) ||
3020 GetObjCArg(Retain) != Arg)
3023 DependingInstructions.clear();
3026 // Convert the autorelease to an autoreleaseRV, since it's
3027 // returning the value.
3028 if (AutoreleaseClass == IC_Autorelease) {
3029 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3030 AutoreleaseClass = IC_AutoreleaseRV;
3033 // Check that there is nothing that can affect the reference
3034 // count between the retain and the call.
3035 FindDependencies(CanChangeRetainCount, Arg, BB, Retain,
3036 DependingInstructions, Visited, PA);
3037 if (DependingInstructions.size() != 1)
3042 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3044 // Check that the pointer is the return value of the call.
3045 if (!Call || Arg != Call)
3048 // Check that the call is a regular call.
3049 InstructionClass Class = GetBasicInstructionClass(Call);
3050 if (Class != IC_CallOrUser && Class != IC_Call)
3053 // If so, we can zap the retain and autorelease.
3056 EraseInstruction(Retain);
3057 EraseInstruction(Autorelease);
3063 DependingInstructions.clear();
3068 bool ObjCARCOpt::doInitialization(Module &M) {
3072 // Identify the imprecise release metadata kind.
3073 ImpreciseReleaseMDKind =
3074 M.getContext().getMDKindID("clang.imprecise_release");
3076 // Identify the declarations for objc_retain and friends.
3077 RetainFunc = M.getFunction("objc_retain");
3078 RetainBlockFunc = M.getFunction("objc_retainBlock");
3079 RetainRVFunc = M.getFunction("objc_retainAutoreleasedReturnValue");
3080 ReleaseFunc = M.getFunction("objc_release");
3081 AutoreleaseFunc = M.getFunction("objc_autorelease");
3083 // Intuitively, objc_retain and others are nocapture, however in practice
3084 // they are not, because they return their argument value. And objc_release
3085 // calls finalizers.
3087 // These are initialized lazily.
3089 AutoreleaseRVCallee = 0;
3092 AutoreleaseCallee = 0;
3097 bool ObjCARCOpt::runOnFunction(Function &F) {
3103 PA.setAA(&getAnalysis<AliasAnalysis>());
3105 // This pass performs several distinct transformations. As a compile-time aid
3106 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3107 // library functions aren't declared.
3109 // Preliminary optimizations. This also computs UsedInThisFunction.
3110 OptimizeIndividualCalls(F);
3112 // Optimizations for weak pointers.
3113 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3114 (1 << IC_LoadWeakRetained) |
3115 (1 << IC_StoreWeak) |
3116 (1 << IC_InitWeak) |
3117 (1 << IC_CopyWeak) |
3118 (1 << IC_MoveWeak) |
3119 (1 << IC_DestroyWeak)))
3120 OptimizeWeakCalls(F);
3122 // Optimizations for retain+release pairs.
3123 if (UsedInThisFunction & ((1 << IC_Retain) |
3124 (1 << IC_RetainRV) |
3125 (1 << IC_RetainBlock)))
3126 if (UsedInThisFunction & (1 << IC_Release))
3127 // Run OptimizeSequences until it either stops making changes or
3128 // no retain+release pair nesting is detected.
3129 while (OptimizeSequences(F)) {}
3131 // Optimizations if objc_autorelease is used.
3132 if (UsedInThisFunction &
3133 ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
3139 void ObjCARCOpt::releaseMemory() {
3143 //===----------------------------------------------------------------------===//
3145 //===----------------------------------------------------------------------===//
3147 // TODO: ObjCARCContract could insert PHI nodes when uses aren't
3148 // dominated by single calls.
3150 #include "llvm/Operator.h"
3151 #include "llvm/InlineAsm.h"
3152 #include "llvm/Analysis/Dominators.h"
3154 STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3157 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3158 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3159 class ObjCARCContract : public FunctionPass {
3163 ProvenanceAnalysis PA;
3165 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3166 /// functions, for use in creating calls to them. These are initialized
3167 /// lazily to avoid cluttering up the Module with unused declarations.
3168 Constant *StoreStrongCallee,
3169 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3171 /// RetainRVMarker - The inline asm string to insert between calls and
3172 /// RetainRV calls to make the optimization work on targets which need it.
3173 const MDString *RetainRVMarker;
3175 Constant *getStoreStrongCallee(Module *M);
3176 Constant *getRetainAutoreleaseCallee(Module *M);
3177 Constant *getRetainAutoreleaseRVCallee(Module *M);
3179 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3180 InstructionClass Class,
3181 SmallPtrSet<Instruction *, 4>
3182 &DependingInstructions,
3183 SmallPtrSet<const BasicBlock *, 4>
3186 void ContractRelease(Instruction *Release,
3187 inst_iterator &Iter);
3189 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3190 virtual bool doInitialization(Module &M);
3191 virtual bool runOnFunction(Function &F);
3195 ObjCARCContract() : FunctionPass(ID) {
3196 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3201 char ObjCARCContract::ID = 0;
3202 INITIALIZE_PASS_BEGIN(ObjCARCContract,
3203 "objc-arc-contract", "ObjC ARC contraction", false, false)
3204 INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3205 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3206 INITIALIZE_PASS_END(ObjCARCContract,
3207 "objc-arc-contract", "ObjC ARC contraction", false, false)
3209 Pass *llvm::createObjCARCContractPass() {
3210 return new ObjCARCContract();
3213 void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3214 AU.addRequired<AliasAnalysis>();
3215 AU.addRequired<DominatorTree>();
3216 AU.setPreservesCFG();
3219 Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3220 if (!StoreStrongCallee) {
3221 LLVMContext &C = M->getContext();
3222 const Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3223 const Type *I8XX = PointerType::getUnqual(I8X);
3224 std::vector<const Type *> Params;
3225 Params.push_back(I8XX);
3226 Params.push_back(I8X);
3228 AttrListPtr Attributes;
3229 Attributes.addAttr(~0u, Attribute::NoUnwind);
3230 Attributes.addAttr(1, Attribute::NoCapture);
3233 M->getOrInsertFunction(
3235 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3238 return StoreStrongCallee;
3241 Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3242 if (!RetainAutoreleaseCallee) {
3243 LLVMContext &C = M->getContext();
3244 const Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3245 std::vector<const Type *> Params;
3246 Params.push_back(I8X);
3247 const FunctionType *FTy =
3248 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3249 AttrListPtr Attributes;
3250 Attributes.addAttr(~0u, Attribute::NoUnwind);
3251 RetainAutoreleaseCallee =
3252 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3254 return RetainAutoreleaseCallee;
3257 Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3258 if (!RetainAutoreleaseRVCallee) {
3259 LLVMContext &C = M->getContext();
3260 const Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3261 std::vector<const Type *> Params;
3262 Params.push_back(I8X);
3263 const FunctionType *FTy =
3264 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3265 AttrListPtr Attributes;
3266 Attributes.addAttr(~0u, Attribute::NoUnwind);
3267 RetainAutoreleaseRVCallee =
3268 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3271 return RetainAutoreleaseRVCallee;
3274 /// ContractAutorelease - Merge an autorelease with a retain into a fused
3277 ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3278 InstructionClass Class,
3279 SmallPtrSet<Instruction *, 4>
3280 &DependingInstructions,
3281 SmallPtrSet<const BasicBlock *, 4>
3283 const Value *Arg = GetObjCArg(Autorelease);
3285 // Check that there are no instructions between the retain and the autorelease
3286 // (such as an autorelease_pop) which may change the count.
3287 CallInst *Retain = 0;
3288 if (Class == IC_AutoreleaseRV)
3289 FindDependencies(RetainAutoreleaseRVDep, Arg,
3290 Autorelease->getParent(), Autorelease,
3291 DependingInstructions, Visited, PA);
3293 FindDependencies(RetainAutoreleaseDep, Arg,
3294 Autorelease->getParent(), Autorelease,
3295 DependingInstructions, Visited, PA);
3298 if (DependingInstructions.size() != 1) {
3299 DependingInstructions.clear();
3303 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3304 DependingInstructions.clear();
3307 GetBasicInstructionClass(Retain) != IC_Retain ||
3308 GetObjCArg(Retain) != Arg)
3314 if (Class == IC_AutoreleaseRV)
3315 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3317 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3319 EraseInstruction(Autorelease);
3323 /// ContractRelease - Attempt to merge an objc_release with a store, load, and
3324 /// objc_retain to form an objc_storeStrong. This can be a little tricky because
3325 /// the instructions don't always appear in order, and there may be unrelated
3326 /// intervening instructions.
3327 void ObjCARCContract::ContractRelease(Instruction *Release,
3328 inst_iterator &Iter) {
3329 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
3330 if (!Load || Load->isVolatile()) return;
3332 // For now, require everything to be in one basic block.
3333 BasicBlock *BB = Release->getParent();
3334 if (Load->getParent() != BB) return;
3336 // Walk down to find the store.
3337 BasicBlock::iterator I = Load, End = BB->end();
3339 AliasAnalysis::Location Loc = AA->getLocation(Load);
3342 IsRetain(GetBasicInstructionClass(I)) ||
3343 !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
3345 StoreInst *Store = dyn_cast<StoreInst>(I);
3346 if (!Store || Store->isVolatile()) return;
3347 if (Store->getPointerOperand() != Loc.Ptr) return;
3349 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3351 // Walk up to find the retain.
3353 BasicBlock::iterator Begin = BB->begin();
3354 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3356 Instruction *Retain = I;
3357 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3358 if (GetObjCArg(Retain) != New) return;
3363 LLVMContext &C = Release->getContext();
3364 const Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3365 const Type *I8XX = PointerType::getUnqual(I8X);
3367 Value *Args[] = { Load->getPointerOperand(), New };
3368 if (Args[0]->getType() != I8XX)
3369 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3370 if (Args[1]->getType() != I8X)
3371 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3372 CallInst *StoreStrong =
3373 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
3374 Args, array_endof(Args), "", Store);
3375 StoreStrong->setDoesNotThrow();
3376 StoreStrong->setDebugLoc(Store->getDebugLoc());
3378 if (&*Iter == Store) ++Iter;
3379 Store->eraseFromParent();
3380 Release->eraseFromParent();
3381 EraseInstruction(Retain);
3382 if (Load->use_empty())
3383 Load->eraseFromParent();
3386 bool ObjCARCContract::doInitialization(Module &M) {
3387 // These are initialized lazily.
3388 StoreStrongCallee = 0;
3389 RetainAutoreleaseCallee = 0;
3390 RetainAutoreleaseRVCallee = 0;
3392 // Initialize RetainRVMarker.
3394 if (NamedMDNode *NMD =
3395 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3396 if (NMD->getNumOperands() == 1) {
3397 const MDNode *N = NMD->getOperand(0);
3398 if (N->getNumOperands() == 1)
3399 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
3406 bool ObjCARCContract::runOnFunction(Function &F) {
3411 AA = &getAnalysis<AliasAnalysis>();
3412 DT = &getAnalysis<DominatorTree>();
3414 PA.setAA(&getAnalysis<AliasAnalysis>());
3416 // For ObjC library calls which return their argument, replace uses of the
3417 // argument with uses of the call return value, if it dominates the use. This
3418 // reduces register pressure.
3419 SmallPtrSet<Instruction *, 4> DependingInstructions;
3420 SmallPtrSet<const BasicBlock *, 4> Visited;
3421 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3422 Instruction *Inst = &*I++;
3424 // Only these library routines return their argument. In particular,
3425 // objc_retainBlock does not necessarily return its argument.
3426 InstructionClass Class = GetBasicInstructionClass(Inst);
3429 case IC_FusedRetainAutorelease:
3430 case IC_FusedRetainAutoreleaseRV:
3432 case IC_Autorelease:
3433 case IC_AutoreleaseRV:
3434 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
3438 // If we're compiling for a target which needs a special inline-asm
3439 // marker to do the retainAutoreleasedReturnValue optimization,
3441 if (!RetainRVMarker)
3443 BasicBlock::iterator BBI = Inst;
3445 while (isNoopInstruction(BBI)) --BBI;
3446 if (&*BBI == GetObjCArg(Inst)) {
3448 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
3449 /*isVarArg=*/false),
3450 RetainRVMarker->getString(),
3451 /*Constraints=*/"", /*hasSideEffects=*/true);
3452 CallInst::Create(IA, "", Inst);
3457 // objc_initWeak(p, null) => *p = null
3458 CallInst *CI = cast<CallInst>(Inst);
3459 if (isNullOrUndef(CI->getArgOperand(1))) {
3461 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
3463 new StoreInst(Null, CI->getArgOperand(0), CI);
3464 CI->replaceAllUsesWith(Null);
3465 CI->eraseFromParent();
3470 ContractRelease(Inst, I);
3476 // Don't use GetObjCArg because we don't want to look through bitcasts
3477 // and such; to do the replacement, the argument must have type i8*.
3478 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
3480 // If we're compiling bugpointed code, don't get in trouble.
3481 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
3483 // Look through the uses of the pointer.
3484 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
3486 Use &U = UI.getUse();
3487 unsigned OperandNo = UI.getOperandNo();
3488 ++UI; // Increment UI now, because we may unlink its element.
3489 if (Instruction *UserInst = dyn_cast<Instruction>(U.getUser()))
3490 if (Inst != UserInst && DT->dominates(Inst, UserInst)) {
3492 Instruction *Replacement = Inst;
3493 const Type *UseTy = U.get()->getType();
3494 if (PHINode *PHI = dyn_cast<PHINode>(UserInst)) {
3495 // For PHI nodes, insert the bitcast in the predecessor block.
3497 PHINode::getIncomingValueNumForOperand(OperandNo);
3499 PHI->getIncomingBlock(ValNo);
3500 if (Replacement->getType() != UseTy)
3501 Replacement = new BitCastInst(Replacement, UseTy, "",
3503 for (unsigned i = 0, e = PHI->getNumIncomingValues();
3505 if (PHI->getIncomingBlock(i) == BB) {
3506 // Keep the UI iterator valid.
3507 if (&PHI->getOperandUse(
3508 PHINode::getOperandNumForIncomingValue(i)) ==
3511 PHI->setIncomingValue(i, Replacement);
3514 if (Replacement->getType() != UseTy)
3515 Replacement = new BitCastInst(Replacement, UseTy, "", UserInst);
3521 // If Arg is a no-op casted pointer, strip one level of casts and
3523 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
3524 Arg = BI->getOperand(0);
3525 else if (isa<GEPOperator>(Arg) &&
3526 cast<GEPOperator>(Arg)->hasAllZeroIndices())
3527 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
3528 else if (isa<GlobalAlias>(Arg) &&
3529 !cast<GlobalAlias>(Arg)->mayBeOverridden())
3530 Arg = cast<GlobalAlias>(Arg)->getAliasee();