blob: 62c4694616f10a12a5ce17431264b9b5972254c4 [file] [log] [blame]
John McCall9fbd3182011-06-15 23:37:01 +00001//===- ObjCARC.cpp - ObjC ARC Optimization --------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
13//
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
18// simplifications.
19//
20// This file also defines a simple ARC-aware AliasAnalysis.
21//
22// WARNING: This file knows about certain library functions. It recognizes them
23// by name, and hardwires knowedge of their semantics.
24//
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.
28//
29//===----------------------------------------------------------------------===//
30
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"
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +000036#include "llvm/Module.h"
John McCall9fbd3182011-06-15 23:37:01 +000037#include "llvm/Analysis/ValueTracking.h"
38#include "llvm/Transforms/Utils/Local.h"
39#include "llvm/Support/CallSite.h"
40#include "llvm/Support/CommandLine.h"
41#include "llvm/ADT/StringSwitch.h"
42#include "llvm/ADT/DenseMap.h"
43#include "llvm/ADT/STLExtras.h"
44using namespace llvm;
45
46// A handy option to enable/disable all optimizations in this file.
47static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
48
49//===----------------------------------------------------------------------===//
50// Misc. Utilities
51//===----------------------------------------------------------------------===//
52
53namespace {
54 /// MapVector - An associative container with fast insertion-order
55 /// (deterministic) iteration over its elements. Plus the special
56 /// blot operation.
57 template<class KeyT, class ValueT>
58 class MapVector {
59 /// Map - Map keys to indices in Vector.
60 typedef DenseMap<KeyT, size_t> MapTy;
61 MapTy Map;
62
63 /// Vector - Keys and values.
64 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
65 VectorTy Vector;
66
67 public:
68 typedef typename VectorTy::iterator iterator;
69 typedef typename VectorTy::const_iterator const_iterator;
70 iterator begin() { return Vector.begin(); }
71 iterator end() { return Vector.end(); }
72 const_iterator begin() const { return Vector.begin(); }
73 const_iterator end() const { return Vector.end(); }
74
75#ifdef XDEBUG
76 ~MapVector() {
77 assert(Vector.size() >= Map.size()); // May differ due to blotting.
78 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
79 I != E; ++I) {
80 assert(I->second < Vector.size());
81 assert(Vector[I->second].first == I->first);
82 }
83 for (typename VectorTy::const_iterator I = Vector.begin(),
84 E = Vector.end(); I != E; ++I)
85 assert(!I->first ||
86 (Map.count(I->first) &&
87 Map[I->first] == size_t(I - Vector.begin())));
88 }
89#endif
90
Dan Gohman22cc4cc2012-03-02 01:13:53 +000091 ValueT &operator[](const KeyT &Arg) {
John McCall9fbd3182011-06-15 23:37:01 +000092 std::pair<typename MapTy::iterator, bool> Pair =
93 Map.insert(std::make_pair(Arg, size_t(0)));
94 if (Pair.second) {
Dan Gohman22cc4cc2012-03-02 01:13:53 +000095 size_t Num = Vector.size();
96 Pair.first->second = Num;
John McCall9fbd3182011-06-15 23:37:01 +000097 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman22cc4cc2012-03-02 01:13:53 +000098 return Vector[Num].second;
John McCall9fbd3182011-06-15 23:37:01 +000099 }
100 return Vector[Pair.first->second].second;
101 }
102
103 std::pair<iterator, bool>
104 insert(const std::pair<KeyT, ValueT> &InsertPair) {
105 std::pair<typename MapTy::iterator, bool> Pair =
106 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
107 if (Pair.second) {
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000108 size_t Num = Vector.size();
109 Pair.first->second = Num;
John McCall9fbd3182011-06-15 23:37:01 +0000110 Vector.push_back(InsertPair);
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000111 return std::make_pair(Vector.begin() + Num, true);
John McCall9fbd3182011-06-15 23:37:01 +0000112 }
113 return std::make_pair(Vector.begin() + Pair.first->second, false);
114 }
115
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000116 const_iterator find(const KeyT &Key) const {
John McCall9fbd3182011-06-15 23:37:01 +0000117 typename MapTy::const_iterator It = Map.find(Key);
118 if (It == Map.end()) return Vector.end();
119 return Vector.begin() + It->second;
120 }
121
122 /// blot - This is similar to erase, but instead of removing the element
123 /// from the vector, it just zeros out the key in the vector. This leaves
124 /// iterators intact, but clients must be prepared for zeroed-out keys when
125 /// iterating.
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000126 void blot(const KeyT &Key) {
John McCall9fbd3182011-06-15 23:37:01 +0000127 typename MapTy::iterator It = Map.find(Key);
128 if (It == Map.end()) return;
129 Vector[It->second].first = KeyT();
130 Map.erase(It);
131 }
132
133 void clear() {
134 Map.clear();
135 Vector.clear();
136 }
137 };
138}
139
140//===----------------------------------------------------------------------===//
141// ARC Utilities.
142//===----------------------------------------------------------------------===//
143
144namespace {
145 /// InstructionClass - A simple classification for instructions.
146 enum InstructionClass {
147 IC_Retain, ///< objc_retain
148 IC_RetainRV, ///< objc_retainAutoreleasedReturnValue
149 IC_RetainBlock, ///< objc_retainBlock
150 IC_Release, ///< objc_release
151 IC_Autorelease, ///< objc_autorelease
152 IC_AutoreleaseRV, ///< objc_autoreleaseReturnValue
153 IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
154 IC_AutoreleasepoolPop, ///< objc_autoreleasePoolPop
155 IC_NoopCast, ///< objc_retainedObject, etc.
156 IC_FusedRetainAutorelease, ///< objc_retainAutorelease
157 IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
158 IC_LoadWeakRetained, ///< objc_loadWeakRetained (primitive)
159 IC_StoreWeak, ///< objc_storeWeak (primitive)
160 IC_InitWeak, ///< objc_initWeak (derived)
161 IC_LoadWeak, ///< objc_loadWeak (derived)
162 IC_MoveWeak, ///< objc_moveWeak (derived)
163 IC_CopyWeak, ///< objc_copyWeak (derived)
164 IC_DestroyWeak, ///< objc_destroyWeak (derived)
165 IC_CallOrUser, ///< could call objc_release and/or "use" pointers
166 IC_Call, ///< could call objc_release
167 IC_User, ///< could "use" a pointer
168 IC_None ///< anything else
169 };
170}
171
172/// IsPotentialUse - Test whether the given value is possible a
173/// reference-counted pointer.
174static bool IsPotentialUse(const Value *Op) {
175 // Pointers to static or stack storage are not reference-counted pointers.
176 if (isa<Constant>(Op) || isa<AllocaInst>(Op))
177 return false;
178 // Special arguments are not reference-counted.
179 if (const Argument *Arg = dyn_cast<Argument>(Op))
180 if (Arg->hasByValAttr() ||
181 Arg->hasNestAttr() ||
182 Arg->hasStructRetAttr())
183 return false;
Dan Gohmanf9096e42011-12-14 19:10:53 +0000184 // Only consider values with pointer types.
185 // It seemes intuitive to exclude function pointer types as well, since
186 // functions are never reference-counted, however clang occasionally
187 // bitcasts reference-counted pointers to function-pointer type
188 // temporarily.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000189 PointerType *Ty = dyn_cast<PointerType>(Op->getType());
Dan Gohmanf9096e42011-12-14 19:10:53 +0000190 if (!Ty)
John McCall9fbd3182011-06-15 23:37:01 +0000191 return false;
192 // Conservatively assume anything else is a potential use.
193 return true;
194}
195
196/// GetCallSiteClass - Helper for GetInstructionClass. Determines what kind
197/// of construct CS is.
198static InstructionClass GetCallSiteClass(ImmutableCallSite CS) {
199 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
200 I != E; ++I)
201 if (IsPotentialUse(*I))
202 return CS.onlyReadsMemory() ? IC_User : IC_CallOrUser;
203
204 return CS.onlyReadsMemory() ? IC_None : IC_Call;
205}
206
207/// GetFunctionClass - Determine if F is one of the special known Functions.
208/// If it isn't, return IC_CallOrUser.
209static InstructionClass GetFunctionClass(const Function *F) {
210 Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
211
212 // No arguments.
213 if (AI == AE)
214 return StringSwitch<InstructionClass>(F->getName())
215 .Case("objc_autoreleasePoolPush", IC_AutoreleasepoolPush)
216 .Default(IC_CallOrUser);
217
218 // One argument.
219 const Argument *A0 = AI++;
220 if (AI == AE)
221 // Argument is a pointer.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000222 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType())) {
223 Type *ETy = PTy->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000224 // Argument is i8*.
225 if (ETy->isIntegerTy(8))
226 return StringSwitch<InstructionClass>(F->getName())
227 .Case("objc_retain", IC_Retain)
228 .Case("objc_retainAutoreleasedReturnValue", IC_RetainRV)
229 .Case("objc_retainBlock", IC_RetainBlock)
230 .Case("objc_release", IC_Release)
231 .Case("objc_autorelease", IC_Autorelease)
232 .Case("objc_autoreleaseReturnValue", IC_AutoreleaseRV)
233 .Case("objc_autoreleasePoolPop", IC_AutoreleasepoolPop)
234 .Case("objc_retainedObject", IC_NoopCast)
235 .Case("objc_unretainedObject", IC_NoopCast)
236 .Case("objc_unretainedPointer", IC_NoopCast)
237 .Case("objc_retain_autorelease", IC_FusedRetainAutorelease)
238 .Case("objc_retainAutorelease", IC_FusedRetainAutorelease)
239 .Case("objc_retainAutoreleaseReturnValue",IC_FusedRetainAutoreleaseRV)
240 .Default(IC_CallOrUser);
241
242 // Argument is i8**
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000243 if (PointerType *Pte = dyn_cast<PointerType>(ETy))
John McCall9fbd3182011-06-15 23:37:01 +0000244 if (Pte->getElementType()->isIntegerTy(8))
245 return StringSwitch<InstructionClass>(F->getName())
246 .Case("objc_loadWeakRetained", IC_LoadWeakRetained)
247 .Case("objc_loadWeak", IC_LoadWeak)
248 .Case("objc_destroyWeak", IC_DestroyWeak)
249 .Default(IC_CallOrUser);
250 }
251
252 // Two arguments, first is i8**.
253 const Argument *A1 = AI++;
254 if (AI == AE)
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000255 if (PointerType *PTy = dyn_cast<PointerType>(A0->getType()))
256 if (PointerType *Pte = dyn_cast<PointerType>(PTy->getElementType()))
John McCall9fbd3182011-06-15 23:37:01 +0000257 if (Pte->getElementType()->isIntegerTy(8))
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000258 if (PointerType *PTy1 = dyn_cast<PointerType>(A1->getType())) {
259 Type *ETy1 = PTy1->getElementType();
John McCall9fbd3182011-06-15 23:37:01 +0000260 // Second argument is i8*
261 if (ETy1->isIntegerTy(8))
262 return StringSwitch<InstructionClass>(F->getName())
263 .Case("objc_storeWeak", IC_StoreWeak)
264 .Case("objc_initWeak", IC_InitWeak)
265 .Default(IC_CallOrUser);
266 // Second argument is i8**.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000267 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
John McCall9fbd3182011-06-15 23:37:01 +0000268 if (Pte1->getElementType()->isIntegerTy(8))
269 return StringSwitch<InstructionClass>(F->getName())
270 .Case("objc_moveWeak", IC_MoveWeak)
271 .Case("objc_copyWeak", IC_CopyWeak)
272 .Default(IC_CallOrUser);
273 }
274
275 // Anything else.
276 return IC_CallOrUser;
277}
278
279/// GetInstructionClass - Determine what kind of construct V is.
280static InstructionClass GetInstructionClass(const Value *V) {
281 if (const Instruction *I = dyn_cast<Instruction>(V)) {
282 // Any instruction other than bitcast and gep with a pointer operand have a
283 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
284 // to a subsequent use, rather than using it themselves, in this sense.
285 // As a short cut, several other opcodes are known to have no pointer
286 // operands of interest. And ret is never followed by a release, so it's
287 // not interesting to examine.
288 switch (I->getOpcode()) {
289 case Instruction::Call: {
290 const CallInst *CI = cast<CallInst>(I);
291 // Check for calls to special functions.
292 if (const Function *F = CI->getCalledFunction()) {
293 InstructionClass Class = GetFunctionClass(F);
294 if (Class != IC_CallOrUser)
295 return Class;
296
297 // None of the intrinsic functions do objc_release. For intrinsics, the
298 // only question is whether or not they may be users.
299 switch (F->getIntrinsicID()) {
300 case 0: break;
301 case Intrinsic::bswap: case Intrinsic::ctpop:
302 case Intrinsic::ctlz: case Intrinsic::cttz:
303 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
304 case Intrinsic::stacksave: case Intrinsic::stackrestore:
305 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
306 // Don't let dbg info affect our results.
307 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
308 // Short cut: Some intrinsics obviously don't use ObjC pointers.
309 return IC_None;
310 default:
311 for (Function::const_arg_iterator AI = F->arg_begin(),
312 AE = F->arg_end(); AI != AE; ++AI)
313 if (IsPotentialUse(AI))
314 return IC_User;
315 return IC_None;
316 }
317 }
318 return GetCallSiteClass(CI);
319 }
320 case Instruction::Invoke:
321 return GetCallSiteClass(cast<InvokeInst>(I));
322 case Instruction::BitCast:
323 case Instruction::GetElementPtr:
324 case Instruction::Select: case Instruction::PHI:
325 case Instruction::Ret: case Instruction::Br:
326 case Instruction::Switch: case Instruction::IndirectBr:
327 case Instruction::Alloca: case Instruction::VAArg:
328 case Instruction::Add: case Instruction::FAdd:
329 case Instruction::Sub: case Instruction::FSub:
330 case Instruction::Mul: case Instruction::FMul:
331 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
332 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
333 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
334 case Instruction::And: case Instruction::Or: case Instruction::Xor:
335 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
336 case Instruction::IntToPtr: case Instruction::FCmp:
337 case Instruction::FPTrunc: case Instruction::FPExt:
338 case Instruction::FPToUI: case Instruction::FPToSI:
339 case Instruction::UIToFP: case Instruction::SIToFP:
340 case Instruction::InsertElement: case Instruction::ExtractElement:
341 case Instruction::ShuffleVector:
342 case Instruction::ExtractValue:
343 break;
344 case Instruction::ICmp:
345 // Comparing a pointer with null, or any other constant, isn't an
346 // interesting use, because we don't care what the pointer points to, or
347 // about the values of any other dynamic reference-counted pointers.
348 if (IsPotentialUse(I->getOperand(1)))
349 return IC_User;
350 break;
351 default:
352 // For anything else, check all the operands.
Dan Gohmand4464602011-08-22 17:29:37 +0000353 // Note that this includes both operands of a Store: while the first
354 // operand isn't actually being dereferenced, it is being stored to
355 // memory where we can no longer track who might read it and dereference
356 // it, so we have to consider it potentially used.
John McCall9fbd3182011-06-15 23:37:01 +0000357 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
358 OI != OE; ++OI)
359 if (IsPotentialUse(*OI))
360 return IC_User;
361 }
362 }
363
364 // Otherwise, it's totally inert for ARC purposes.
365 return IC_None;
366}
367
368/// GetBasicInstructionClass - Determine what kind of construct V is. This is
369/// similar to GetInstructionClass except that it only detects objc runtine
370/// calls. This allows it to be faster.
371static InstructionClass GetBasicInstructionClass(const Value *V) {
372 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
373 if (const Function *F = CI->getCalledFunction())
374 return GetFunctionClass(F);
375 // Otherwise, be conservative.
376 return IC_CallOrUser;
377 }
378
379 // Otherwise, be conservative.
Dan Gohman2f6263c2012-01-17 20:52:24 +0000380 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
John McCall9fbd3182011-06-15 23:37:01 +0000381}
382
383/// IsRetain - Test if the the given class is objc_retain or
384/// equivalent.
385static bool IsRetain(InstructionClass Class) {
386 return Class == IC_Retain ||
387 Class == IC_RetainRV;
388}
389
390/// IsAutorelease - Test if the the given class is objc_autorelease or
391/// equivalent.
392static bool IsAutorelease(InstructionClass Class) {
393 return Class == IC_Autorelease ||
394 Class == IC_AutoreleaseRV;
395}
396
397/// IsForwarding - Test if the given class represents instructions which return
398/// their argument verbatim.
399static bool IsForwarding(InstructionClass Class) {
400 // objc_retainBlock technically doesn't always return its argument
401 // verbatim, but it doesn't matter for our purposes here.
402 return Class == IC_Retain ||
403 Class == IC_RetainRV ||
404 Class == IC_Autorelease ||
405 Class == IC_AutoreleaseRV ||
406 Class == IC_RetainBlock ||
407 Class == IC_NoopCast;
408}
409
410/// IsNoopOnNull - Test if the given class represents instructions which do
411/// nothing if passed a null pointer.
412static bool IsNoopOnNull(InstructionClass Class) {
413 return Class == IC_Retain ||
414 Class == IC_RetainRV ||
415 Class == IC_Release ||
416 Class == IC_Autorelease ||
417 Class == IC_AutoreleaseRV ||
418 Class == IC_RetainBlock;
419}
420
421/// IsAlwaysTail - Test if the given class represents instructions which are
422/// always safe to mark with the "tail" keyword.
423static bool IsAlwaysTail(InstructionClass Class) {
424 // IC_RetainBlock may be given a stack argument.
425 return Class == IC_Retain ||
426 Class == IC_RetainRV ||
427 Class == IC_Autorelease ||
428 Class == IC_AutoreleaseRV;
429}
430
431/// IsNoThrow - Test if the given class represents instructions which are always
432/// safe to mark with the nounwind attribute..
433static bool IsNoThrow(InstructionClass Class) {
Dan Gohman1d2fd752011-09-14 18:33:34 +0000434 // objc_retainBlock is not nounwind because it calls user copy constructors
435 // which could theoretically throw.
John McCall9fbd3182011-06-15 23:37:01 +0000436 return Class == IC_Retain ||
437 Class == IC_RetainRV ||
John McCall9fbd3182011-06-15 23:37:01 +0000438 Class == IC_Release ||
439 Class == IC_Autorelease ||
440 Class == IC_AutoreleaseRV ||
441 Class == IC_AutoreleasepoolPush ||
442 Class == IC_AutoreleasepoolPop;
443}
444
445/// EraseInstruction - Erase the given instruction. ObjC calls return their
446/// argument verbatim, so if it's such a call and the return value has users,
447/// replace them with the argument value.
448static void EraseInstruction(Instruction *CI) {
449 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
450
451 bool Unused = CI->use_empty();
452
453 if (!Unused) {
454 // Replace the return value with the argument.
455 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
456 "Can't delete non-forwarding instruction with users!");
457 CI->replaceAllUsesWith(OldArg);
458 }
459
460 CI->eraseFromParent();
461
462 if (Unused)
463 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
464}
465
466/// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
467/// also knows how to look through objc_retain and objc_autorelease calls, which
468/// we know to return their argument verbatim.
469static const Value *GetUnderlyingObjCPtr(const Value *V) {
470 for (;;) {
471 V = GetUnderlyingObject(V);
472 if (!IsForwarding(GetBasicInstructionClass(V)))
473 break;
474 V = cast<CallInst>(V)->getArgOperand(0);
475 }
476
477 return V;
478}
479
480/// StripPointerCastsAndObjCCalls - This is a wrapper around
481/// Value::stripPointerCasts which also knows how to look through objc_retain
482/// and objc_autorelease calls, which we know to return their argument verbatim.
483static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
484 for (;;) {
485 V = V->stripPointerCasts();
486 if (!IsForwarding(GetBasicInstructionClass(V)))
487 break;
488 V = cast<CallInst>(V)->getArgOperand(0);
489 }
490 return V;
491}
492
493/// StripPointerCastsAndObjCCalls - This is a wrapper around
494/// Value::stripPointerCasts which also knows how to look through objc_retain
495/// and objc_autorelease calls, which we know to return their argument verbatim.
496static Value *StripPointerCastsAndObjCCalls(Value *V) {
497 for (;;) {
498 V = V->stripPointerCasts();
499 if (!IsForwarding(GetBasicInstructionClass(V)))
500 break;
501 V = cast<CallInst>(V)->getArgOperand(0);
502 }
503 return V;
504}
505
506/// GetObjCArg - Assuming the given instruction is one of the special calls such
507/// as objc_retain or objc_release, return the argument value, stripped of no-op
508/// casts and forwarding calls.
509static Value *GetObjCArg(Value *Inst) {
510 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
511}
512
513/// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
514/// isObjCIdentifiedObject, except that it uses special knowledge of
515/// ObjC conventions...
516static bool IsObjCIdentifiedObject(const Value *V) {
517 // Assume that call results and arguments have their own "provenance".
518 // Constants (including GlobalVariables) and Allocas are never
519 // reference-counted.
520 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
521 isa<Argument>(V) || isa<Constant>(V) ||
522 isa<AllocaInst>(V))
523 return true;
524
525 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
526 const Value *Pointer =
527 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
528 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
Dan Gohman1b31ea82011-08-22 17:29:11 +0000529 // A constant pointer can't be pointing to an object on the heap. It may
530 // be reference-counted, but it won't be deleted.
531 if (GV->isConstant())
532 return true;
John McCall9fbd3182011-06-15 23:37:01 +0000533 StringRef Name = GV->getName();
534 // These special variables are known to hold values which are not
535 // reference-counted pointers.
536 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
537 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
538 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
539 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
540 Name.startswith("\01l_objc_msgSend_fixup_"))
541 return true;
542 }
543 }
544
545 return false;
546}
547
548/// FindSingleUseIdentifiedObject - This is similar to
549/// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
550/// with multiple uses.
551static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
552 if (Arg->hasOneUse()) {
553 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
554 return FindSingleUseIdentifiedObject(BC->getOperand(0));
555 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
556 if (GEP->hasAllZeroIndices())
557 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
558 if (IsForwarding(GetBasicInstructionClass(Arg)))
559 return FindSingleUseIdentifiedObject(
560 cast<CallInst>(Arg)->getArgOperand(0));
561 if (!IsObjCIdentifiedObject(Arg))
562 return 0;
563 return Arg;
564 }
565
566 // If we found an identifiable object but it has multiple uses, but they
567 // are trivial uses, we can still consider this to be a single-use
568 // value.
569 if (IsObjCIdentifiedObject(Arg)) {
570 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
571 UI != UE; ++UI) {
572 const User *U = *UI;
573 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
574 return 0;
575 }
576
577 return Arg;
578 }
579
580 return 0;
581}
582
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000583/// ModuleHasARC - Test if the given module looks interesting to run ARC
584/// optimization on.
585static bool ModuleHasARC(const Module &M) {
586 return
587 M.getNamedValue("objc_retain") ||
588 M.getNamedValue("objc_release") ||
589 M.getNamedValue("objc_autorelease") ||
590 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
591 M.getNamedValue("objc_retainBlock") ||
592 M.getNamedValue("objc_autoreleaseReturnValue") ||
593 M.getNamedValue("objc_autoreleasePoolPush") ||
594 M.getNamedValue("objc_loadWeakRetained") ||
595 M.getNamedValue("objc_loadWeak") ||
596 M.getNamedValue("objc_destroyWeak") ||
597 M.getNamedValue("objc_storeWeak") ||
598 M.getNamedValue("objc_initWeak") ||
599 M.getNamedValue("objc_moveWeak") ||
600 M.getNamedValue("objc_copyWeak") ||
601 M.getNamedValue("objc_retainedObject") ||
602 M.getNamedValue("objc_unretainedObject") ||
603 M.getNamedValue("objc_unretainedPointer");
604}
605
Dan Gohman79522dc2012-01-13 00:39:07 +0000606/// DoesObjCBlockEscape - Test whether the given pointer, which is an
607/// Objective C block pointer, does not "escape". This differs from regular
608/// escape analysis in that a use as an argument to a call is not considered
609/// an escape.
610static bool DoesObjCBlockEscape(const Value *BlockPtr) {
611 // Walk the def-use chains.
612 SmallVector<const Value *, 4> Worklist;
613 Worklist.push_back(BlockPtr);
614 do {
615 const Value *V = Worklist.pop_back_val();
616 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
617 UI != UE; ++UI) {
618 const User *UUser = *UI;
619 // Special - Use by a call (callee or argument) is not considered
620 // to be an escape.
Dan Gohman92180982012-01-14 00:47:44 +0000621 if (isa<CallInst>(UUser) || isa<InvokeInst>(UUser))
Dan Gohman79522dc2012-01-13 00:39:07 +0000622 continue;
Dan Gohmana3b08d62012-02-13 22:57:02 +0000623 // Use by an instruction which copies the value is an escape if the
624 // result is an escape.
Dan Gohman79522dc2012-01-13 00:39:07 +0000625 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
626 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
627 Worklist.push_back(UUser);
628 continue;
629 }
Dan Gohmana3b08d62012-02-13 22:57:02 +0000630 // Use by a load is not an escape.
631 if (isa<LoadInst>(UUser))
632 continue;
633 // Use by a store is not an escape if the use is the address.
634 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
635 if (V != SI->getValueOperand())
636 continue;
637 // Otherwise, conservatively assume an escape.
Dan Gohman79522dc2012-01-13 00:39:07 +0000638 return true;
639 }
640 } while (!Worklist.empty());
641
642 // No escapes found.
643 return false;
644}
645
John McCall9fbd3182011-06-15 23:37:01 +0000646//===----------------------------------------------------------------------===//
647// ARC AliasAnalysis.
648//===----------------------------------------------------------------------===//
649
650#include "llvm/Pass.h"
651#include "llvm/Analysis/AliasAnalysis.h"
652#include "llvm/Analysis/Passes.h"
653
654namespace {
655 /// ObjCARCAliasAnalysis - This is a simple alias analysis
656 /// implementation that uses knowledge of ARC constructs to answer queries.
657 ///
658 /// TODO: This class could be generalized to know about other ObjC-specific
659 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
660 /// even though their offsets are dynamic.
661 class ObjCARCAliasAnalysis : public ImmutablePass,
662 public AliasAnalysis {
663 public:
664 static char ID; // Class identification, replacement for typeinfo
665 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
666 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
667 }
668
669 private:
670 virtual void initializePass() {
671 InitializeAliasAnalysis(this);
672 }
673
674 /// getAdjustedAnalysisPointer - This method is used when a pass implements
675 /// an analysis interface through multiple inheritance. If needed, it
676 /// should override this to adjust the this pointer as needed for the
677 /// specified pass info.
678 virtual void *getAdjustedAnalysisPointer(const void *PI) {
679 if (PI == &AliasAnalysis::ID)
680 return (AliasAnalysis*)this;
681 return this;
682 }
683
684 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
685 virtual AliasResult alias(const Location &LocA, const Location &LocB);
686 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
687 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
688 virtual ModRefBehavior getModRefBehavior(const Function *F);
689 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
690 const Location &Loc);
691 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
692 ImmutableCallSite CS2);
693 };
694} // End of anonymous namespace
695
696// Register this pass...
697char ObjCARCAliasAnalysis::ID = 0;
698INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
699 "ObjC-ARC-Based Alias Analysis", false, true, false)
700
701ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
702 return new ObjCARCAliasAnalysis();
703}
704
705void
706ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
707 AU.setPreservesAll();
708 AliasAnalysis::getAnalysisUsage(AU);
709}
710
711AliasAnalysis::AliasResult
712ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
713 if (!EnableARCOpts)
714 return AliasAnalysis::alias(LocA, LocB);
715
716 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
717 // precise alias query.
718 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
719 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
720 AliasResult Result =
721 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
722 Location(SB, LocB.Size, LocB.TBAATag));
723 if (Result != MayAlias)
724 return Result;
725
726 // If that failed, climb to the underlying object, including climbing through
727 // ObjC-specific no-ops, and try making an imprecise alias query.
728 const Value *UA = GetUnderlyingObjCPtr(SA);
729 const Value *UB = GetUnderlyingObjCPtr(SB);
730 if (UA != SA || UB != SB) {
731 Result = AliasAnalysis::alias(Location(UA), Location(UB));
732 // We can't use MustAlias or PartialAlias results here because
733 // GetUnderlyingObjCPtr may return an offsetted pointer value.
734 if (Result == NoAlias)
735 return NoAlias;
736 }
737
738 // If that failed, fail. We don't need to chain here, since that's covered
739 // by the earlier precise query.
740 return MayAlias;
741}
742
743bool
744ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
745 bool OrLocal) {
746 if (!EnableARCOpts)
747 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
748
749 // First, strip off no-ops, including ObjC-specific no-ops, and try making
750 // a precise alias query.
751 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
752 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
753 OrLocal))
754 return true;
755
756 // If that failed, climb to the underlying object, including climbing through
757 // ObjC-specific no-ops, and try making an imprecise alias query.
758 const Value *U = GetUnderlyingObjCPtr(S);
759 if (U != S)
760 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
761
762 // If that failed, fail. We don't need to chain here, since that's covered
763 // by the earlier precise query.
764 return false;
765}
766
767AliasAnalysis::ModRefBehavior
768ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
769 // We have nothing to do. Just chain to the next AliasAnalysis.
770 return AliasAnalysis::getModRefBehavior(CS);
771}
772
773AliasAnalysis::ModRefBehavior
774ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
775 if (!EnableARCOpts)
776 return AliasAnalysis::getModRefBehavior(F);
777
778 switch (GetFunctionClass(F)) {
779 case IC_NoopCast:
780 return DoesNotAccessMemory;
781 default:
782 break;
783 }
784
785 return AliasAnalysis::getModRefBehavior(F);
786}
787
788AliasAnalysis::ModRefResult
789ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
790 if (!EnableARCOpts)
791 return AliasAnalysis::getModRefInfo(CS, Loc);
792
793 switch (GetBasicInstructionClass(CS.getInstruction())) {
794 case IC_Retain:
795 case IC_RetainRV:
John McCall9fbd3182011-06-15 23:37:01 +0000796 case IC_Autorelease:
797 case IC_AutoreleaseRV:
798 case IC_NoopCast:
799 case IC_AutoreleasepoolPush:
800 case IC_FusedRetainAutorelease:
801 case IC_FusedRetainAutoreleaseRV:
802 // These functions don't access any memory visible to the compiler.
Dan Gohman21104822011-09-14 18:13:00 +0000803 // Note that this doesn't include objc_retainBlock, becuase it updates
804 // pointers when it copies block data.
John McCall9fbd3182011-06-15 23:37:01 +0000805 return NoModRef;
806 default:
807 break;
808 }
809
810 return AliasAnalysis::getModRefInfo(CS, Loc);
811}
812
813AliasAnalysis::ModRefResult
814ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
815 ImmutableCallSite CS2) {
816 // TODO: Theoretically we could check for dependencies between objc_* calls
817 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
818 return AliasAnalysis::getModRefInfo(CS1, CS2);
819}
820
821//===----------------------------------------------------------------------===//
822// ARC expansion.
823//===----------------------------------------------------------------------===//
824
825#include "llvm/Support/InstIterator.h"
826#include "llvm/Transforms/Scalar.h"
827
828namespace {
829 /// ObjCARCExpand - Early ARC transformations.
830 class ObjCARCExpand : public FunctionPass {
831 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000832 virtual bool doInitialization(Module &M);
John McCall9fbd3182011-06-15 23:37:01 +0000833 virtual bool runOnFunction(Function &F);
834
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000835 /// Run - A flag indicating whether this optimization pass should run.
836 bool Run;
837
John McCall9fbd3182011-06-15 23:37:01 +0000838 public:
839 static char ID;
840 ObjCARCExpand() : FunctionPass(ID) {
841 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
842 }
843 };
844}
845
846char ObjCARCExpand::ID = 0;
847INITIALIZE_PASS(ObjCARCExpand,
848 "objc-arc-expand", "ObjC ARC expansion", false, false)
849
850Pass *llvm::createObjCARCExpandPass() {
851 return new ObjCARCExpand();
852}
853
854void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
855 AU.setPreservesCFG();
856}
857
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000858bool ObjCARCExpand::doInitialization(Module &M) {
859 Run = ModuleHasARC(M);
860 return false;
861}
862
John McCall9fbd3182011-06-15 23:37:01 +0000863bool ObjCARCExpand::runOnFunction(Function &F) {
864 if (!EnableARCOpts)
865 return false;
866
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000867 // If nothing in the Module uses ARC, don't do anything.
868 if (!Run)
869 return false;
870
John McCall9fbd3182011-06-15 23:37:01 +0000871 bool Changed = false;
872
873 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
874 Instruction *Inst = &*I;
875
876 switch (GetBasicInstructionClass(Inst)) {
877 case IC_Retain:
878 case IC_RetainRV:
879 case IC_Autorelease:
880 case IC_AutoreleaseRV:
881 case IC_FusedRetainAutorelease:
882 case IC_FusedRetainAutoreleaseRV:
883 // These calls return their argument verbatim, as a low-level
884 // optimization. However, this makes high-level optimizations
885 // harder. Undo any uses of this optimization that the front-end
886 // emitted here. We'll redo them in a later pass.
887 Changed = true;
888 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
889 break;
890 default:
891 break;
892 }
893 }
894
895 return Changed;
896}
897
898//===----------------------------------------------------------------------===//
Dan Gohman2f6263c2012-01-17 20:52:24 +0000899// ARC autorelease pool elimination.
900//===----------------------------------------------------------------------===//
901
Dan Gohman1dae3e92012-01-18 21:19:38 +0000902#include "llvm/Constants.h"
903
Dan Gohman2f6263c2012-01-17 20:52:24 +0000904namespace {
905 /// ObjCARCAPElim - Autorelease pool elimination.
906 class ObjCARCAPElim : public ModulePass {
907 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
908 virtual bool runOnModule(Module &M);
909
Dan Gohman2f77bbd2012-01-18 21:24:45 +0000910 bool MayAutorelease(CallSite CS, unsigned Depth = 0);
Dan Gohman2f6263c2012-01-17 20:52:24 +0000911 bool OptimizeBB(BasicBlock *BB);
912
913 public:
914 static char ID;
915 ObjCARCAPElim() : ModulePass(ID) {
916 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
917 }
918 };
919}
920
921char ObjCARCAPElim::ID = 0;
922INITIALIZE_PASS(ObjCARCAPElim,
923 "objc-arc-apelim",
924 "ObjC ARC autorelease pool elimination",
925 false, false)
926
927Pass *llvm::createObjCARCAPElimPass() {
928 return new ObjCARCAPElim();
929}
930
931void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
932 AU.setPreservesCFG();
933}
934
935/// MayAutorelease - Interprocedurally determine if calls made by the
936/// given call site can possibly produce autoreleases.
Dan Gohman2f77bbd2012-01-18 21:24:45 +0000937bool ObjCARCAPElim::MayAutorelease(CallSite CS, unsigned Depth) {
Dan Gohman2f6263c2012-01-17 20:52:24 +0000938 if (Function *Callee = CS.getCalledFunction()) {
939 if (Callee->isDeclaration() || Callee->mayBeOverridden())
940 return true;
941 for (Function::iterator I = Callee->begin(), E = Callee->end();
942 I != E; ++I) {
943 BasicBlock *BB = I;
944 for (BasicBlock::iterator J = BB->begin(), F = BB->end(); J != F; ++J)
945 if (CallSite JCS = CallSite(J))
Dan Gohman2f77bbd2012-01-18 21:24:45 +0000946 // This recursion depth limit is arbitrary. It's just great
947 // enough to cover known interesting testcases.
948 if (Depth < 3 &&
949 !JCS.onlyReadsMemory() &&
950 MayAutorelease(JCS, Depth + 1))
Dan Gohman2f6263c2012-01-17 20:52:24 +0000951 return true;
952 }
953 return false;
954 }
955
956 return true;
957}
958
959bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
960 bool Changed = false;
961
962 Instruction *Push = 0;
963 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
964 Instruction *Inst = I++;
965 switch (GetBasicInstructionClass(Inst)) {
966 case IC_AutoreleasepoolPush:
967 Push = Inst;
968 break;
969 case IC_AutoreleasepoolPop:
970 // If this pop matches a push and nothing in between can autorelease,
971 // zap the pair.
972 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
973 Changed = true;
974 Inst->eraseFromParent();
975 Push->eraseFromParent();
976 }
977 Push = 0;
978 break;
979 case IC_CallOrUser:
980 if (MayAutorelease(CallSite(Inst)))
981 Push = 0;
982 break;
983 default:
984 break;
985 }
986 }
987
988 return Changed;
989}
990
991bool ObjCARCAPElim::runOnModule(Module &M) {
992 if (!EnableARCOpts)
993 return false;
994
995 // If nothing in the Module uses ARC, don't do anything.
996 if (!ModuleHasARC(M))
997 return false;
998
Dan Gohman1dae3e92012-01-18 21:19:38 +0000999 // Find the llvm.global_ctors variable, as the first step in
1000 // identifying the global constructors.
1001 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1002 if (!GV)
1003 return false;
1004
1005 assert(GV->hasDefinitiveInitializer() &&
1006 "llvm.global_ctors is uncooperative!");
1007
Dan Gohman2f6263c2012-01-17 20:52:24 +00001008 bool Changed = false;
1009
Dan Gohman1dae3e92012-01-18 21:19:38 +00001010 // Dig the constructor functions out of GV's initializer.
1011 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1012 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1013 OI != OE; ++OI) {
1014 Value *Op = *OI;
1015 // llvm.global_ctors is an array of pairs where the second members
1016 // are constructor functions.
1017 Function *F = cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
Dan Gohman2f6263c2012-01-17 20:52:24 +00001018 // Only look at function definitions.
1019 if (F->isDeclaration())
1020 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001021 // Only look at functions with one basic block.
1022 if (llvm::next(F->begin()) != F->end())
1023 continue;
1024 // Ok, a single-block constructor function definition. Try to optimize it.
1025 Changed |= OptimizeBB(F->begin());
1026 }
1027
1028 return Changed;
1029}
1030
1031//===----------------------------------------------------------------------===//
John McCall9fbd3182011-06-15 23:37:01 +00001032// ARC optimization.
1033//===----------------------------------------------------------------------===//
1034
1035// TODO: On code like this:
1036//
1037// objc_retain(%x)
1038// stuff_that_cannot_release()
1039// objc_autorelease(%x)
1040// stuff_that_cannot_release()
1041// objc_retain(%x)
1042// stuff_that_cannot_release()
1043// objc_autorelease(%x)
1044//
1045// The second retain and autorelease can be deleted.
1046
1047// TODO: It should be possible to delete
1048// objc_autoreleasePoolPush and objc_autoreleasePoolPop
1049// pairs if nothing is actually autoreleased between them. Also, autorelease
1050// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1051// after inlining) can be turned into plain release calls.
1052
1053// TODO: Critical-edge splitting. If the optimial insertion point is
1054// a critical edge, the current algorithm has to fail, because it doesn't
1055// know how to split edges. It should be possible to make the optimizer
1056// think in terms of edges, rather than blocks, and then split critical
1057// edges on demand.
1058
1059// TODO: OptimizeSequences could generalized to be Interprocedural.
1060
1061// TODO: Recognize that a bunch of other objc runtime calls have
1062// non-escaping arguments and non-releasing arguments, and may be
1063// non-autoreleasing.
1064
1065// TODO: Sink autorelease calls as far as possible. Unfortunately we
1066// usually can't sink them past other calls, which would be the main
1067// case where it would be useful.
1068
Dan Gohmane6d5e882011-08-19 00:26:36 +00001069// TODO: The pointer returned from objc_loadWeakRetained is retained.
1070
1071// TODO: Delete release+retain pairs (rare).
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001072
John McCall9fbd3182011-06-15 23:37:01 +00001073#include "llvm/GlobalAlias.h"
John McCall9fbd3182011-06-15 23:37:01 +00001074#include "llvm/Constants.h"
1075#include "llvm/LLVMContext.h"
1076#include "llvm/Support/ErrorHandling.h"
1077#include "llvm/Support/CFG.h"
John McCall9fbd3182011-06-15 23:37:01 +00001078#include "llvm/ADT/Statistic.h"
Dan Gohman59a1c932011-12-12 19:42:25 +00001079#include "llvm/ADT/SmallPtrSet.h"
1080#include "llvm/ADT/DenseSet.h"
John McCall9fbd3182011-06-15 23:37:01 +00001081
1082STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1083STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1084STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1085STATISTIC(NumRets, "Number of return value forwarding "
1086 "retain+autoreleaes eliminated");
1087STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1088STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1089
1090namespace {
1091 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1092 /// uses many of the same techniques, except it uses special ObjC-specific
1093 /// reasoning about pointer relationships.
1094 class ProvenanceAnalysis {
1095 AliasAnalysis *AA;
1096
1097 typedef std::pair<const Value *, const Value *> ValuePairTy;
1098 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1099 CachedResultsTy CachedResults;
1100
1101 bool relatedCheck(const Value *A, const Value *B);
1102 bool relatedSelect(const SelectInst *A, const Value *B);
1103 bool relatedPHI(const PHINode *A, const Value *B);
1104
1105 // Do not implement.
1106 void operator=(const ProvenanceAnalysis &);
1107 ProvenanceAnalysis(const ProvenanceAnalysis &);
1108
1109 public:
1110 ProvenanceAnalysis() {}
1111
1112 void setAA(AliasAnalysis *aa) { AA = aa; }
1113
1114 AliasAnalysis *getAA() const { return AA; }
1115
1116 bool related(const Value *A, const Value *B);
1117
1118 void clear() {
1119 CachedResults.clear();
1120 }
1121 };
1122}
1123
1124bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1125 // If the values are Selects with the same condition, we can do a more precise
1126 // check: just check for relations between the values on corresponding arms.
1127 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
1128 if (A->getCondition() == SB->getCondition()) {
1129 if (related(A->getTrueValue(), SB->getTrueValue()))
1130 return true;
1131 if (related(A->getFalseValue(), SB->getFalseValue()))
1132 return true;
1133 return false;
1134 }
1135
1136 // Check both arms of the Select node individually.
1137 if (related(A->getTrueValue(), B))
1138 return true;
1139 if (related(A->getFalseValue(), B))
1140 return true;
1141
1142 // The arms both checked out.
1143 return false;
1144}
1145
1146bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1147 // If the values are PHIs in the same block, we can do a more precise as well
1148 // as efficient check: just check for relations between the values on
1149 // corresponding edges.
1150 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1151 if (PNB->getParent() == A->getParent()) {
1152 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1153 if (related(A->getIncomingValue(i),
1154 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1155 return true;
1156 return false;
1157 }
1158
1159 // Check each unique source of the PHI node against B.
1160 SmallPtrSet<const Value *, 4> UniqueSrc;
1161 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1162 const Value *PV1 = A->getIncomingValue(i);
1163 if (UniqueSrc.insert(PV1) && related(PV1, B))
1164 return true;
1165 }
1166
1167 // All of the arms checked out.
1168 return false;
1169}
1170
1171/// isStoredObjCPointer - Test if the value of P, or any value covered by its
1172/// provenance, is ever stored within the function (not counting callees).
1173static bool isStoredObjCPointer(const Value *P) {
1174 SmallPtrSet<const Value *, 8> Visited;
1175 SmallVector<const Value *, 8> Worklist;
1176 Worklist.push_back(P);
1177 Visited.insert(P);
1178 do {
1179 P = Worklist.pop_back_val();
1180 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1181 UI != UE; ++UI) {
1182 const User *Ur = *UI;
1183 if (isa<StoreInst>(Ur)) {
1184 if (UI.getOperandNo() == 0)
1185 // The pointer is stored.
1186 return true;
1187 // The pointed is stored through.
1188 continue;
1189 }
1190 if (isa<CallInst>(Ur))
1191 // The pointer is passed as an argument, ignore this.
1192 continue;
1193 if (isa<PtrToIntInst>(P))
1194 // Assume the worst.
1195 return true;
1196 if (Visited.insert(Ur))
1197 Worklist.push_back(Ur);
1198 }
1199 } while (!Worklist.empty());
1200
1201 // Everything checked out.
1202 return false;
1203}
1204
1205bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1206 // Skip past provenance pass-throughs.
1207 A = GetUnderlyingObjCPtr(A);
1208 B = GetUnderlyingObjCPtr(B);
1209
1210 // Quick check.
1211 if (A == B)
1212 return true;
1213
1214 // Ask regular AliasAnalysis, for a first approximation.
1215 switch (AA->alias(A, B)) {
1216 case AliasAnalysis::NoAlias:
1217 return false;
1218 case AliasAnalysis::MustAlias:
1219 case AliasAnalysis::PartialAlias:
1220 return true;
1221 case AliasAnalysis::MayAlias:
1222 break;
1223 }
1224
1225 bool AIsIdentified = IsObjCIdentifiedObject(A);
1226 bool BIsIdentified = IsObjCIdentifiedObject(B);
1227
1228 // An ObjC-Identified object can't alias a load if it is never locally stored.
1229 if (AIsIdentified) {
1230 if (BIsIdentified) {
1231 // If both pointers have provenance, they can be directly compared.
1232 if (A != B)
1233 return false;
1234 } else {
1235 if (isa<LoadInst>(B))
1236 return isStoredObjCPointer(A);
1237 }
1238 } else {
1239 if (BIsIdentified && isa<LoadInst>(A))
1240 return isStoredObjCPointer(B);
1241 }
1242
1243 // Special handling for PHI and Select.
1244 if (const PHINode *PN = dyn_cast<PHINode>(A))
1245 return relatedPHI(PN, B);
1246 if (const PHINode *PN = dyn_cast<PHINode>(B))
1247 return relatedPHI(PN, A);
1248 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1249 return relatedSelect(S, B);
1250 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1251 return relatedSelect(S, A);
1252
1253 // Conservative.
1254 return true;
1255}
1256
1257bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1258 // Begin by inserting a conservative value into the map. If the insertion
1259 // fails, we have the answer already. If it succeeds, leave it there until we
1260 // compute the real answer to guard against recursive queries.
1261 if (A > B) std::swap(A, B);
1262 std::pair<CachedResultsTy::iterator, bool> Pair =
1263 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1264 if (!Pair.second)
1265 return Pair.first->second;
1266
1267 bool Result = relatedCheck(A, B);
1268 CachedResults[ValuePairTy(A, B)] = Result;
1269 return Result;
1270}
1271
1272namespace {
1273 // Sequence - A sequence of states that a pointer may go through in which an
1274 // objc_retain and objc_release are actually needed.
1275 enum Sequence {
1276 S_None,
1277 S_Retain, ///< objc_retain(x)
1278 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1279 S_Use, ///< any use of x
1280 S_Stop, ///< like S_Release, but code motion is stopped
1281 S_Release, ///< objc_release(x)
1282 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1283 };
1284}
1285
1286static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1287 // The easy cases.
1288 if (A == B)
1289 return A;
1290 if (A == S_None || B == S_None)
1291 return S_None;
1292
John McCall9fbd3182011-06-15 23:37:01 +00001293 if (A > B) std::swap(A, B);
1294 if (TopDown) {
1295 // Choose the side which is further along in the sequence.
Dan Gohmana7f7db22011-08-12 00:26:31 +00001296 if ((A == S_Retain || A == S_CanRelease) &&
1297 (B == S_CanRelease || B == S_Use))
John McCall9fbd3182011-06-15 23:37:01 +00001298 return B;
1299 } else {
1300 // Choose the side which is further along in the sequence.
1301 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohmana7f7db22011-08-12 00:26:31 +00001302 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCall9fbd3182011-06-15 23:37:01 +00001303 return A;
1304 // If both sides are releases, choose the more conservative one.
1305 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1306 return A;
1307 if (A == S_Release && B == S_MovableRelease)
1308 return A;
1309 }
1310
1311 return S_None;
1312}
1313
1314namespace {
1315 /// RRInfo - Unidirectional information about either a
1316 /// retain-decrement-use-release sequence or release-use-decrement-retain
1317 /// reverese sequence.
1318 struct RRInfo {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001319 /// KnownSafe - After an objc_retain, the reference count of the referenced
1320 /// object is known to be positive. Similarly, before an objc_release, the
1321 /// reference count of the referenced object is known to be positive. If
1322 /// there are retain-release pairs in code regions where the retain count
1323 /// is known to be positive, they can be eliminated, regardless of any side
1324 /// effects between them.
1325 ///
1326 /// Also, a retain+release pair nested within another retain+release
1327 /// pair all on the known same pointer value can be eliminated, regardless
1328 /// of any intervening side effects.
1329 ///
1330 /// KnownSafe is true when either of these conditions is satisfied.
1331 bool KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001332
1333 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1334 /// opposed to objc_retain calls).
1335 bool IsRetainBlock;
1336
1337 /// IsTailCallRelease - True of the objc_release calls are all marked
1338 /// with the "tail" keyword.
1339 bool IsTailCallRelease;
1340
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001341 /// Partial - True of we've seen an opportunity for partial RR elimination,
1342 /// such as pushing calls into a CFG triangle or into one side of a
1343 /// CFG diamond.
Dan Gohmanafee0272011-12-12 18:30:26 +00001344 /// TODO: Consider moving this to PtrState.
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001345 bool Partial;
1346
John McCall9fbd3182011-06-15 23:37:01 +00001347 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1348 /// a clang.imprecise_release tag, this is the metadata tag.
1349 MDNode *ReleaseMetadata;
1350
1351 /// Calls - For a top-down sequence, the set of objc_retains or
1352 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1353 SmallPtrSet<Instruction *, 2> Calls;
1354
1355 /// ReverseInsertPts - The set of optimal insert positions for
1356 /// moving calls in the opposite sequence.
1357 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1358
1359 RRInfo() :
Dan Gohman79522dc2012-01-13 00:39:07 +00001360 KnownSafe(false), IsRetainBlock(false),
Dan Gohmana974bea2011-10-17 22:53:25 +00001361 IsTailCallRelease(false), Partial(false),
John McCall9fbd3182011-06-15 23:37:01 +00001362 ReleaseMetadata(0) {}
1363
1364 void clear();
1365 };
1366}
1367
1368void RRInfo::clear() {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001369 KnownSafe = false;
John McCall9fbd3182011-06-15 23:37:01 +00001370 IsRetainBlock = false;
1371 IsTailCallRelease = false;
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001372 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001373 ReleaseMetadata = 0;
1374 Calls.clear();
1375 ReverseInsertPts.clear();
1376}
1377
1378namespace {
1379 /// PtrState - This class summarizes several per-pointer runtime properties
1380 /// which are propogated through the flow graph.
1381 class PtrState {
1382 /// RefCount - The known minimum number of reference count increments.
1383 unsigned RefCount;
1384
Dan Gohmane6d5e882011-08-19 00:26:36 +00001385 /// NestCount - The known minimum level of retain+release nesting.
1386 unsigned NestCount;
1387
John McCall9fbd3182011-06-15 23:37:01 +00001388 /// Seq - The current position in the sequence.
1389 Sequence Seq;
1390
1391 public:
1392 /// RRI - Unidirectional information about the current sequence.
1393 /// TODO: Encapsulate this better.
1394 RRInfo RRI;
1395
Dan Gohmane6d5e882011-08-19 00:26:36 +00001396 PtrState() : RefCount(0), NestCount(0), Seq(S_None) {}
John McCall9fbd3182011-06-15 23:37:01 +00001397
Dan Gohmana7f7db22011-08-12 00:26:31 +00001398 void SetAtLeastOneRefCount() {
1399 if (RefCount == 0) RefCount = 1;
1400 }
1401
John McCall9fbd3182011-06-15 23:37:01 +00001402 void IncrementRefCount() {
1403 if (RefCount != UINT_MAX) ++RefCount;
1404 }
1405
1406 void DecrementRefCount() {
1407 if (RefCount != 0) --RefCount;
1408 }
1409
John McCall9fbd3182011-06-15 23:37:01 +00001410 bool IsKnownIncremented() const {
1411 return RefCount > 0;
1412 }
1413
Dan Gohmane6d5e882011-08-19 00:26:36 +00001414 void IncrementNestCount() {
1415 if (NestCount != UINT_MAX) ++NestCount;
1416 }
1417
1418 void DecrementNestCount() {
1419 if (NestCount != 0) --NestCount;
1420 }
1421
1422 bool IsKnownNested() const {
1423 return NestCount > 0;
1424 }
1425
John McCall9fbd3182011-06-15 23:37:01 +00001426 void SetSeq(Sequence NewSeq) {
1427 Seq = NewSeq;
1428 }
1429
John McCall9fbd3182011-06-15 23:37:01 +00001430 Sequence GetSeq() const {
1431 return Seq;
1432 }
1433
1434 void ClearSequenceProgress() {
1435 Seq = S_None;
1436 RRI.clear();
1437 }
1438
1439 void Merge(const PtrState &Other, bool TopDown);
1440 };
1441}
1442
1443void
1444PtrState::Merge(const PtrState &Other, bool TopDown) {
1445 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
1446 RefCount = std::min(RefCount, Other.RefCount);
Dan Gohmane6d5e882011-08-19 00:26:36 +00001447 NestCount = std::min(NestCount, Other.NestCount);
John McCall9fbd3182011-06-15 23:37:01 +00001448
1449 // We can't merge a plain objc_retain with an objc_retainBlock.
1450 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1451 Seq = S_None;
1452
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001453 // If we're not in a sequence (anymore), drop all associated state.
John McCall9fbd3182011-06-15 23:37:01 +00001454 if (Seq == S_None) {
1455 RRI.clear();
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001456 } else if (RRI.Partial || Other.RRI.Partial) {
1457 // If we're doing a merge on a path that's previously seen a partial
1458 // merge, conservatively drop the sequence, to avoid doing partial
1459 // RR elimination. If the branch predicates for the two merge differ,
1460 // mixing them is unsafe.
1461 Seq = S_None;
1462 RRI.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001463 } else {
1464 // Conservatively merge the ReleaseMetadata information.
1465 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1466 RRI.ReleaseMetadata = 0;
1467
Dan Gohmane6d5e882011-08-19 00:26:36 +00001468 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001469 RRI.IsTailCallRelease = RRI.IsTailCallRelease && Other.RRI.IsTailCallRelease;
1470 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001471
1472 // Merge the insert point sets. If there are any differences,
1473 // that makes this a partial merge.
1474 RRI.Partial = RRI.ReverseInsertPts.size() !=
1475 Other.RRI.ReverseInsertPts.size();
1476 for (SmallPtrSet<Instruction *, 2>::const_iterator
1477 I = Other.RRI.ReverseInsertPts.begin(),
1478 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
1479 RRI.Partial |= RRI.ReverseInsertPts.insert(*I);
John McCall9fbd3182011-06-15 23:37:01 +00001480 }
1481}
1482
1483namespace {
1484 /// BBState - Per-BasicBlock state.
1485 class BBState {
1486 /// TopDownPathCount - The number of unique control paths from the entry
1487 /// which can reach this block.
1488 unsigned TopDownPathCount;
1489
1490 /// BottomUpPathCount - The number of unique control paths to exits
1491 /// from this block.
1492 unsigned BottomUpPathCount;
1493
1494 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1495 typedef MapVector<const Value *, PtrState> MapTy;
1496
1497 /// PerPtrTopDown - The top-down traversal uses this to record information
1498 /// known about a pointer at the bottom of each block.
1499 MapTy PerPtrTopDown;
1500
1501 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1502 /// known about a pointer at the top of each block.
1503 MapTy PerPtrBottomUp;
1504
1505 public:
1506 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1507
1508 typedef MapTy::iterator ptr_iterator;
1509 typedef MapTy::const_iterator ptr_const_iterator;
1510
1511 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1512 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1513 ptr_const_iterator top_down_ptr_begin() const {
1514 return PerPtrTopDown.begin();
1515 }
1516 ptr_const_iterator top_down_ptr_end() const {
1517 return PerPtrTopDown.end();
1518 }
1519
1520 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1521 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1522 ptr_const_iterator bottom_up_ptr_begin() const {
1523 return PerPtrBottomUp.begin();
1524 }
1525 ptr_const_iterator bottom_up_ptr_end() const {
1526 return PerPtrBottomUp.end();
1527 }
1528
1529 /// SetAsEntry - Mark this block as being an entry block, which has one
1530 /// path from the entry by definition.
1531 void SetAsEntry() { TopDownPathCount = 1; }
1532
1533 /// SetAsExit - Mark this block as being an exit block, which has one
1534 /// path to an exit by definition.
1535 void SetAsExit() { BottomUpPathCount = 1; }
1536
1537 PtrState &getPtrTopDownState(const Value *Arg) {
1538 return PerPtrTopDown[Arg];
1539 }
1540
1541 PtrState &getPtrBottomUpState(const Value *Arg) {
1542 return PerPtrBottomUp[Arg];
1543 }
1544
1545 void clearBottomUpPointers() {
Evan Chenga81388f2011-08-04 18:40:26 +00001546 PerPtrBottomUp.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001547 }
1548
1549 void clearTopDownPointers() {
1550 PerPtrTopDown.clear();
1551 }
1552
1553 void InitFromPred(const BBState &Other);
1554 void InitFromSucc(const BBState &Other);
1555 void MergePred(const BBState &Other);
1556 void MergeSucc(const BBState &Other);
1557
1558 /// GetAllPathCount - Return the number of possible unique paths from an
1559 /// entry to an exit which pass through this block. This is only valid
1560 /// after both the top-down and bottom-up traversals are complete.
1561 unsigned GetAllPathCount() const {
1562 return TopDownPathCount * BottomUpPathCount;
1563 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00001564
1565 /// IsVisitedTopDown - Test whether the block for this BBState has been
1566 /// visited by the top-down portion of the algorithm.
1567 bool isVisitedTopDown() const {
1568 return TopDownPathCount != 0;
1569 }
John McCall9fbd3182011-06-15 23:37:01 +00001570 };
1571}
1572
1573void BBState::InitFromPred(const BBState &Other) {
1574 PerPtrTopDown = Other.PerPtrTopDown;
1575 TopDownPathCount = Other.TopDownPathCount;
1576}
1577
1578void BBState::InitFromSucc(const BBState &Other) {
1579 PerPtrBottomUp = Other.PerPtrBottomUp;
1580 BottomUpPathCount = Other.BottomUpPathCount;
1581}
1582
1583/// MergePred - The top-down traversal uses this to merge information about
1584/// predecessors to form the initial state for a new block.
1585void BBState::MergePred(const BBState &Other) {
1586 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1587 // loop backedge. Loop backedges are special.
1588 TopDownPathCount += Other.TopDownPathCount;
1589
1590 // For each entry in the other set, if our set has an entry with the same key,
1591 // merge the entries. Otherwise, copy the entry and merge it with an empty
1592 // entry.
1593 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1594 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1595 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1596 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1597 /*TopDown=*/true);
1598 }
1599
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001600 // For each entry in our set, if the other set doesn't have an entry with the
John McCall9fbd3182011-06-15 23:37:01 +00001601 // same key, force it to merge with an empty entry.
1602 for (ptr_iterator MI = top_down_ptr_begin(),
1603 ME = top_down_ptr_end(); MI != ME; ++MI)
1604 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1605 MI->second.Merge(PtrState(), /*TopDown=*/true);
1606}
1607
1608/// MergeSucc - The bottom-up traversal uses this to merge information about
1609/// successors to form the initial state for a new block.
1610void BBState::MergeSucc(const BBState &Other) {
1611 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1612 // loop backedge. Loop backedges are special.
1613 BottomUpPathCount += Other.BottomUpPathCount;
1614
1615 // For each entry in the other set, if our set has an entry with the
1616 // same key, merge the entries. Otherwise, copy the entry and merge
1617 // it with an empty entry.
1618 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1619 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1620 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1621 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1622 /*TopDown=*/false);
1623 }
1624
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001625 // For each entry in our set, if the other set doesn't have an entry
John McCall9fbd3182011-06-15 23:37:01 +00001626 // with the same key, force it to merge with an empty entry.
1627 for (ptr_iterator MI = bottom_up_ptr_begin(),
1628 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1629 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1630 MI->second.Merge(PtrState(), /*TopDown=*/false);
1631}
1632
1633namespace {
1634 /// ObjCARCOpt - The main ARC optimization pass.
1635 class ObjCARCOpt : public FunctionPass {
1636 bool Changed;
1637 ProvenanceAnalysis PA;
1638
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001639 /// Run - A flag indicating whether this optimization pass should run.
1640 bool Run;
1641
John McCall9fbd3182011-06-15 23:37:01 +00001642 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1643 /// functions, for use in creating calls to them. These are initialized
1644 /// lazily to avoid cluttering up the Module with unused declarations.
1645 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
Dan Gohman44280692011-07-22 22:29:21 +00001646 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
John McCall9fbd3182011-06-15 23:37:01 +00001647
1648 /// UsedInThisFunciton - Flags which determine whether each of the
1649 /// interesting runtine functions is in fact used in the current function.
1650 unsigned UsedInThisFunction;
1651
1652 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1653 /// metadata.
1654 unsigned ImpreciseReleaseMDKind;
1655
Dan Gohman62e5b402011-12-12 18:20:00 +00001656 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
Dan Gohmana974bea2011-10-17 22:53:25 +00001657 /// metadata.
1658 unsigned CopyOnEscapeMDKind;
1659
Dan Gohmandbe266b2012-02-17 18:59:53 +00001660 /// NoObjCARCExceptionsMDKind - The Metadata Kind for
1661 /// clang.arc.no_objc_arc_exceptions metadata.
1662 unsigned NoObjCARCExceptionsMDKind;
1663
John McCall9fbd3182011-06-15 23:37:01 +00001664 Constant *getRetainRVCallee(Module *M);
1665 Constant *getAutoreleaseRVCallee(Module *M);
1666 Constant *getReleaseCallee(Module *M);
1667 Constant *getRetainCallee(Module *M);
Dan Gohman44280692011-07-22 22:29:21 +00001668 Constant *getRetainBlockCallee(Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001669 Constant *getAutoreleaseCallee(Module *M);
1670
Dan Gohman79522dc2012-01-13 00:39:07 +00001671 bool IsRetainBlockOptimizable(const Instruction *Inst);
1672
John McCall9fbd3182011-06-15 23:37:01 +00001673 void OptimizeRetainCall(Function &F, Instruction *Retain);
1674 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1675 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1676 void OptimizeIndividualCalls(Function &F);
1677
1678 void CheckForCFGHazards(const BasicBlock *BB,
1679 DenseMap<const BasicBlock *, BBState> &BBStates,
1680 BBState &MyStates) const;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001681 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00001682 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001683 MapVector<Value *, RRInfo> &Retains,
1684 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001685 bool VisitBottomUp(BasicBlock *BB,
1686 DenseMap<const BasicBlock *, BBState> &BBStates,
1687 MapVector<Value *, RRInfo> &Retains);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001688 bool VisitInstructionTopDown(Instruction *Inst,
1689 DenseMap<Value *, RRInfo> &Releases,
1690 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001691 bool VisitTopDown(BasicBlock *BB,
1692 DenseMap<const BasicBlock *, BBState> &BBStates,
1693 DenseMap<Value *, RRInfo> &Releases);
1694 bool Visit(Function &F,
1695 DenseMap<const BasicBlock *, BBState> &BBStates,
1696 MapVector<Value *, RRInfo> &Retains,
1697 DenseMap<Value *, RRInfo> &Releases);
1698
1699 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1700 MapVector<Value *, RRInfo> &Retains,
1701 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00001702 SmallVectorImpl<Instruction *> &DeadInsts,
1703 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001704
1705 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1706 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00001707 DenseMap<Value *, RRInfo> &Releases,
1708 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001709
1710 void OptimizeWeakCalls(Function &F);
1711
1712 bool OptimizeSequences(Function &F);
1713
1714 void OptimizeReturns(Function &F);
1715
1716 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1717 virtual bool doInitialization(Module &M);
1718 virtual bool runOnFunction(Function &F);
1719 virtual void releaseMemory();
1720
1721 public:
1722 static char ID;
1723 ObjCARCOpt() : FunctionPass(ID) {
1724 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1725 }
1726 };
1727}
1728
1729char ObjCARCOpt::ID = 0;
1730INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1731 "objc-arc", "ObjC ARC optimization", false, false)
1732INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1733INITIALIZE_PASS_END(ObjCARCOpt,
1734 "objc-arc", "ObjC ARC optimization", false, false)
1735
1736Pass *llvm::createObjCARCOptPass() {
1737 return new ObjCARCOpt();
1738}
1739
1740void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1741 AU.addRequired<ObjCARCAliasAnalysis>();
1742 AU.addRequired<AliasAnalysis>();
1743 // ARC optimization doesn't currently split critical edges.
1744 AU.setPreservesCFG();
1745}
1746
Dan Gohman79522dc2012-01-13 00:39:07 +00001747bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1748 // Without the magic metadata tag, we have to assume this might be an
1749 // objc_retainBlock call inserted to convert a block pointer to an id,
1750 // in which case it really is needed.
1751 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1752 return false;
1753
1754 // If the pointer "escapes" (not including being used in a call),
1755 // the copy may be needed.
1756 if (DoesObjCBlockEscape(Inst))
1757 return false;
1758
1759 // Otherwise, it's not needed.
1760 return true;
1761}
1762
John McCall9fbd3182011-06-15 23:37:01 +00001763Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1764 if (!RetainRVCallee) {
1765 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001766 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1767 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001768 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001769 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00001770 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1771 AttrListPtr Attributes;
1772 Attributes.addAttr(~0u, Attribute::NoUnwind);
1773 RetainRVCallee =
1774 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1775 Attributes);
1776 }
1777 return RetainRVCallee;
1778}
1779
1780Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1781 if (!AutoreleaseRVCallee) {
1782 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001783 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1784 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001785 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001786 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00001787 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1788 AttrListPtr Attributes;
1789 Attributes.addAttr(~0u, Attribute::NoUnwind);
1790 AutoreleaseRVCallee =
1791 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1792 Attributes);
1793 }
1794 return AutoreleaseRVCallee;
1795}
1796
1797Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1798 if (!ReleaseCallee) {
1799 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001800 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001801 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1802 AttrListPtr Attributes;
1803 Attributes.addAttr(~0u, Attribute::NoUnwind);
1804 ReleaseCallee =
1805 M->getOrInsertFunction(
1806 "objc_release",
1807 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1808 Attributes);
1809 }
1810 return ReleaseCallee;
1811}
1812
1813Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1814 if (!RetainCallee) {
1815 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001816 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001817 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1818 AttrListPtr Attributes;
1819 Attributes.addAttr(~0u, Attribute::NoUnwind);
1820 RetainCallee =
1821 M->getOrInsertFunction(
1822 "objc_retain",
1823 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1824 Attributes);
1825 }
1826 return RetainCallee;
1827}
1828
Dan Gohman44280692011-07-22 22:29:21 +00001829Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1830 if (!RetainBlockCallee) {
1831 LLVMContext &C = M->getContext();
1832 std::vector<Type *> Params;
1833 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1834 AttrListPtr Attributes;
Dan Gohman1d2fd752011-09-14 18:33:34 +00001835 // objc_retainBlock is not nounwind because it calls user copy constructors
1836 // which could theoretically throw.
Dan Gohman44280692011-07-22 22:29:21 +00001837 RetainBlockCallee =
1838 M->getOrInsertFunction(
1839 "objc_retainBlock",
1840 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1841 Attributes);
1842 }
1843 return RetainBlockCallee;
1844}
1845
John McCall9fbd3182011-06-15 23:37:01 +00001846Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1847 if (!AutoreleaseCallee) {
1848 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001849 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001850 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1851 AttrListPtr Attributes;
1852 Attributes.addAttr(~0u, Attribute::NoUnwind);
1853 AutoreleaseCallee =
1854 M->getOrInsertFunction(
1855 "objc_autorelease",
1856 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1857 Attributes);
1858 }
1859 return AutoreleaseCallee;
1860}
1861
1862/// CanAlterRefCount - Test whether the given instruction can result in a
1863/// reference count modification (positive or negative) for the pointer's
1864/// object.
1865static bool
1866CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1867 ProvenanceAnalysis &PA, InstructionClass Class) {
1868 switch (Class) {
1869 case IC_Autorelease:
1870 case IC_AutoreleaseRV:
1871 case IC_User:
1872 // These operations never directly modify a reference count.
1873 return false;
1874 default: break;
1875 }
1876
1877 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1878 assert(CS && "Only calls can alter reference counts!");
1879
1880 // See if AliasAnalysis can help us with the call.
1881 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1882 if (AliasAnalysis::onlyReadsMemory(MRB))
1883 return false;
1884 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1885 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1886 I != E; ++I) {
1887 const Value *Op = *I;
1888 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1889 return true;
1890 }
1891 return false;
1892 }
1893
1894 // Assume the worst.
1895 return true;
1896}
1897
1898/// CanUse - Test whether the given instruction can "use" the given pointer's
1899/// object in a way that requires the reference count to be positive.
1900static bool
1901CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1902 InstructionClass Class) {
1903 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1904 if (Class == IC_Call)
1905 return false;
1906
1907 // Consider various instructions which may have pointer arguments which are
1908 // not "uses".
1909 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1910 // Comparing a pointer with null, or any other constant, isn't really a use,
1911 // because we don't care what the pointer points to, or about the values
1912 // of any other dynamic reference-counted pointers.
1913 if (!IsPotentialUse(ICI->getOperand(1)))
1914 return false;
1915 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1916 // For calls, just check the arguments (and not the callee operand).
1917 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1918 OE = CS.arg_end(); OI != OE; ++OI) {
1919 const Value *Op = *OI;
1920 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1921 return true;
1922 }
1923 return false;
1924 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1925 // Special-case stores, because we don't care about the stored value, just
1926 // the store address.
1927 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1928 // If we can't tell what the underlying object was, assume there is a
1929 // dependence.
1930 return IsPotentialUse(Op) && PA.related(Op, Ptr);
1931 }
1932
1933 // Check each operand for a match.
1934 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1935 OI != OE; ++OI) {
1936 const Value *Op = *OI;
1937 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1938 return true;
1939 }
1940 return false;
1941}
1942
1943/// CanInterruptRV - Test whether the given instruction can autorelease
1944/// any pointer or cause an autoreleasepool pop.
1945static bool
1946CanInterruptRV(InstructionClass Class) {
1947 switch (Class) {
1948 case IC_AutoreleasepoolPop:
1949 case IC_CallOrUser:
1950 case IC_Call:
1951 case IC_Autorelease:
1952 case IC_AutoreleaseRV:
1953 case IC_FusedRetainAutorelease:
1954 case IC_FusedRetainAutoreleaseRV:
1955 return true;
1956 default:
1957 return false;
1958 }
1959}
1960
1961namespace {
1962 /// DependenceKind - There are several kinds of dependence-like concepts in
1963 /// use here.
1964 enum DependenceKind {
1965 NeedsPositiveRetainCount,
Dan Gohman511568d2012-04-13 00:59:57 +00001966 AutoreleasePoolBoundary,
John McCall9fbd3182011-06-15 23:37:01 +00001967 CanChangeRetainCount,
1968 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1969 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1970 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1971 };
1972}
1973
1974/// Depends - Test if there can be dependencies on Inst through Arg. This
1975/// function only tests dependencies relevant for removing pairs of calls.
1976static bool
1977Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1978 ProvenanceAnalysis &PA) {
1979 // If we've reached the definition of Arg, stop.
1980 if (Inst == Arg)
1981 return true;
1982
1983 switch (Flavor) {
1984 case NeedsPositiveRetainCount: {
1985 InstructionClass Class = GetInstructionClass(Inst);
1986 switch (Class) {
1987 case IC_AutoreleasepoolPop:
1988 case IC_AutoreleasepoolPush:
1989 case IC_None:
1990 return false;
1991 default:
1992 return CanUse(Inst, Arg, PA, Class);
1993 }
1994 }
1995
Dan Gohman511568d2012-04-13 00:59:57 +00001996 case AutoreleasePoolBoundary: {
1997 InstructionClass Class = GetInstructionClass(Inst);
1998 switch (Class) {
1999 case IC_AutoreleasepoolPop:
2000 case IC_AutoreleasepoolPush:
2001 // These mark the end and begin of an autorelease pool scope.
2002 return true;
2003 default:
2004 // Nothing else does this.
2005 return false;
2006 }
2007 }
2008
John McCall9fbd3182011-06-15 23:37:01 +00002009 case CanChangeRetainCount: {
2010 InstructionClass Class = GetInstructionClass(Inst);
2011 switch (Class) {
2012 case IC_AutoreleasepoolPop:
2013 // Conservatively assume this can decrement any count.
2014 return true;
2015 case IC_AutoreleasepoolPush:
2016 case IC_None:
2017 return false;
2018 default:
2019 return CanAlterRefCount(Inst, Arg, PA, Class);
2020 }
2021 }
2022
2023 case RetainAutoreleaseDep:
2024 switch (GetBasicInstructionClass(Inst)) {
2025 case IC_AutoreleasepoolPop:
Dan Gohman511568d2012-04-13 00:59:57 +00002026 case IC_AutoreleasepoolPush:
John McCall9fbd3182011-06-15 23:37:01 +00002027 // Don't merge an objc_autorelease with an objc_retain inside a different
2028 // autoreleasepool scope.
2029 return true;
2030 case IC_Retain:
2031 case IC_RetainRV:
2032 // Check for a retain of the same pointer for merging.
2033 return GetObjCArg(Inst) == Arg;
2034 default:
2035 // Nothing else matters for objc_retainAutorelease formation.
2036 return false;
2037 }
John McCall9fbd3182011-06-15 23:37:01 +00002038
2039 case RetainAutoreleaseRVDep: {
2040 InstructionClass Class = GetBasicInstructionClass(Inst);
2041 switch (Class) {
2042 case IC_Retain:
2043 case IC_RetainRV:
2044 // Check for a retain of the same pointer for merging.
2045 return GetObjCArg(Inst) == Arg;
2046 default:
2047 // Anything that can autorelease interrupts
2048 // retainAutoreleaseReturnValue formation.
2049 return CanInterruptRV(Class);
2050 }
John McCall9fbd3182011-06-15 23:37:01 +00002051 }
2052
2053 case RetainRVDep:
2054 return CanInterruptRV(GetBasicInstructionClass(Inst));
2055 }
2056
2057 llvm_unreachable("Invalid dependence flavor");
John McCall9fbd3182011-06-15 23:37:01 +00002058}
2059
2060/// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2061/// find local and non-local dependencies on Arg.
2062/// TODO: Cache results?
2063static void
2064FindDependencies(DependenceKind Flavor,
2065 const Value *Arg,
2066 BasicBlock *StartBB, Instruction *StartInst,
2067 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2068 SmallPtrSet<const BasicBlock *, 4> &Visited,
2069 ProvenanceAnalysis &PA) {
2070 BasicBlock::iterator StartPos = StartInst;
2071
2072 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2073 Worklist.push_back(std::make_pair(StartBB, StartPos));
2074 do {
2075 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2076 Worklist.pop_back_val();
2077 BasicBlock *LocalStartBB = Pair.first;
2078 BasicBlock::iterator LocalStartPos = Pair.second;
2079 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2080 for (;;) {
2081 if (LocalStartPos == StartBBBegin) {
2082 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2083 if (PI == PE)
2084 // If we've reached the function entry, produce a null dependence.
2085 DependingInstructions.insert(0);
2086 else
2087 // Add the predecessors to the worklist.
2088 do {
2089 BasicBlock *PredBB = *PI;
2090 if (Visited.insert(PredBB))
2091 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2092 } while (++PI != PE);
2093 break;
2094 }
2095
2096 Instruction *Inst = --LocalStartPos;
2097 if (Depends(Flavor, Inst, Arg, PA)) {
2098 DependingInstructions.insert(Inst);
2099 break;
2100 }
2101 }
2102 } while (!Worklist.empty());
2103
2104 // Determine whether the original StartBB post-dominates all of the blocks we
2105 // visited. If not, insert a sentinal indicating that most optimizations are
2106 // not safe.
2107 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2108 E = Visited.end(); I != E; ++I) {
2109 const BasicBlock *BB = *I;
2110 if (BB == StartBB)
2111 continue;
2112 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2113 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2114 const BasicBlock *Succ = *SI;
2115 if (Succ != StartBB && !Visited.count(Succ)) {
2116 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2117 return;
2118 }
2119 }
2120 }
2121}
2122
2123static bool isNullOrUndef(const Value *V) {
2124 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2125}
2126
2127static bool isNoopInstruction(const Instruction *I) {
2128 return isa<BitCastInst>(I) ||
2129 (isa<GetElementPtrInst>(I) &&
2130 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2131}
2132
2133/// OptimizeRetainCall - Turn objc_retain into
2134/// objc_retainAutoreleasedReturnValue if the operand is a return value.
2135void
2136ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
2137 CallSite CS(GetObjCArg(Retain));
2138 Instruction *Call = CS.getInstruction();
2139 if (!Call) return;
2140 if (Call->getParent() != Retain->getParent()) return;
2141
2142 // Check that the call is next to the retain.
2143 BasicBlock::iterator I = Call;
2144 ++I;
2145 while (isNoopInstruction(I)) ++I;
2146 if (&*I != Retain)
2147 return;
2148
2149 // Turn it to an objc_retainAutoreleasedReturnValue..
2150 Changed = true;
2151 ++NumPeeps;
2152 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2153}
2154
2155/// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
2156/// objc_retain if the operand is not a return value. Or, if it can be
2157/// paired with an objc_autoreleaseReturnValue, delete the pair and
2158/// return true.
2159bool
2160ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002161 // Check for the argument being from an immediately preceding call or invoke.
John McCall9fbd3182011-06-15 23:37:01 +00002162 Value *Arg = GetObjCArg(RetainRV);
2163 CallSite CS(Arg);
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002164 if (Instruction *Call = CS.getInstruction()) {
John McCall9fbd3182011-06-15 23:37:01 +00002165 if (Call->getParent() == RetainRV->getParent()) {
2166 BasicBlock::iterator I = Call;
2167 ++I;
2168 while (isNoopInstruction(I)) ++I;
2169 if (&*I == RetainRV)
2170 return false;
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002171 } else if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
2172 BasicBlock *RetainRVParent = RetainRV->getParent();
2173 if (II->getNormalDest() == RetainRVParent) {
2174 BasicBlock::iterator I = RetainRVParent->begin();
2175 while (isNoopInstruction(I)) ++I;
2176 if (&*I == RetainRV)
2177 return false;
2178 }
John McCall9fbd3182011-06-15 23:37:01 +00002179 }
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002180 }
John McCall9fbd3182011-06-15 23:37:01 +00002181
2182 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2183 // pointer. In this case, we can delete the pair.
2184 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2185 if (I != Begin) {
2186 do --I; while (I != Begin && isNoopInstruction(I));
2187 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2188 GetObjCArg(I) == Arg) {
2189 Changed = true;
2190 ++NumPeeps;
2191 EraseInstruction(I);
2192 EraseInstruction(RetainRV);
2193 return true;
2194 }
2195 }
2196
2197 // Turn it to a plain objc_retain.
2198 Changed = true;
2199 ++NumPeeps;
2200 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2201 return false;
2202}
2203
2204/// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2205/// objc_autorelease if the result is not used as a return value.
2206void
2207ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
2208 // Check for a return of the pointer value.
2209 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman126a54f2011-08-12 00:36:31 +00002210 SmallVector<const Value *, 2> Users;
2211 Users.push_back(Ptr);
2212 do {
2213 Ptr = Users.pop_back_val();
2214 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2215 UI != UE; ++UI) {
2216 const User *I = *UI;
2217 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2218 return;
2219 if (isa<BitCastInst>(I))
2220 Users.push_back(I);
2221 }
2222 } while (!Users.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002223
2224 Changed = true;
2225 ++NumPeeps;
2226 cast<CallInst>(AutoreleaseRV)->
2227 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2228}
2229
2230/// OptimizeIndividualCalls - Visit each call, one at a time, and make
2231/// simplifications without doing any additional analysis.
2232void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2233 // Reset all the flags in preparation for recomputing them.
2234 UsedInThisFunction = 0;
2235
2236 // Visit all objc_* calls in F.
2237 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2238 Instruction *Inst = &*I++;
2239 InstructionClass Class = GetBasicInstructionClass(Inst);
2240
2241 switch (Class) {
2242 default: break;
2243
2244 // Delete no-op casts. These function calls have special semantics, but
2245 // the semantics are entirely implemented via lowering in the front-end,
2246 // so by the time they reach the optimizer, they are just no-op calls
2247 // which return their argument.
2248 //
2249 // There are gray areas here, as the ability to cast reference-counted
2250 // pointers to raw void* and back allows code to break ARC assumptions,
2251 // however these are currently considered to be unimportant.
2252 case IC_NoopCast:
2253 Changed = true;
2254 ++NumNoops;
2255 EraseInstruction(Inst);
2256 continue;
2257
2258 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2259 case IC_StoreWeak:
2260 case IC_LoadWeak:
2261 case IC_LoadWeakRetained:
2262 case IC_InitWeak:
2263 case IC_DestroyWeak: {
2264 CallInst *CI = cast<CallInst>(Inst);
2265 if (isNullOrUndef(CI->getArgOperand(0))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002266 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002267 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2268 Constant::getNullValue(Ty),
2269 CI);
2270 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2271 CI->eraseFromParent();
2272 continue;
2273 }
2274 break;
2275 }
2276 case IC_CopyWeak:
2277 case IC_MoveWeak: {
2278 CallInst *CI = cast<CallInst>(Inst);
2279 if (isNullOrUndef(CI->getArgOperand(0)) ||
2280 isNullOrUndef(CI->getArgOperand(1))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002281 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002282 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2283 Constant::getNullValue(Ty),
2284 CI);
2285 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2286 CI->eraseFromParent();
2287 continue;
2288 }
2289 break;
2290 }
2291 case IC_Retain:
2292 OptimizeRetainCall(F, Inst);
2293 break;
2294 case IC_RetainRV:
2295 if (OptimizeRetainRVCall(F, Inst))
2296 continue;
2297 break;
2298 case IC_AutoreleaseRV:
2299 OptimizeAutoreleaseRVCall(F, Inst);
2300 break;
2301 }
2302
2303 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2304 if (IsAutorelease(Class) && Inst->use_empty()) {
2305 CallInst *Call = cast<CallInst>(Inst);
2306 const Value *Arg = Call->getArgOperand(0);
2307 Arg = FindSingleUseIdentifiedObject(Arg);
2308 if (Arg) {
2309 Changed = true;
2310 ++NumAutoreleases;
2311
2312 // Create the declaration lazily.
2313 LLVMContext &C = Inst->getContext();
2314 CallInst *NewCall =
2315 CallInst::Create(getReleaseCallee(F.getParent()),
2316 Call->getArgOperand(0), "", Call);
2317 NewCall->setMetadata(ImpreciseReleaseMDKind,
2318 MDNode::get(C, ArrayRef<Value *>()));
2319 EraseInstruction(Call);
2320 Inst = NewCall;
2321 Class = IC_Release;
2322 }
2323 }
2324
2325 // For functions which can never be passed stack arguments, add
2326 // a tail keyword.
2327 if (IsAlwaysTail(Class)) {
2328 Changed = true;
2329 cast<CallInst>(Inst)->setTailCall();
2330 }
2331
2332 // Set nounwind as needed.
2333 if (IsNoThrow(Class)) {
2334 Changed = true;
2335 cast<CallInst>(Inst)->setDoesNotThrow();
2336 }
2337
2338 if (!IsNoopOnNull(Class)) {
2339 UsedInThisFunction |= 1 << Class;
2340 continue;
2341 }
2342
2343 const Value *Arg = GetObjCArg(Inst);
2344
2345 // ARC calls with null are no-ops. Delete them.
2346 if (isNullOrUndef(Arg)) {
2347 Changed = true;
2348 ++NumNoops;
2349 EraseInstruction(Inst);
2350 continue;
2351 }
2352
2353 // Keep track of which of retain, release, autorelease, and retain_block
2354 // are actually present in this function.
2355 UsedInThisFunction |= 1 << Class;
2356
2357 // If Arg is a PHI, and one or more incoming values to the
2358 // PHI are null, and the call is control-equivalent to the PHI, and there
2359 // are no relevant side effects between the PHI and the call, the call
2360 // could be pushed up to just those paths with non-null incoming values.
2361 // For now, don't bother splitting critical edges for this.
2362 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2363 Worklist.push_back(std::make_pair(Inst, Arg));
2364 do {
2365 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2366 Inst = Pair.first;
2367 Arg = Pair.second;
2368
2369 const PHINode *PN = dyn_cast<PHINode>(Arg);
2370 if (!PN) continue;
2371
2372 // Determine if the PHI has any null operands, or any incoming
2373 // critical edges.
2374 bool HasNull = false;
2375 bool HasCriticalEdges = false;
2376 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2377 Value *Incoming =
2378 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2379 if (isNullOrUndef(Incoming))
2380 HasNull = true;
2381 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2382 .getNumSuccessors() != 1) {
2383 HasCriticalEdges = true;
2384 break;
2385 }
2386 }
2387 // If we have null operands and no critical edges, optimize.
2388 if (!HasCriticalEdges && HasNull) {
2389 SmallPtrSet<Instruction *, 4> DependingInstructions;
2390 SmallPtrSet<const BasicBlock *, 4> Visited;
2391
2392 // Check that there is nothing that cares about the reference
2393 // count between the call and the phi.
Dan Gohman511568d2012-04-13 00:59:57 +00002394 switch (Class) {
2395 case IC_Retain:
2396 case IC_RetainBlock:
2397 // These can always be moved up.
2398 break;
2399 case IC_Release:
2400 // These can't be moved across things that care about the retain count.
2401 FindDependencies(NeedsPositiveRetainCount, Arg,
2402 Inst->getParent(), Inst,
2403 DependingInstructions, Visited, PA);
2404 break;
2405 case IC_Autorelease:
2406 // These can't be moved across autorelease pool scope boundaries.
2407 FindDependencies(AutoreleasePoolBoundary, Arg,
2408 Inst->getParent(), Inst,
2409 DependingInstructions, Visited, PA);
2410 break;
2411 case IC_RetainRV:
2412 case IC_AutoreleaseRV:
2413 // Don't move these; the RV optimization depends on the autoreleaseRV
2414 // being tail called, and the retainRV being immediately after a call
2415 // (which might still happen if we get lucky with codegen layout, but
2416 // it's not worth taking the chance).
2417 continue;
2418 default:
2419 llvm_unreachable("Invalid dependence flavor");
2420 }
2421
John McCall9fbd3182011-06-15 23:37:01 +00002422 if (DependingInstructions.size() == 1 &&
2423 *DependingInstructions.begin() == PN) {
2424 Changed = true;
2425 ++NumPartialNoops;
2426 // Clone the call into each predecessor that has a non-null value.
2427 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002428 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002429 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2430 Value *Incoming =
2431 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2432 if (!isNullOrUndef(Incoming)) {
2433 CallInst *Clone = cast<CallInst>(CInst->clone());
2434 Value *Op = PN->getIncomingValue(i);
2435 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2436 if (Op->getType() != ParamTy)
2437 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2438 Clone->setArgOperand(0, Op);
2439 Clone->insertBefore(InsertPos);
2440 Worklist.push_back(std::make_pair(Clone, Incoming));
2441 }
2442 }
2443 // Erase the original call.
2444 EraseInstruction(CInst);
2445 continue;
2446 }
2447 }
2448 } while (!Worklist.empty());
2449 }
2450}
2451
2452/// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2453/// control flow, or other CFG structures where moving code across the edge
2454/// would result in it being executed more.
2455void
2456ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2457 DenseMap<const BasicBlock *, BBState> &BBStates,
2458 BBState &MyStates) const {
2459 // If any top-down local-use or possible-dec has a succ which is earlier in
2460 // the sequence, forget it.
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002461 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCall9fbd3182011-06-15 23:37:01 +00002462 E = MyStates.top_down_ptr_end(); I != E; ++I)
2463 switch (I->second.GetSeq()) {
2464 default: break;
2465 case S_Use: {
2466 const Value *Arg = I->first;
2467 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2468 bool SomeSuccHasSame = false;
2469 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002470 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002471 succ_const_iterator SI(TI), SE(TI, false);
2472
2473 // If the terminator is an invoke marked with the
2474 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2475 // ignored, for ARC purposes.
2476 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2477 --SE;
2478
2479 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002480 Sequence SuccSSeq = S_None;
2481 bool SuccSRRIKnownSafe = false;
2482 // If VisitBottomUp has visited this successor, take what we know about it.
2483 DenseMap<const BasicBlock *, BBState>::iterator BBI = BBStates.find(*SI);
2484 if (BBI != BBStates.end()) {
2485 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2486 SuccSSeq = SuccS.GetSeq();
2487 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2488 }
2489 switch (SuccSSeq) {
John McCall9fbd3182011-06-15 23:37:01 +00002490 case S_None:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002491 case S_CanRelease: {
Dan Gohman70e29682012-03-02 01:26:46 +00002492 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002493 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002494 break;
2495 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002496 continue;
2497 }
John McCall9fbd3182011-06-15 23:37:01 +00002498 case S_Use:
2499 SomeSuccHasSame = true;
2500 break;
2501 case S_Stop:
2502 case S_Release:
2503 case S_MovableRelease:
Dan Gohman70e29682012-03-02 01:26:46 +00002504 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002505 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002506 break;
2507 case S_Retain:
2508 llvm_unreachable("bottom-up pointer in retain state!");
2509 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002510 }
John McCall9fbd3182011-06-15 23:37:01 +00002511 // If the state at the other end of any of the successor edges
2512 // matches the current state, require all edges to match. This
2513 // guards against loops in the middle of a sequence.
2514 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002515 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002516 break;
John McCall9fbd3182011-06-15 23:37:01 +00002517 }
2518 case S_CanRelease: {
2519 const Value *Arg = I->first;
2520 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2521 bool SomeSuccHasSame = false;
2522 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002523 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002524 succ_const_iterator SI(TI), SE(TI, false);
2525
2526 // If the terminator is an invoke marked with the
2527 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2528 // ignored, for ARC purposes.
2529 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2530 --SE;
2531
2532 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002533 Sequence SuccSSeq = S_None;
2534 bool SuccSRRIKnownSafe = false;
2535 // If VisitBottomUp has visited this successor, take what we know about it.
2536 DenseMap<const BasicBlock *, BBState>::iterator BBI = BBStates.find(*SI);
2537 if (BBI != BBStates.end()) {
2538 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2539 SuccSSeq = SuccS.GetSeq();
2540 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2541 }
2542 switch (SuccSSeq) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002543 case S_None: {
Dan Gohman70e29682012-03-02 01:26:46 +00002544 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002545 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002546 break;
2547 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002548 continue;
2549 }
John McCall9fbd3182011-06-15 23:37:01 +00002550 case S_CanRelease:
2551 SomeSuccHasSame = true;
2552 break;
2553 case S_Stop:
2554 case S_Release:
2555 case S_MovableRelease:
2556 case S_Use:
Dan Gohman70e29682012-03-02 01:26:46 +00002557 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002558 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002559 break;
2560 case S_Retain:
2561 llvm_unreachable("bottom-up pointer in retain state!");
2562 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002563 }
John McCall9fbd3182011-06-15 23:37:01 +00002564 // If the state at the other end of any of the successor edges
2565 // matches the current state, require all edges to match. This
2566 // guards against loops in the middle of a sequence.
2567 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002568 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002569 break;
John McCall9fbd3182011-06-15 23:37:01 +00002570 }
2571 }
2572}
2573
2574bool
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002575ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002576 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002577 MapVector<Value *, RRInfo> &Retains,
2578 BBState &MyStates) {
2579 bool NestingDetected = false;
2580 InstructionClass Class = GetInstructionClass(Inst);
2581 const Value *Arg = 0;
2582
2583 switch (Class) {
2584 case IC_Release: {
2585 Arg = GetObjCArg(Inst);
2586
2587 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2588
2589 // If we see two releases in a row on the same pointer. If so, make
2590 // a note, and we'll cicle back to revisit it after we've
2591 // hopefully eliminated the second release, which may allow us to
2592 // eliminate the first release too.
2593 // Theoretically we could implement removal of nested retain+release
2594 // pairs by making PtrState hold a stack of states, but this is
2595 // simple and avoids adding overhead for the non-nested case.
2596 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2597 NestingDetected = true;
2598
2599 S.RRI.clear();
2600
2601 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2602 S.SetSeq(ReleaseMetadata ? S_MovableRelease : S_Release);
2603 S.RRI.ReleaseMetadata = ReleaseMetadata;
2604 S.RRI.KnownSafe = S.IsKnownNested() || S.IsKnownIncremented();
2605 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2606 S.RRI.Calls.insert(Inst);
2607
2608 S.IncrementRefCount();
2609 S.IncrementNestCount();
2610 break;
2611 }
2612 case IC_RetainBlock:
2613 // An objc_retainBlock call with just a use may need to be kept,
2614 // because it may be copying a block from the stack to the heap.
2615 if (!IsRetainBlockOptimizable(Inst))
2616 break;
2617 // FALLTHROUGH
2618 case IC_Retain:
2619 case IC_RetainRV: {
2620 Arg = GetObjCArg(Inst);
2621
2622 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2623 S.DecrementRefCount();
2624 S.SetAtLeastOneRefCount();
2625 S.DecrementNestCount();
2626
2627 switch (S.GetSeq()) {
2628 case S_Stop:
2629 case S_Release:
2630 case S_MovableRelease:
2631 case S_Use:
2632 S.RRI.ReverseInsertPts.clear();
2633 // FALL THROUGH
2634 case S_CanRelease:
2635 // Don't do retain+release tracking for IC_RetainRV, because it's
2636 // better to let it remain as the first instruction after a call.
2637 if (Class != IC_RetainRV) {
2638 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2639 Retains[Inst] = S.RRI;
2640 }
2641 S.ClearSequenceProgress();
2642 break;
2643 case S_None:
2644 break;
2645 case S_Retain:
2646 llvm_unreachable("bottom-up pointer in retain state!");
2647 }
2648 return NestingDetected;
2649 }
2650 case IC_AutoreleasepoolPop:
2651 // Conservatively, clear MyStates for all known pointers.
2652 MyStates.clearBottomUpPointers();
2653 return NestingDetected;
2654 case IC_AutoreleasepoolPush:
2655 case IC_None:
2656 // These are irrelevant.
2657 return NestingDetected;
2658 default:
2659 break;
2660 }
2661
2662 // Consider any other possible effects of this instruction on each
2663 // pointer being tracked.
2664 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2665 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2666 const Value *Ptr = MI->first;
2667 if (Ptr == Arg)
2668 continue; // Handled above.
2669 PtrState &S = MI->second;
2670 Sequence Seq = S.GetSeq();
2671
2672 // Check for possible releases.
2673 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2674 S.DecrementRefCount();
2675 switch (Seq) {
2676 case S_Use:
2677 S.SetSeq(S_CanRelease);
2678 continue;
2679 case S_CanRelease:
2680 case S_Release:
2681 case S_MovableRelease:
2682 case S_Stop:
2683 case S_None:
2684 break;
2685 case S_Retain:
2686 llvm_unreachable("bottom-up pointer in retain state!");
2687 }
2688 }
2689
2690 // Check for possible direct uses.
2691 switch (Seq) {
2692 case S_Release:
2693 case S_MovableRelease:
2694 if (CanUse(Inst, Ptr, PA, Class)) {
2695 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002696 // If this is an invoke instruction, we're scanning it as part of
2697 // one of its successor blocks, since we can't insert code after it
2698 // in its own block, and we don't want to split critical edges.
2699 if (isa<InvokeInst>(Inst))
2700 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2701 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002702 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002703 S.SetSeq(S_Use);
2704 } else if (Seq == S_Release &&
2705 (Class == IC_User || Class == IC_CallOrUser)) {
2706 // Non-movable releases depend on any possible objc pointer use.
2707 S.SetSeq(S_Stop);
2708 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002709 // As above; handle invoke specially.
2710 if (isa<InvokeInst>(Inst))
2711 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2712 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002713 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002714 }
2715 break;
2716 case S_Stop:
2717 if (CanUse(Inst, Ptr, PA, Class))
2718 S.SetSeq(S_Use);
2719 break;
2720 case S_CanRelease:
2721 case S_Use:
2722 case S_None:
2723 break;
2724 case S_Retain:
2725 llvm_unreachable("bottom-up pointer in retain state!");
2726 }
2727 }
2728
2729 return NestingDetected;
2730}
2731
2732bool
John McCall9fbd3182011-06-15 23:37:01 +00002733ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2734 DenseMap<const BasicBlock *, BBState> &BBStates,
2735 MapVector<Value *, RRInfo> &Retains) {
2736 bool NestingDetected = false;
2737 BBState &MyStates = BBStates[BB];
2738
2739 // Merge the states from each successor to compute the initial state
2740 // for the current block.
2741 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2742 succ_const_iterator SI(TI), SE(TI, false);
2743 if (SI == SE)
2744 MyStates.SetAsExit();
Dan Gohmandbe266b2012-02-17 18:59:53 +00002745 else {
2746 // If the terminator is an invoke marked with the
2747 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2748 // ignored, for ARC purposes.
2749 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2750 --SE;
2751
John McCall9fbd3182011-06-15 23:37:01 +00002752 do {
2753 const BasicBlock *Succ = *SI++;
2754 if (Succ == BB)
2755 continue;
2756 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
Dan Gohmana7f7db22011-08-12 00:26:31 +00002757 // If we haven't seen this node yet, then we've found a CFG cycle.
2758 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
John McCall9fbd3182011-06-15 23:37:01 +00002759 if (I == BBStates.end())
2760 continue;
2761 MyStates.InitFromSucc(I->second);
2762 while (SI != SE) {
2763 Succ = *SI++;
2764 if (Succ != BB) {
2765 I = BBStates.find(Succ);
2766 if (I != BBStates.end())
2767 MyStates.MergeSucc(I->second);
2768 }
2769 }
2770 break;
2771 } while (SI != SE);
Dan Gohmandbe266b2012-02-17 18:59:53 +00002772 }
John McCall9fbd3182011-06-15 23:37:01 +00002773
2774 // Visit all the instructions, bottom-up.
2775 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2776 Instruction *Inst = llvm::prior(I);
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002777
2778 // Invoke instructions are visited as part of their successors (below).
2779 if (isa<InvokeInst>(Inst))
2780 continue;
2781
2782 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2783 }
2784
2785 // If there's a predecessor with an invoke, visit the invoke as
2786 // if it were part of this block, since we can't insert code after
2787 // an invoke in its own block, and we don't want to split critical
2788 // edges.
2789 for (pred_iterator PI(BB), PE(BB, false); PI != PE; ++PI) {
2790 BasicBlock *Pred = *PI;
2791 TerminatorInst *PredTI = cast<TerminatorInst>(&Pred->back());
2792 if (isa<InvokeInst>(PredTI))
2793 NestingDetected |= VisitInstructionBottomUp(PredTI, BB, Retains, MyStates);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002794 }
John McCall9fbd3182011-06-15 23:37:01 +00002795
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002796 return NestingDetected;
2797}
John McCall9fbd3182011-06-15 23:37:01 +00002798
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002799bool
2800ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2801 DenseMap<Value *, RRInfo> &Releases,
2802 BBState &MyStates) {
2803 bool NestingDetected = false;
2804 InstructionClass Class = GetInstructionClass(Inst);
2805 const Value *Arg = 0;
John McCall9fbd3182011-06-15 23:37:01 +00002806
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002807 switch (Class) {
2808 case IC_RetainBlock:
2809 // An objc_retainBlock call with just a use may need to be kept,
2810 // because it may be copying a block from the stack to the heap.
2811 if (!IsRetainBlockOptimizable(Inst))
2812 break;
2813 // FALLTHROUGH
2814 case IC_Retain:
2815 case IC_RetainRV: {
2816 Arg = GetObjCArg(Inst);
2817
2818 PtrState &S = MyStates.getPtrTopDownState(Arg);
2819
2820 // Don't do retain+release tracking for IC_RetainRV, because it's
2821 // better to let it remain as the first instruction after a call.
2822 if (Class != IC_RetainRV) {
2823 // If we see two retains in a row on the same pointer. If so, make
John McCall9fbd3182011-06-15 23:37:01 +00002824 // a note, and we'll cicle back to revisit it after we've
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002825 // hopefully eliminated the second retain, which may allow us to
2826 // eliminate the first retain too.
John McCall9fbd3182011-06-15 23:37:01 +00002827 // Theoretically we could implement removal of nested retain+release
2828 // pairs by making PtrState hold a stack of states, but this is
2829 // simple and avoids adding overhead for the non-nested case.
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002830 if (S.GetSeq() == S_Retain)
John McCall9fbd3182011-06-15 23:37:01 +00002831 NestingDetected = true;
2832
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002833 S.SetSeq(S_Retain);
John McCall9fbd3182011-06-15 23:37:01 +00002834 S.RRI.clear();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002835 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2836 // Don't check S.IsKnownIncremented() here because it's not
2837 // sufficient.
2838 S.RRI.KnownSafe = S.IsKnownNested();
John McCall9fbd3182011-06-15 23:37:01 +00002839 S.RRI.Calls.insert(Inst);
John McCall9fbd3182011-06-15 23:37:01 +00002840 }
John McCall9fbd3182011-06-15 23:37:01 +00002841
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002842 S.SetAtLeastOneRefCount();
2843 S.IncrementRefCount();
2844 S.IncrementNestCount();
2845 return NestingDetected;
2846 }
2847 case IC_Release: {
2848 Arg = GetObjCArg(Inst);
2849
2850 PtrState &S = MyStates.getPtrTopDownState(Arg);
2851 S.DecrementRefCount();
2852 S.DecrementNestCount();
2853
2854 switch (S.GetSeq()) {
2855 case S_Retain:
2856 case S_CanRelease:
2857 S.RRI.ReverseInsertPts.clear();
2858 // FALL THROUGH
2859 case S_Use:
2860 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2861 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2862 Releases[Inst] = S.RRI;
2863 S.ClearSequenceProgress();
2864 break;
2865 case S_None:
2866 break;
2867 case S_Stop:
2868 case S_Release:
2869 case S_MovableRelease:
2870 llvm_unreachable("top-down pointer in release state!");
2871 }
2872 break;
2873 }
2874 case IC_AutoreleasepoolPop:
2875 // Conservatively, clear MyStates for all known pointers.
2876 MyStates.clearTopDownPointers();
2877 return NestingDetected;
2878 case IC_AutoreleasepoolPush:
2879 case IC_None:
2880 // These are irrelevant.
2881 return NestingDetected;
2882 default:
2883 break;
2884 }
2885
2886 // Consider any other possible effects of this instruction on each
2887 // pointer being tracked.
2888 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2889 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2890 const Value *Ptr = MI->first;
2891 if (Ptr == Arg)
2892 continue; // Handled above.
2893 PtrState &S = MI->second;
2894 Sequence Seq = S.GetSeq();
2895
2896 // Check for possible releases.
2897 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
John McCall9fbd3182011-06-15 23:37:01 +00002898 S.DecrementRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00002899 switch (Seq) {
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002900 case S_Retain:
2901 S.SetSeq(S_CanRelease);
2902 assert(S.RRI.ReverseInsertPts.empty());
2903 S.RRI.ReverseInsertPts.insert(Inst);
2904
2905 // One call can't cause a transition from S_Retain to S_CanRelease
2906 // and S_CanRelease to S_Use. If we've made the first transition,
2907 // we're done.
2908 continue;
John McCall9fbd3182011-06-15 23:37:01 +00002909 case S_Use:
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002910 case S_CanRelease:
John McCall9fbd3182011-06-15 23:37:01 +00002911 case S_None:
2912 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002913 case S_Stop:
2914 case S_Release:
2915 case S_MovableRelease:
2916 llvm_unreachable("top-down pointer in release state!");
John McCall9fbd3182011-06-15 23:37:01 +00002917 }
2918 }
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002919
2920 // Check for possible direct uses.
2921 switch (Seq) {
2922 case S_CanRelease:
2923 if (CanUse(Inst, Ptr, PA, Class))
2924 S.SetSeq(S_Use);
2925 break;
2926 case S_Retain:
2927 case S_Use:
2928 case S_None:
2929 break;
2930 case S_Stop:
2931 case S_Release:
2932 case S_MovableRelease:
2933 llvm_unreachable("top-down pointer in release state!");
2934 }
John McCall9fbd3182011-06-15 23:37:01 +00002935 }
2936
2937 return NestingDetected;
2938}
2939
2940bool
2941ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2942 DenseMap<const BasicBlock *, BBState> &BBStates,
2943 DenseMap<Value *, RRInfo> &Releases) {
2944 bool NestingDetected = false;
2945 BBState &MyStates = BBStates[BB];
2946
2947 // Merge the states from each predecessor to compute the initial state
2948 // for the current block.
2949 const_pred_iterator PI(BB), PE(BB, false);
2950 if (PI == PE)
2951 MyStates.SetAsEntry();
2952 else
2953 do {
Dan Gohmandbe266b2012-02-17 18:59:53 +00002954 unsigned OperandNo = PI.getOperandNo();
2955 const Use &Us = PI.getUse();
2956 ++PI;
2957
2958 // Skip invoke unwind edges on invoke instructions marked with
2959 // clang.arc.no_objc_arc_exceptions.
2960 if (const InvokeInst *II = dyn_cast<InvokeInst>(Us.getUser()))
2961 if (OperandNo == II->getNumArgOperands() + 2 &&
2962 II->getMetadata(NoObjCARCExceptionsMDKind))
2963 continue;
2964
2965 const BasicBlock *Pred = cast<TerminatorInst>(Us.getUser())->getParent();
John McCall9fbd3182011-06-15 23:37:01 +00002966 if (Pred == BB)
2967 continue;
2968 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
Dan Gohmana7f7db22011-08-12 00:26:31 +00002969 // If we haven't seen this node yet, then we've found a CFG cycle.
2970 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
Dan Gohman59a1c932011-12-12 19:42:25 +00002971 if (I == BBStates.end() || !I->second.isVisitedTopDown())
John McCall9fbd3182011-06-15 23:37:01 +00002972 continue;
2973 MyStates.InitFromPred(I->second);
2974 while (PI != PE) {
2975 Pred = *PI++;
2976 if (Pred != BB) {
2977 I = BBStates.find(Pred);
Dan Gohman48371602011-12-21 21:43:50 +00002978 if (I != BBStates.end() && I->second.isVisitedTopDown())
John McCall9fbd3182011-06-15 23:37:01 +00002979 MyStates.MergePred(I->second);
2980 }
2981 }
2982 break;
2983 } while (PI != PE);
2984
2985 // Visit all the instructions, top-down.
2986 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2987 Instruction *Inst = I;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002988 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00002989 }
2990
2991 CheckForCFGHazards(BB, BBStates, MyStates);
2992 return NestingDetected;
2993}
2994
Dan Gohman59a1c932011-12-12 19:42:25 +00002995static void
2996ComputePostOrders(Function &F,
2997 SmallVectorImpl<BasicBlock *> &PostOrder,
2998 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder) {
2999 /// Backedges - Backedges detected in the DFS. These edges will be
3000 /// ignored in the reverse-CFG DFS, so that loops with multiple exits will be
3001 /// traversed in the desired order.
3002 DenseSet<std::pair<BasicBlock *, BasicBlock *> > Backedges;
3003
3004 /// Visited - The visited set, for doing DFS walks.
3005 SmallPtrSet<BasicBlock *, 16> Visited;
3006
3007 // Do DFS, computing the PostOrder.
3008 SmallPtrSet<BasicBlock *, 16> OnStack;
3009 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
3010 BasicBlock *EntryBB = &F.getEntryBlock();
3011 SuccStack.push_back(std::make_pair(EntryBB, succ_begin(EntryBB)));
3012 Visited.insert(EntryBB);
3013 OnStack.insert(EntryBB);
3014 do {
3015 dfs_next_succ:
Dan Gohmandbe266b2012-02-17 18:59:53 +00003016 TerminatorInst *TI = cast<TerminatorInst>(&SuccStack.back().first->back());
3017 succ_iterator End = succ_iterator(TI, true);
Dan Gohman59a1c932011-12-12 19:42:25 +00003018 while (SuccStack.back().second != End) {
3019 BasicBlock *BB = *SuccStack.back().second++;
3020 if (Visited.insert(BB)) {
3021 SuccStack.push_back(std::make_pair(BB, succ_begin(BB)));
3022 OnStack.insert(BB);
3023 goto dfs_next_succ;
3024 }
3025 if (OnStack.count(BB))
3026 Backedges.insert(std::make_pair(SuccStack.back().first, BB));
3027 }
3028 OnStack.erase(SuccStack.back().first);
3029 PostOrder.push_back(SuccStack.pop_back_val().first);
3030 } while (!SuccStack.empty());
3031
3032 Visited.clear();
3033
3034 // Compute the exits, which are the starting points for reverse-CFG DFS.
Dan Gohman5992f672012-03-09 18:50:52 +00003035 // This includes blocks where all the successors are backedges that
3036 // we're skipping.
Dan Gohman59a1c932011-12-12 19:42:25 +00003037 SmallVector<BasicBlock *, 4> Exits;
3038 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3039 BasicBlock *BB = I;
Dan Gohman5992f672012-03-09 18:50:52 +00003040 TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
3041 for (succ_iterator SI(TI), SE(TI, true); SI != SE; ++SI)
3042 if (!Backedges.count(std::make_pair(BB, *SI)))
3043 goto HasNonBackedgeSucc;
3044 Exits.push_back(BB);
3045 HasNonBackedgeSucc:;
Dan Gohman59a1c932011-12-12 19:42:25 +00003046 }
3047
3048 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
3049 SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> PredStack;
3050 for (SmallVectorImpl<BasicBlock *>::iterator I = Exits.begin(), E = Exits.end();
3051 I != E; ++I) {
3052 BasicBlock *ExitBB = *I;
3053 PredStack.push_back(std::make_pair(ExitBB, pred_begin(ExitBB)));
3054 Visited.insert(ExitBB);
3055 while (!PredStack.empty()) {
3056 reverse_dfs_next_succ:
3057 pred_iterator End = pred_end(PredStack.back().first);
3058 while (PredStack.back().second != End) {
3059 BasicBlock *BB = *PredStack.back().second++;
3060 // Skip backedges detected in the forward-CFG DFS.
3061 if (Backedges.count(std::make_pair(BB, PredStack.back().first)))
3062 continue;
3063 if (Visited.insert(BB)) {
3064 PredStack.push_back(std::make_pair(BB, pred_begin(BB)));
3065 goto reverse_dfs_next_succ;
3066 }
3067 }
3068 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3069 }
3070 }
3071}
3072
John McCall9fbd3182011-06-15 23:37:01 +00003073// Visit - Visit the function both top-down and bottom-up.
3074bool
3075ObjCARCOpt::Visit(Function &F,
3076 DenseMap<const BasicBlock *, BBState> &BBStates,
3077 MapVector<Value *, RRInfo> &Retains,
3078 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003079
3080 // Use reverse-postorder traversals, because we magically know that loops
3081 // will be well behaved, i.e. they won't repeatedly call retain on a single
3082 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3083 // class here because we want the reverse-CFG postorder to consider each
3084 // function exit point, and we want to ignore selected cycle edges.
3085 SmallVector<BasicBlock *, 16> PostOrder;
3086 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
3087 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder);
3088
3089 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCall9fbd3182011-06-15 23:37:01 +00003090 bool BottomUpNestingDetected = false;
Dan Gohmanb48ef3a2011-08-18 21:27:42 +00003091 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohman59a1c932011-12-12 19:42:25 +00003092 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3093 I != E; ++I)
3094 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCall9fbd3182011-06-15 23:37:01 +00003095
Dan Gohman59a1c932011-12-12 19:42:25 +00003096 // Use reverse-postorder for top-down.
John McCall9fbd3182011-06-15 23:37:01 +00003097 bool TopDownNestingDetected = false;
Dan Gohman59a1c932011-12-12 19:42:25 +00003098 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3099 PostOrder.rbegin(), E = PostOrder.rend();
3100 I != E; ++I)
3101 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCall9fbd3182011-06-15 23:37:01 +00003102
3103 return TopDownNestingDetected && BottomUpNestingDetected;
3104}
3105
3106/// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
3107void ObjCARCOpt::MoveCalls(Value *Arg,
3108 RRInfo &RetainsToMove,
3109 RRInfo &ReleasesToMove,
3110 MapVector<Value *, RRInfo> &Retains,
3111 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00003112 SmallVectorImpl<Instruction *> &DeadInsts,
3113 Module *M) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003114 Type *ArgTy = Arg->getType();
Dan Gohman44280692011-07-22 22:29:21 +00003115 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCall9fbd3182011-06-15 23:37:01 +00003116
3117 // Insert the new retain and release calls.
3118 for (SmallPtrSet<Instruction *, 2>::const_iterator
3119 PI = ReleasesToMove.ReverseInsertPts.begin(),
3120 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3121 Instruction *InsertPt = *PI;
3122 Value *MyArg = ArgTy == ParamTy ? Arg :
3123 new BitCastInst(Arg, ParamTy, "", InsertPt);
3124 CallInst *Call =
3125 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman44280692011-07-22 22:29:21 +00003126 getRetainBlockCallee(M) : getRetainCallee(M),
John McCall9fbd3182011-06-15 23:37:01 +00003127 MyArg, "", InsertPt);
3128 Call->setDoesNotThrow();
Dan Gohman79522dc2012-01-13 00:39:07 +00003129 if (RetainsToMove.IsRetainBlock)
Dan Gohmana974bea2011-10-17 22:53:25 +00003130 Call->setMetadata(CopyOnEscapeMDKind,
3131 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman79522dc2012-01-13 00:39:07 +00003132 else
John McCall9fbd3182011-06-15 23:37:01 +00003133 Call->setTailCall();
3134 }
3135 for (SmallPtrSet<Instruction *, 2>::const_iterator
3136 PI = RetainsToMove.ReverseInsertPts.begin(),
3137 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00003138 Instruction *InsertPt = *PI;
3139 Value *MyArg = ArgTy == ParamTy ? Arg :
3140 new BitCastInst(Arg, ParamTy, "", InsertPt);
3141 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3142 "", InsertPt);
3143 // Attach a clang.imprecise_release metadata tag, if appropriate.
3144 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3145 Call->setMetadata(ImpreciseReleaseMDKind, M);
3146 Call->setDoesNotThrow();
3147 if (ReleasesToMove.IsTailCallRelease)
3148 Call->setTailCall();
John McCall9fbd3182011-06-15 23:37:01 +00003149 }
3150
3151 // Delete the original retain and release calls.
3152 for (SmallPtrSet<Instruction *, 2>::const_iterator
3153 AI = RetainsToMove.Calls.begin(),
3154 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3155 Instruction *OrigRetain = *AI;
3156 Retains.blot(OrigRetain);
3157 DeadInsts.push_back(OrigRetain);
3158 }
3159 for (SmallPtrSet<Instruction *, 2>::const_iterator
3160 AI = ReleasesToMove.Calls.begin(),
3161 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3162 Instruction *OrigRelease = *AI;
3163 Releases.erase(OrigRelease);
3164 DeadInsts.push_back(OrigRelease);
3165 }
3166}
3167
3168bool
3169ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3170 &BBStates,
3171 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00003172 DenseMap<Value *, RRInfo> &Releases,
3173 Module *M) {
John McCall9fbd3182011-06-15 23:37:01 +00003174 bool AnyPairsCompletelyEliminated = false;
3175 RRInfo RetainsToMove;
3176 RRInfo ReleasesToMove;
3177 SmallVector<Instruction *, 4> NewRetains;
3178 SmallVector<Instruction *, 4> NewReleases;
3179 SmallVector<Instruction *, 8> DeadInsts;
3180
3181 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman597fece2011-09-29 22:25:23 +00003182 E = Retains.end(); I != E; ++I) {
3183 Value *V = I->first;
John McCall9fbd3182011-06-15 23:37:01 +00003184 if (!V) continue; // blotted
3185
3186 Instruction *Retain = cast<Instruction>(V);
3187 Value *Arg = GetObjCArg(Retain);
3188
Dan Gohman79522dc2012-01-13 00:39:07 +00003189 // If the object being released is in static or stack storage, we know it's
John McCall9fbd3182011-06-15 23:37:01 +00003190 // not being managed by ObjC reference counting, so we can delete pairs
3191 // regardless of what possible decrements or uses lie between them.
Dan Gohman79522dc2012-01-13 00:39:07 +00003192 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman597fece2011-09-29 22:25:23 +00003193
Dan Gohman1b31ea82011-08-22 17:29:11 +00003194 // A constant pointer can't be pointing to an object on the heap. It may
3195 // be reference-counted, but it won't be deleted.
3196 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3197 if (const GlobalVariable *GV =
3198 dyn_cast<GlobalVariable>(
3199 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3200 if (GV->isConstant())
3201 KnownSafe = true;
3202
John McCall9fbd3182011-06-15 23:37:01 +00003203 // If a pair happens in a region where it is known that the reference count
3204 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmane6d5e882011-08-19 00:26:36 +00003205 bool KnownSafeTD = true, KnownSafeBU = true;
John McCall9fbd3182011-06-15 23:37:01 +00003206
3207 // Connect the dots between the top-down-collected RetainsToMove and
3208 // bottom-up-collected ReleasesToMove to form sets of related calls.
3209 // This is an iterative process so that we connect multiple releases
3210 // to multiple retains if needed.
3211 unsigned OldDelta = 0;
3212 unsigned NewDelta = 0;
3213 unsigned OldCount = 0;
3214 unsigned NewCount = 0;
3215 bool FirstRelease = true;
3216 bool FirstRetain = true;
3217 NewRetains.push_back(Retain);
3218 for (;;) {
3219 for (SmallVectorImpl<Instruction *>::const_iterator
3220 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3221 Instruction *NewRetain = *NI;
3222 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3223 assert(It != Retains.end());
3224 const RRInfo &NewRetainRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003225 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003226 for (SmallPtrSet<Instruction *, 2>::const_iterator
3227 LI = NewRetainRRI.Calls.begin(),
3228 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3229 Instruction *NewRetainRelease = *LI;
3230 DenseMap<Value *, RRInfo>::const_iterator Jt =
3231 Releases.find(NewRetainRelease);
3232 if (Jt == Releases.end())
3233 goto next_retain;
3234 const RRInfo &NewRetainReleaseRRI = Jt->second;
3235 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3236 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3237 OldDelta -=
3238 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3239
3240 // Merge the ReleaseMetadata and IsTailCallRelease values.
3241 if (FirstRelease) {
3242 ReleasesToMove.ReleaseMetadata =
3243 NewRetainReleaseRRI.ReleaseMetadata;
3244 ReleasesToMove.IsTailCallRelease =
3245 NewRetainReleaseRRI.IsTailCallRelease;
3246 FirstRelease = false;
3247 } else {
3248 if (ReleasesToMove.ReleaseMetadata !=
3249 NewRetainReleaseRRI.ReleaseMetadata)
3250 ReleasesToMove.ReleaseMetadata = 0;
3251 if (ReleasesToMove.IsTailCallRelease !=
3252 NewRetainReleaseRRI.IsTailCallRelease)
3253 ReleasesToMove.IsTailCallRelease = false;
3254 }
3255
3256 // Collect the optimal insertion points.
3257 if (!KnownSafe)
3258 for (SmallPtrSet<Instruction *, 2>::const_iterator
3259 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3260 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3261 RI != RE; ++RI) {
3262 Instruction *RIP = *RI;
3263 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3264 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3265 }
3266 NewReleases.push_back(NewRetainRelease);
3267 }
3268 }
3269 }
3270 NewRetains.clear();
3271 if (NewReleases.empty()) break;
3272
3273 // Back the other way.
3274 for (SmallVectorImpl<Instruction *>::const_iterator
3275 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3276 Instruction *NewRelease = *NI;
3277 DenseMap<Value *, RRInfo>::const_iterator It =
3278 Releases.find(NewRelease);
3279 assert(It != Releases.end());
3280 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003281 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003282 for (SmallPtrSet<Instruction *, 2>::const_iterator
3283 LI = NewReleaseRRI.Calls.begin(),
3284 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3285 Instruction *NewReleaseRetain = *LI;
3286 MapVector<Value *, RRInfo>::const_iterator Jt =
3287 Retains.find(NewReleaseRetain);
3288 if (Jt == Retains.end())
3289 goto next_retain;
3290 const RRInfo &NewReleaseRetainRRI = Jt->second;
3291 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3292 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3293 unsigned PathCount =
3294 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3295 OldDelta += PathCount;
3296 OldCount += PathCount;
3297
3298 // Merge the IsRetainBlock values.
3299 if (FirstRetain) {
3300 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3301 FirstRetain = false;
3302 } else if (ReleasesToMove.IsRetainBlock !=
3303 NewReleaseRetainRRI.IsRetainBlock)
3304 // It's not possible to merge the sequences if one uses
3305 // objc_retain and the other uses objc_retainBlock.
3306 goto next_retain;
3307
3308 // Collect the optimal insertion points.
3309 if (!KnownSafe)
3310 for (SmallPtrSet<Instruction *, 2>::const_iterator
3311 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3312 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3313 RI != RE; ++RI) {
3314 Instruction *RIP = *RI;
3315 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3316 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3317 NewDelta += PathCount;
3318 NewCount += PathCount;
3319 }
3320 }
3321 NewRetains.push_back(NewReleaseRetain);
3322 }
3323 }
3324 }
3325 NewReleases.clear();
3326 if (NewRetains.empty()) break;
3327 }
3328
Dan Gohmane6d5e882011-08-19 00:26:36 +00003329 // If the pointer is known incremented or nested, we can safely delete the
3330 // pair regardless of what's between them.
3331 if (KnownSafeTD || KnownSafeBU) {
John McCall9fbd3182011-06-15 23:37:01 +00003332 RetainsToMove.ReverseInsertPts.clear();
3333 ReleasesToMove.ReverseInsertPts.clear();
3334 NewCount = 0;
Dan Gohmana7f7db22011-08-12 00:26:31 +00003335 } else {
3336 // Determine whether the new insertion points we computed preserve the
3337 // balance of retain and release calls through the program.
3338 // TODO: If the fully aggressive solution isn't valid, try to find a
3339 // less aggressive solution which is.
3340 if (NewDelta != 0)
3341 goto next_retain;
John McCall9fbd3182011-06-15 23:37:01 +00003342 }
3343
3344 // Determine whether the original call points are balanced in the retain and
3345 // release calls through the program. If not, conservatively don't touch
3346 // them.
3347 // TODO: It's theoretically possible to do code motion in this case, as
3348 // long as the existing imbalances are maintained.
3349 if (OldDelta != 0)
3350 goto next_retain;
3351
John McCall9fbd3182011-06-15 23:37:01 +00003352 // Ok, everything checks out and we're all set. Let's move some code!
3353 Changed = true;
3354 AnyPairsCompletelyEliminated = NewCount == 0;
3355 NumRRs += OldCount - NewCount;
Dan Gohman44280692011-07-22 22:29:21 +00003356 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3357 Retains, Releases, DeadInsts, M);
John McCall9fbd3182011-06-15 23:37:01 +00003358
3359 next_retain:
3360 NewReleases.clear();
3361 NewRetains.clear();
3362 RetainsToMove.clear();
3363 ReleasesToMove.clear();
3364 }
3365
3366 // Now that we're done moving everything, we can delete the newly dead
3367 // instructions, as we no longer need them as insert points.
3368 while (!DeadInsts.empty())
3369 EraseInstruction(DeadInsts.pop_back_val());
3370
3371 return AnyPairsCompletelyEliminated;
3372}
3373
3374/// OptimizeWeakCalls - Weak pointer optimizations.
3375void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3376 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3377 // itself because it uses AliasAnalysis and we need to do provenance
3378 // queries instead.
3379 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3380 Instruction *Inst = &*I++;
3381 InstructionClass Class = GetBasicInstructionClass(Inst);
3382 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3383 continue;
3384
3385 // Delete objc_loadWeak calls with no users.
3386 if (Class == IC_LoadWeak && Inst->use_empty()) {
3387 Inst->eraseFromParent();
3388 continue;
3389 }
3390
3391 // TODO: For now, just look for an earlier available version of this value
3392 // within the same block. Theoretically, we could do memdep-style non-local
3393 // analysis too, but that would want caching. A better approach would be to
3394 // use the technique that EarlyCSE uses.
3395 inst_iterator Current = llvm::prior(I);
3396 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3397 for (BasicBlock::iterator B = CurrentBB->begin(),
3398 J = Current.getInstructionIterator();
3399 J != B; --J) {
3400 Instruction *EarlierInst = &*llvm::prior(J);
3401 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3402 switch (EarlierClass) {
3403 case IC_LoadWeak:
3404 case IC_LoadWeakRetained: {
3405 // If this is loading from the same pointer, replace this load's value
3406 // with that one.
3407 CallInst *Call = cast<CallInst>(Inst);
3408 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3409 Value *Arg = Call->getArgOperand(0);
3410 Value *EarlierArg = EarlierCall->getArgOperand(0);
3411 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3412 case AliasAnalysis::MustAlias:
3413 Changed = true;
3414 // If the load has a builtin retain, insert a plain retain for it.
3415 if (Class == IC_LoadWeakRetained) {
3416 CallInst *CI =
3417 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3418 "", Call);
3419 CI->setTailCall();
3420 }
3421 // Zap the fully redundant load.
3422 Call->replaceAllUsesWith(EarlierCall);
3423 Call->eraseFromParent();
3424 goto clobbered;
3425 case AliasAnalysis::MayAlias:
3426 case AliasAnalysis::PartialAlias:
3427 goto clobbered;
3428 case AliasAnalysis::NoAlias:
3429 break;
3430 }
3431 break;
3432 }
3433 case IC_StoreWeak:
3434 case IC_InitWeak: {
3435 // If this is storing to the same pointer and has the same size etc.
3436 // replace this load's value with the stored value.
3437 CallInst *Call = cast<CallInst>(Inst);
3438 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3439 Value *Arg = Call->getArgOperand(0);
3440 Value *EarlierArg = EarlierCall->getArgOperand(0);
3441 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3442 case AliasAnalysis::MustAlias:
3443 Changed = true;
3444 // If the load has a builtin retain, insert a plain retain for it.
3445 if (Class == IC_LoadWeakRetained) {
3446 CallInst *CI =
3447 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3448 "", Call);
3449 CI->setTailCall();
3450 }
3451 // Zap the fully redundant load.
3452 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3453 Call->eraseFromParent();
3454 goto clobbered;
3455 case AliasAnalysis::MayAlias:
3456 case AliasAnalysis::PartialAlias:
3457 goto clobbered;
3458 case AliasAnalysis::NoAlias:
3459 break;
3460 }
3461 break;
3462 }
3463 case IC_MoveWeak:
3464 case IC_CopyWeak:
3465 // TOOD: Grab the copied value.
3466 goto clobbered;
3467 case IC_AutoreleasepoolPush:
3468 case IC_None:
3469 case IC_User:
3470 // Weak pointers are only modified through the weak entry points
3471 // (and arbitrary calls, which could call the weak entry points).
3472 break;
3473 default:
3474 // Anything else could modify the weak pointer.
3475 goto clobbered;
3476 }
3477 }
3478 clobbered:;
3479 }
3480
3481 // Then, for each destroyWeak with an alloca operand, check to see if
3482 // the alloca and all its users can be zapped.
3483 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3484 Instruction *Inst = &*I++;
3485 InstructionClass Class = GetBasicInstructionClass(Inst);
3486 if (Class != IC_DestroyWeak)
3487 continue;
3488
3489 CallInst *Call = cast<CallInst>(Inst);
3490 Value *Arg = Call->getArgOperand(0);
3491 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3492 for (Value::use_iterator UI = Alloca->use_begin(),
3493 UE = Alloca->use_end(); UI != UE; ++UI) {
3494 Instruction *UserInst = cast<Instruction>(*UI);
3495 switch (GetBasicInstructionClass(UserInst)) {
3496 case IC_InitWeak:
3497 case IC_StoreWeak:
3498 case IC_DestroyWeak:
3499 continue;
3500 default:
3501 goto done;
3502 }
3503 }
3504 Changed = true;
3505 for (Value::use_iterator UI = Alloca->use_begin(),
3506 UE = Alloca->use_end(); UI != UE; ) {
3507 CallInst *UserInst = cast<CallInst>(*UI++);
3508 if (!UserInst->use_empty())
Dan Gohman8a9eebe2011-12-12 18:19:12 +00003509 UserInst->replaceAllUsesWith(UserInst->getArgOperand(0));
John McCall9fbd3182011-06-15 23:37:01 +00003510 UserInst->eraseFromParent();
3511 }
3512 Alloca->eraseFromParent();
3513 done:;
3514 }
3515 }
3516}
3517
3518/// OptimizeSequences - Identify program paths which execute sequences of
3519/// retains and releases which can be eliminated.
3520bool ObjCARCOpt::OptimizeSequences(Function &F) {
3521 /// Releases, Retains - These are used to store the results of the main flow
3522 /// analysis. These use Value* as the key instead of Instruction* so that the
3523 /// map stays valid when we get around to rewriting code and calls get
3524 /// replaced by arguments.
3525 DenseMap<Value *, RRInfo> Releases;
3526 MapVector<Value *, RRInfo> Retains;
3527
3528 /// BBStates, This is used during the traversal of the function to track the
3529 /// states for each identified object at each block.
3530 DenseMap<const BasicBlock *, BBState> BBStates;
3531
3532 // Analyze the CFG of the function, and all instructions.
3533 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3534
3535 // Transform.
Dan Gohman44280692011-07-22 22:29:21 +00003536 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3537 NestingDetected;
John McCall9fbd3182011-06-15 23:37:01 +00003538}
3539
3540/// OptimizeReturns - Look for this pattern:
3541///
3542/// %call = call i8* @something(...)
3543/// %2 = call i8* @objc_retain(i8* %call)
3544/// %3 = call i8* @objc_autorelease(i8* %2)
3545/// ret i8* %3
3546///
3547/// And delete the retain and autorelease.
3548///
3549/// Otherwise if it's just this:
3550///
3551/// %3 = call i8* @objc_autorelease(i8* %2)
3552/// ret i8* %3
3553///
3554/// convert the autorelease to autoreleaseRV.
3555void ObjCARCOpt::OptimizeReturns(Function &F) {
3556 if (!F.getReturnType()->isPointerTy())
3557 return;
3558
3559 SmallPtrSet<Instruction *, 4> DependingInstructions;
3560 SmallPtrSet<const BasicBlock *, 4> Visited;
3561 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3562 BasicBlock *BB = FI;
3563 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3564 if (!Ret) continue;
3565
3566 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3567 FindDependencies(NeedsPositiveRetainCount, Arg,
3568 BB, Ret, DependingInstructions, Visited, PA);
3569 if (DependingInstructions.size() != 1)
3570 goto next_block;
3571
3572 {
3573 CallInst *Autorelease =
3574 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3575 if (!Autorelease)
3576 goto next_block;
3577 InstructionClass AutoreleaseClass =
3578 GetBasicInstructionClass(Autorelease);
3579 if (!IsAutorelease(AutoreleaseClass))
3580 goto next_block;
3581 if (GetObjCArg(Autorelease) != Arg)
3582 goto next_block;
3583
3584 DependingInstructions.clear();
3585 Visited.clear();
3586
3587 // Check that there is nothing that can affect the reference
3588 // count between the autorelease and the retain.
3589 FindDependencies(CanChangeRetainCount, Arg,
3590 BB, Autorelease, DependingInstructions, Visited, PA);
3591 if (DependingInstructions.size() != 1)
3592 goto next_block;
3593
3594 {
3595 CallInst *Retain =
3596 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3597
3598 // Check that we found a retain with the same argument.
3599 if (!Retain ||
3600 !IsRetain(GetBasicInstructionClass(Retain)) ||
3601 GetObjCArg(Retain) != Arg)
3602 goto next_block;
3603
3604 DependingInstructions.clear();
3605 Visited.clear();
3606
3607 // Convert the autorelease to an autoreleaseRV, since it's
3608 // returning the value.
3609 if (AutoreleaseClass == IC_Autorelease) {
3610 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3611 AutoreleaseClass = IC_AutoreleaseRV;
3612 }
3613
3614 // Check that there is nothing that can affect the reference
3615 // count between the retain and the call.
Dan Gohman27e06662011-09-29 22:27:34 +00003616 // Note that Retain need not be in BB.
3617 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCall9fbd3182011-06-15 23:37:01 +00003618 DependingInstructions, Visited, PA);
3619 if (DependingInstructions.size() != 1)
3620 goto next_block;
3621
3622 {
3623 CallInst *Call =
3624 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3625
3626 // Check that the pointer is the return value of the call.
3627 if (!Call || Arg != Call)
3628 goto next_block;
3629
3630 // Check that the call is a regular call.
3631 InstructionClass Class = GetBasicInstructionClass(Call);
3632 if (Class != IC_CallOrUser && Class != IC_Call)
3633 goto next_block;
3634
3635 // If so, we can zap the retain and autorelease.
3636 Changed = true;
3637 ++NumRets;
3638 EraseInstruction(Retain);
3639 EraseInstruction(Autorelease);
3640 }
3641 }
3642 }
3643
3644 next_block:
3645 DependingInstructions.clear();
3646 Visited.clear();
3647 }
3648}
3649
3650bool ObjCARCOpt::doInitialization(Module &M) {
3651 if (!EnableARCOpts)
3652 return false;
3653
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003654 Run = ModuleHasARC(M);
3655 if (!Run)
3656 return false;
3657
John McCall9fbd3182011-06-15 23:37:01 +00003658 // Identify the imprecise release metadata kind.
3659 ImpreciseReleaseMDKind =
3660 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana974bea2011-10-17 22:53:25 +00003661 CopyOnEscapeMDKind =
3662 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohmandbe266b2012-02-17 18:59:53 +00003663 NoObjCARCExceptionsMDKind =
3664 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCall9fbd3182011-06-15 23:37:01 +00003665
John McCall9fbd3182011-06-15 23:37:01 +00003666 // Intuitively, objc_retain and others are nocapture, however in practice
3667 // they are not, because they return their argument value. And objc_release
3668 // calls finalizers.
3669
3670 // These are initialized lazily.
3671 RetainRVCallee = 0;
3672 AutoreleaseRVCallee = 0;
3673 ReleaseCallee = 0;
3674 RetainCallee = 0;
Dan Gohman44280692011-07-22 22:29:21 +00003675 RetainBlockCallee = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003676 AutoreleaseCallee = 0;
3677
3678 return false;
3679}
3680
3681bool ObjCARCOpt::runOnFunction(Function &F) {
3682 if (!EnableARCOpts)
3683 return false;
3684
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003685 // If nothing in the Module uses ARC, don't do anything.
3686 if (!Run)
3687 return false;
3688
John McCall9fbd3182011-06-15 23:37:01 +00003689 Changed = false;
3690
3691 PA.setAA(&getAnalysis<AliasAnalysis>());
3692
3693 // This pass performs several distinct transformations. As a compile-time aid
3694 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3695 // library functions aren't declared.
3696
3697 // Preliminary optimizations. This also computs UsedInThisFunction.
3698 OptimizeIndividualCalls(F);
3699
3700 // Optimizations for weak pointers.
3701 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3702 (1 << IC_LoadWeakRetained) |
3703 (1 << IC_StoreWeak) |
3704 (1 << IC_InitWeak) |
3705 (1 << IC_CopyWeak) |
3706 (1 << IC_MoveWeak) |
3707 (1 << IC_DestroyWeak)))
3708 OptimizeWeakCalls(F);
3709
3710 // Optimizations for retain+release pairs.
3711 if (UsedInThisFunction & ((1 << IC_Retain) |
3712 (1 << IC_RetainRV) |
3713 (1 << IC_RetainBlock)))
3714 if (UsedInThisFunction & (1 << IC_Release))
3715 // Run OptimizeSequences until it either stops making changes or
3716 // no retain+release pair nesting is detected.
3717 while (OptimizeSequences(F)) {}
3718
3719 // Optimizations if objc_autorelease is used.
3720 if (UsedInThisFunction &
3721 ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
3722 OptimizeReturns(F);
3723
3724 return Changed;
3725}
3726
3727void ObjCARCOpt::releaseMemory() {
3728 PA.clear();
3729}
3730
3731//===----------------------------------------------------------------------===//
3732// ARC contraction.
3733//===----------------------------------------------------------------------===//
3734
3735// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3736// dominated by single calls.
3737
3738#include "llvm/Operator.h"
3739#include "llvm/InlineAsm.h"
3740#include "llvm/Analysis/Dominators.h"
3741
3742STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3743
3744namespace {
3745 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3746 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3747 class ObjCARCContract : public FunctionPass {
3748 bool Changed;
3749 AliasAnalysis *AA;
3750 DominatorTree *DT;
3751 ProvenanceAnalysis PA;
3752
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003753 /// Run - A flag indicating whether this optimization pass should run.
3754 bool Run;
3755
John McCall9fbd3182011-06-15 23:37:01 +00003756 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3757 /// functions, for use in creating calls to them. These are initialized
3758 /// lazily to avoid cluttering up the Module with unused declarations.
3759 Constant *StoreStrongCallee,
3760 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3761
3762 /// RetainRVMarker - The inline asm string to insert between calls and
3763 /// RetainRV calls to make the optimization work on targets which need it.
3764 const MDString *RetainRVMarker;
3765
Dan Gohman0cdece42012-01-19 19:14:36 +00003766 /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
3767 /// at the end of walking the function we have found no alloca
3768 /// instructions, these calls can be marked "tail".
3769 DenseSet<CallInst *> StoreStrongCalls;
3770
John McCall9fbd3182011-06-15 23:37:01 +00003771 Constant *getStoreStrongCallee(Module *M);
3772 Constant *getRetainAutoreleaseCallee(Module *M);
3773 Constant *getRetainAutoreleaseRVCallee(Module *M);
3774
3775 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3776 InstructionClass Class,
3777 SmallPtrSet<Instruction *, 4>
3778 &DependingInstructions,
3779 SmallPtrSet<const BasicBlock *, 4>
3780 &Visited);
3781
3782 void ContractRelease(Instruction *Release,
3783 inst_iterator &Iter);
3784
3785 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3786 virtual bool doInitialization(Module &M);
3787 virtual bool runOnFunction(Function &F);
3788
3789 public:
3790 static char ID;
3791 ObjCARCContract() : FunctionPass(ID) {
3792 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3793 }
3794 };
3795}
3796
3797char ObjCARCContract::ID = 0;
3798INITIALIZE_PASS_BEGIN(ObjCARCContract,
3799 "objc-arc-contract", "ObjC ARC contraction", false, false)
3800INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3801INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3802INITIALIZE_PASS_END(ObjCARCContract,
3803 "objc-arc-contract", "ObjC ARC contraction", false, false)
3804
3805Pass *llvm::createObjCARCContractPass() {
3806 return new ObjCARCContract();
3807}
3808
3809void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3810 AU.addRequired<AliasAnalysis>();
3811 AU.addRequired<DominatorTree>();
3812 AU.setPreservesCFG();
3813}
3814
3815Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3816 if (!StoreStrongCallee) {
3817 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003818 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3819 Type *I8XX = PointerType::getUnqual(I8X);
3820 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003821 Params.push_back(I8XX);
3822 Params.push_back(I8X);
3823
3824 AttrListPtr Attributes;
3825 Attributes.addAttr(~0u, Attribute::NoUnwind);
3826 Attributes.addAttr(1, Attribute::NoCapture);
3827
3828 StoreStrongCallee =
3829 M->getOrInsertFunction(
3830 "objc_storeStrong",
3831 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3832 Attributes);
3833 }
3834 return StoreStrongCallee;
3835}
3836
3837Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3838 if (!RetainAutoreleaseCallee) {
3839 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003840 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3841 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003842 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003843 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00003844 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3845 AttrListPtr Attributes;
3846 Attributes.addAttr(~0u, Attribute::NoUnwind);
3847 RetainAutoreleaseCallee =
3848 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3849 }
3850 return RetainAutoreleaseCallee;
3851}
3852
3853Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3854 if (!RetainAutoreleaseRVCallee) {
3855 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003856 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3857 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003858 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003859 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00003860 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3861 AttrListPtr Attributes;
3862 Attributes.addAttr(~0u, Attribute::NoUnwind);
3863 RetainAutoreleaseRVCallee =
3864 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3865 Attributes);
3866 }
3867 return RetainAutoreleaseRVCallee;
3868}
3869
3870/// ContractAutorelease - Merge an autorelease with a retain into a fused
3871/// call.
3872bool
3873ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3874 InstructionClass Class,
3875 SmallPtrSet<Instruction *, 4>
3876 &DependingInstructions,
3877 SmallPtrSet<const BasicBlock *, 4>
3878 &Visited) {
3879 const Value *Arg = GetObjCArg(Autorelease);
3880
3881 // Check that there are no instructions between the retain and the autorelease
3882 // (such as an autorelease_pop) which may change the count.
3883 CallInst *Retain = 0;
3884 if (Class == IC_AutoreleaseRV)
3885 FindDependencies(RetainAutoreleaseRVDep, Arg,
3886 Autorelease->getParent(), Autorelease,
3887 DependingInstructions, Visited, PA);
3888 else
3889 FindDependencies(RetainAutoreleaseDep, Arg,
3890 Autorelease->getParent(), Autorelease,
3891 DependingInstructions, Visited, PA);
3892
3893 Visited.clear();
3894 if (DependingInstructions.size() != 1) {
3895 DependingInstructions.clear();
3896 return false;
3897 }
3898
3899 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3900 DependingInstructions.clear();
3901
3902 if (!Retain ||
3903 GetBasicInstructionClass(Retain) != IC_Retain ||
3904 GetObjCArg(Retain) != Arg)
3905 return false;
3906
3907 Changed = true;
3908 ++NumPeeps;
3909
3910 if (Class == IC_AutoreleaseRV)
3911 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3912 else
3913 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3914
3915 EraseInstruction(Autorelease);
3916 return true;
3917}
3918
3919/// ContractRelease - Attempt to merge an objc_release with a store, load, and
3920/// objc_retain to form an objc_storeStrong. This can be a little tricky because
3921/// the instructions don't always appear in order, and there may be unrelated
3922/// intervening instructions.
3923void ObjCARCContract::ContractRelease(Instruction *Release,
3924 inst_iterator &Iter) {
3925 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman2bc3d522011-09-12 20:23:13 +00003926 if (!Load || !Load->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00003927
3928 // For now, require everything to be in one basic block.
3929 BasicBlock *BB = Release->getParent();
3930 if (Load->getParent() != BB) return;
3931
3932 // Walk down to find the store.
3933 BasicBlock::iterator I = Load, End = BB->end();
3934 ++I;
3935 AliasAnalysis::Location Loc = AA->getLocation(Load);
3936 while (I != End &&
3937 (&*I == Release ||
3938 IsRetain(GetBasicInstructionClass(I)) ||
3939 !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
3940 ++I;
3941 StoreInst *Store = dyn_cast<StoreInst>(I);
Eli Friedman2bc3d522011-09-12 20:23:13 +00003942 if (!Store || !Store->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00003943 if (Store->getPointerOperand() != Loc.Ptr) return;
3944
3945 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3946
3947 // Walk up to find the retain.
3948 I = Store;
3949 BasicBlock::iterator Begin = BB->begin();
3950 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3951 --I;
3952 Instruction *Retain = I;
3953 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3954 if (GetObjCArg(Retain) != New) return;
3955
3956 Changed = true;
3957 ++NumStoreStrongs;
3958
3959 LLVMContext &C = Release->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003960 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3961 Type *I8XX = PointerType::getUnqual(I8X);
John McCall9fbd3182011-06-15 23:37:01 +00003962
3963 Value *Args[] = { Load->getPointerOperand(), New };
3964 if (Args[0]->getType() != I8XX)
3965 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3966 if (Args[1]->getType() != I8X)
3967 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3968 CallInst *StoreStrong =
3969 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foada3efbb12011-07-15 08:37:34 +00003970 Args, "", Store);
John McCall9fbd3182011-06-15 23:37:01 +00003971 StoreStrong->setDoesNotThrow();
3972 StoreStrong->setDebugLoc(Store->getDebugLoc());
3973
Dan Gohman0cdece42012-01-19 19:14:36 +00003974 // We can't set the tail flag yet, because we haven't yet determined
3975 // whether there are any escaping allocas. Remember this call, so that
3976 // we can set the tail flag once we know it's safe.
3977 StoreStrongCalls.insert(StoreStrong);
3978
John McCall9fbd3182011-06-15 23:37:01 +00003979 if (&*Iter == Store) ++Iter;
3980 Store->eraseFromParent();
3981 Release->eraseFromParent();
3982 EraseInstruction(Retain);
3983 if (Load->use_empty())
3984 Load->eraseFromParent();
3985}
3986
3987bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003988 Run = ModuleHasARC(M);
3989 if (!Run)
3990 return false;
3991
John McCall9fbd3182011-06-15 23:37:01 +00003992 // These are initialized lazily.
3993 StoreStrongCallee = 0;
3994 RetainAutoreleaseCallee = 0;
3995 RetainAutoreleaseRVCallee = 0;
3996
3997 // Initialize RetainRVMarker.
3998 RetainRVMarker = 0;
3999 if (NamedMDNode *NMD =
4000 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4001 if (NMD->getNumOperands() == 1) {
4002 const MDNode *N = NMD->getOperand(0);
4003 if (N->getNumOperands() == 1)
4004 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4005 RetainRVMarker = S;
4006 }
4007
4008 return false;
4009}
4010
4011bool ObjCARCContract::runOnFunction(Function &F) {
4012 if (!EnableARCOpts)
4013 return false;
4014
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004015 // If nothing in the Module uses ARC, don't do anything.
4016 if (!Run)
4017 return false;
4018
John McCall9fbd3182011-06-15 23:37:01 +00004019 Changed = false;
4020 AA = &getAnalysis<AliasAnalysis>();
4021 DT = &getAnalysis<DominatorTree>();
4022
4023 PA.setAA(&getAnalysis<AliasAnalysis>());
4024
Dan Gohman0cdece42012-01-19 19:14:36 +00004025 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4026 // keyword. Be conservative if the function has variadic arguments.
4027 // It seems that functions which "return twice" are also unsafe for the
4028 // "tail" argument, because they are setjmp, which could need to
4029 // return to an earlier stack state.
4030 bool TailOkForStoreStrongs = !F.isVarArg() && !F.callsFunctionThatReturnsTwice();
4031
John McCall9fbd3182011-06-15 23:37:01 +00004032 // For ObjC library calls which return their argument, replace uses of the
4033 // argument with uses of the call return value, if it dominates the use. This
4034 // reduces register pressure.
4035 SmallPtrSet<Instruction *, 4> DependingInstructions;
4036 SmallPtrSet<const BasicBlock *, 4> Visited;
4037 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4038 Instruction *Inst = &*I++;
4039
4040 // Only these library routines return their argument. In particular,
4041 // objc_retainBlock does not necessarily return its argument.
4042 InstructionClass Class = GetBasicInstructionClass(Inst);
4043 switch (Class) {
4044 case IC_Retain:
4045 case IC_FusedRetainAutorelease:
4046 case IC_FusedRetainAutoreleaseRV:
4047 break;
4048 case IC_Autorelease:
4049 case IC_AutoreleaseRV:
4050 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4051 continue;
4052 break;
4053 case IC_RetainRV: {
4054 // If we're compiling for a target which needs a special inline-asm
4055 // marker to do the retainAutoreleasedReturnValue optimization,
4056 // insert it now.
4057 if (!RetainRVMarker)
4058 break;
4059 BasicBlock::iterator BBI = Inst;
4060 --BBI;
4061 while (isNoopInstruction(BBI)) --BBI;
4062 if (&*BBI == GetObjCArg(Inst)) {
4063 InlineAsm *IA =
4064 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4065 /*isVarArg=*/false),
4066 RetainRVMarker->getString(),
4067 /*Constraints=*/"", /*hasSideEffects=*/true);
4068 CallInst::Create(IA, "", Inst);
4069 }
4070 break;
4071 }
4072 case IC_InitWeak: {
4073 // objc_initWeak(p, null) => *p = null
4074 CallInst *CI = cast<CallInst>(Inst);
4075 if (isNullOrUndef(CI->getArgOperand(1))) {
4076 Value *Null =
4077 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4078 Changed = true;
4079 new StoreInst(Null, CI->getArgOperand(0), CI);
4080 CI->replaceAllUsesWith(Null);
4081 CI->eraseFromParent();
4082 }
4083 continue;
4084 }
4085 case IC_Release:
4086 ContractRelease(Inst, I);
4087 continue;
Dan Gohman0cdece42012-01-19 19:14:36 +00004088 case IC_User:
4089 // Be conservative if the function has any alloca instructions.
4090 // Technically we only care about escaping alloca instructions,
4091 // but this is sufficient to handle some interesting cases.
4092 if (isa<AllocaInst>(Inst))
4093 TailOkForStoreStrongs = false;
4094 continue;
John McCall9fbd3182011-06-15 23:37:01 +00004095 default:
4096 continue;
4097 }
4098
4099 // Don't use GetObjCArg because we don't want to look through bitcasts
4100 // and such; to do the replacement, the argument must have type i8*.
4101 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4102 for (;;) {
4103 // If we're compiling bugpointed code, don't get in trouble.
4104 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4105 break;
4106 // Look through the uses of the pointer.
4107 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4108 UI != UE; ) {
4109 Use &U = UI.getUse();
4110 unsigned OperandNo = UI.getOperandNo();
4111 ++UI; // Increment UI now, because we may unlink its element.
Rafael Espindola2453dff2012-03-15 15:52:59 +00004112 Instruction *UserInst = dyn_cast<Instruction>(U.getUser());
4113 if (!UserInst)
4114 continue;
4115 // FIXME: dominates should return true for unreachable UserInst.
Dan Gohman036ebfd2012-04-05 20:27:21 +00004116 if (DT->isReachableFromEntry(UserInst->getParent()) &&
Rafael Espindola2453dff2012-03-15 15:52:59 +00004117 DT->dominates(Inst, UserInst)) {
4118 Changed = true;
4119 Instruction *Replacement = Inst;
4120 Type *UseTy = U.get()->getType();
4121 if (PHINode *PHI = dyn_cast<PHINode>(UserInst)) {
4122 // For PHI nodes, insert the bitcast in the predecessor block.
4123 unsigned ValNo =
4124 PHINode::getIncomingValueNumForOperand(OperandNo);
4125 BasicBlock *BB =
4126 PHI->getIncomingBlock(ValNo);
4127 if (Replacement->getType() != UseTy)
4128 Replacement = new BitCastInst(Replacement, UseTy, "",
4129 &BB->back());
4130 for (unsigned i = 0, e = PHI->getNumIncomingValues();
4131 i != e; ++i)
4132 if (PHI->getIncomingBlock(i) == BB) {
4133 // Keep the UI iterator valid.
4134 if (&PHI->getOperandUse(
4135 PHINode::getOperandNumForIncomingValue(i)) ==
4136 &UI.getUse())
4137 ++UI;
4138 PHI->setIncomingValue(i, Replacement);
4139 }
4140 } else {
4141 if (Replacement->getType() != UseTy)
4142 Replacement = new BitCastInst(Replacement, UseTy, "", UserInst);
4143 U.set(Replacement);
John McCall9fbd3182011-06-15 23:37:01 +00004144 }
Rafael Espindola2453dff2012-03-15 15:52:59 +00004145 }
John McCall9fbd3182011-06-15 23:37:01 +00004146 }
4147
4148 // If Arg is a no-op casted pointer, strip one level of casts and
4149 // iterate.
4150 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4151 Arg = BI->getOperand(0);
4152 else if (isa<GEPOperator>(Arg) &&
4153 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4154 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4155 else if (isa<GlobalAlias>(Arg) &&
4156 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4157 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4158 else
4159 break;
4160 }
4161 }
4162
Dan Gohman0cdece42012-01-19 19:14:36 +00004163 // If this function has no escaping allocas or suspicious vararg usage,
4164 // objc_storeStrong calls can be marked with the "tail" keyword.
4165 if (TailOkForStoreStrongs)
4166 for (DenseSet<CallInst *>::iterator I = StoreStrongCalls.begin(),
4167 E = StoreStrongCalls.end(); I != E; ++I)
4168 (*I)->setTailCall();
4169 StoreStrongCalls.clear();
4170
John McCall9fbd3182011-06-15 23:37:01 +00004171 return Changed;
4172}