blob: 8bebee471794973ec96e2b1afc42cacfe63db9ef [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,
1682 MapVector<Value *, RRInfo> &Retains,
1683 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001684 bool VisitBottomUp(BasicBlock *BB,
1685 DenseMap<const BasicBlock *, BBState> &BBStates,
1686 MapVector<Value *, RRInfo> &Retains);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001687 bool VisitInstructionTopDown(Instruction *Inst,
1688 DenseMap<Value *, RRInfo> &Releases,
1689 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001690 bool VisitTopDown(BasicBlock *BB,
1691 DenseMap<const BasicBlock *, BBState> &BBStates,
1692 DenseMap<Value *, RRInfo> &Releases);
1693 bool Visit(Function &F,
1694 DenseMap<const BasicBlock *, BBState> &BBStates,
1695 MapVector<Value *, RRInfo> &Retains,
1696 DenseMap<Value *, RRInfo> &Releases);
1697
1698 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1699 MapVector<Value *, RRInfo> &Retains,
1700 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00001701 SmallVectorImpl<Instruction *> &DeadInsts,
1702 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001703
1704 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1705 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00001706 DenseMap<Value *, RRInfo> &Releases,
1707 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001708
1709 void OptimizeWeakCalls(Function &F);
1710
1711 bool OptimizeSequences(Function &F);
1712
1713 void OptimizeReturns(Function &F);
1714
1715 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1716 virtual bool doInitialization(Module &M);
1717 virtual bool runOnFunction(Function &F);
1718 virtual void releaseMemory();
1719
1720 public:
1721 static char ID;
1722 ObjCARCOpt() : FunctionPass(ID) {
1723 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1724 }
1725 };
1726}
1727
1728char ObjCARCOpt::ID = 0;
1729INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1730 "objc-arc", "ObjC ARC optimization", false, false)
1731INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1732INITIALIZE_PASS_END(ObjCARCOpt,
1733 "objc-arc", "ObjC ARC optimization", false, false)
1734
1735Pass *llvm::createObjCARCOptPass() {
1736 return new ObjCARCOpt();
1737}
1738
1739void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1740 AU.addRequired<ObjCARCAliasAnalysis>();
1741 AU.addRequired<AliasAnalysis>();
1742 // ARC optimization doesn't currently split critical edges.
1743 AU.setPreservesCFG();
1744}
1745
Dan Gohman79522dc2012-01-13 00:39:07 +00001746bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1747 // Without the magic metadata tag, we have to assume this might be an
1748 // objc_retainBlock call inserted to convert a block pointer to an id,
1749 // in which case it really is needed.
1750 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1751 return false;
1752
1753 // If the pointer "escapes" (not including being used in a call),
1754 // the copy may be needed.
1755 if (DoesObjCBlockEscape(Inst))
1756 return false;
1757
1758 // Otherwise, it's not needed.
1759 return true;
1760}
1761
John McCall9fbd3182011-06-15 23:37:01 +00001762Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1763 if (!RetainRVCallee) {
1764 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001765 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1766 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001767 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001768 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00001769 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1770 AttrListPtr Attributes;
1771 Attributes.addAttr(~0u, Attribute::NoUnwind);
1772 RetainRVCallee =
1773 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
1774 Attributes);
1775 }
1776 return RetainRVCallee;
1777}
1778
1779Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1780 if (!AutoreleaseRVCallee) {
1781 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001782 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
1783 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001784 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001785 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00001786 FunctionType::get(I8X, Params, /*isVarArg=*/false);
1787 AttrListPtr Attributes;
1788 Attributes.addAttr(~0u, Attribute::NoUnwind);
1789 AutoreleaseRVCallee =
1790 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
1791 Attributes);
1792 }
1793 return AutoreleaseRVCallee;
1794}
1795
1796Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1797 if (!ReleaseCallee) {
1798 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001799 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001800 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1801 AttrListPtr Attributes;
1802 Attributes.addAttr(~0u, Attribute::NoUnwind);
1803 ReleaseCallee =
1804 M->getOrInsertFunction(
1805 "objc_release",
1806 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
1807 Attributes);
1808 }
1809 return ReleaseCallee;
1810}
1811
1812Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1813 if (!RetainCallee) {
1814 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001815 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001816 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1817 AttrListPtr Attributes;
1818 Attributes.addAttr(~0u, Attribute::NoUnwind);
1819 RetainCallee =
1820 M->getOrInsertFunction(
1821 "objc_retain",
1822 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1823 Attributes);
1824 }
1825 return RetainCallee;
1826}
1827
Dan Gohman44280692011-07-22 22:29:21 +00001828Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1829 if (!RetainBlockCallee) {
1830 LLVMContext &C = M->getContext();
1831 std::vector<Type *> Params;
1832 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1833 AttrListPtr Attributes;
Dan Gohman1d2fd752011-09-14 18:33:34 +00001834 // objc_retainBlock is not nounwind because it calls user copy constructors
1835 // which could theoretically throw.
Dan Gohman44280692011-07-22 22:29:21 +00001836 RetainBlockCallee =
1837 M->getOrInsertFunction(
1838 "objc_retainBlock",
1839 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1840 Attributes);
1841 }
1842 return RetainBlockCallee;
1843}
1844
John McCall9fbd3182011-06-15 23:37:01 +00001845Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1846 if (!AutoreleaseCallee) {
1847 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001848 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00001849 Params.push_back(PointerType::getUnqual(Type::getInt8Ty(C)));
1850 AttrListPtr Attributes;
1851 Attributes.addAttr(~0u, Attribute::NoUnwind);
1852 AutoreleaseCallee =
1853 M->getOrInsertFunction(
1854 "objc_autorelease",
1855 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
1856 Attributes);
1857 }
1858 return AutoreleaseCallee;
1859}
1860
1861/// CanAlterRefCount - Test whether the given instruction can result in a
1862/// reference count modification (positive or negative) for the pointer's
1863/// object.
1864static bool
1865CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1866 ProvenanceAnalysis &PA, InstructionClass Class) {
1867 switch (Class) {
1868 case IC_Autorelease:
1869 case IC_AutoreleaseRV:
1870 case IC_User:
1871 // These operations never directly modify a reference count.
1872 return false;
1873 default: break;
1874 }
1875
1876 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1877 assert(CS && "Only calls can alter reference counts!");
1878
1879 // See if AliasAnalysis can help us with the call.
1880 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1881 if (AliasAnalysis::onlyReadsMemory(MRB))
1882 return false;
1883 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1884 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1885 I != E; ++I) {
1886 const Value *Op = *I;
1887 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1888 return true;
1889 }
1890 return false;
1891 }
1892
1893 // Assume the worst.
1894 return true;
1895}
1896
1897/// CanUse - Test whether the given instruction can "use" the given pointer's
1898/// object in a way that requires the reference count to be positive.
1899static bool
1900CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1901 InstructionClass Class) {
1902 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1903 if (Class == IC_Call)
1904 return false;
1905
1906 // Consider various instructions which may have pointer arguments which are
1907 // not "uses".
1908 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1909 // Comparing a pointer with null, or any other constant, isn't really a use,
1910 // because we don't care what the pointer points to, or about the values
1911 // of any other dynamic reference-counted pointers.
1912 if (!IsPotentialUse(ICI->getOperand(1)))
1913 return false;
1914 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1915 // For calls, just check the arguments (and not the callee operand).
1916 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1917 OE = CS.arg_end(); OI != OE; ++OI) {
1918 const Value *Op = *OI;
1919 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1920 return true;
1921 }
1922 return false;
1923 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1924 // Special-case stores, because we don't care about the stored value, just
1925 // the store address.
1926 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1927 // If we can't tell what the underlying object was, assume there is a
1928 // dependence.
1929 return IsPotentialUse(Op) && PA.related(Op, Ptr);
1930 }
1931
1932 // Check each operand for a match.
1933 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1934 OI != OE; ++OI) {
1935 const Value *Op = *OI;
1936 if (IsPotentialUse(Op) && PA.related(Ptr, Op))
1937 return true;
1938 }
1939 return false;
1940}
1941
1942/// CanInterruptRV - Test whether the given instruction can autorelease
1943/// any pointer or cause an autoreleasepool pop.
1944static bool
1945CanInterruptRV(InstructionClass Class) {
1946 switch (Class) {
1947 case IC_AutoreleasepoolPop:
1948 case IC_CallOrUser:
1949 case IC_Call:
1950 case IC_Autorelease:
1951 case IC_AutoreleaseRV:
1952 case IC_FusedRetainAutorelease:
1953 case IC_FusedRetainAutoreleaseRV:
1954 return true;
1955 default:
1956 return false;
1957 }
1958}
1959
1960namespace {
1961 /// DependenceKind - There are several kinds of dependence-like concepts in
1962 /// use here.
1963 enum DependenceKind {
1964 NeedsPositiveRetainCount,
1965 CanChangeRetainCount,
1966 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
1967 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
1968 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
1969 };
1970}
1971
1972/// Depends - Test if there can be dependencies on Inst through Arg. This
1973/// function only tests dependencies relevant for removing pairs of calls.
1974static bool
1975Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
1976 ProvenanceAnalysis &PA) {
1977 // If we've reached the definition of Arg, stop.
1978 if (Inst == Arg)
1979 return true;
1980
1981 switch (Flavor) {
1982 case NeedsPositiveRetainCount: {
1983 InstructionClass Class = GetInstructionClass(Inst);
1984 switch (Class) {
1985 case IC_AutoreleasepoolPop:
1986 case IC_AutoreleasepoolPush:
1987 case IC_None:
1988 return false;
1989 default:
1990 return CanUse(Inst, Arg, PA, Class);
1991 }
1992 }
1993
1994 case CanChangeRetainCount: {
1995 InstructionClass Class = GetInstructionClass(Inst);
1996 switch (Class) {
1997 case IC_AutoreleasepoolPop:
1998 // Conservatively assume this can decrement any count.
1999 return true;
2000 case IC_AutoreleasepoolPush:
2001 case IC_None:
2002 return false;
2003 default:
2004 return CanAlterRefCount(Inst, Arg, PA, Class);
2005 }
2006 }
2007
2008 case RetainAutoreleaseDep:
2009 switch (GetBasicInstructionClass(Inst)) {
2010 case IC_AutoreleasepoolPop:
2011 // Don't merge an objc_autorelease with an objc_retain inside a different
2012 // autoreleasepool scope.
2013 return true;
2014 case IC_Retain:
2015 case IC_RetainRV:
2016 // Check for a retain of the same pointer for merging.
2017 return GetObjCArg(Inst) == Arg;
2018 default:
2019 // Nothing else matters for objc_retainAutorelease formation.
2020 return false;
2021 }
John McCall9fbd3182011-06-15 23:37:01 +00002022
2023 case RetainAutoreleaseRVDep: {
2024 InstructionClass Class = GetBasicInstructionClass(Inst);
2025 switch (Class) {
2026 case IC_Retain:
2027 case IC_RetainRV:
2028 // Check for a retain of the same pointer for merging.
2029 return GetObjCArg(Inst) == Arg;
2030 default:
2031 // Anything that can autorelease interrupts
2032 // retainAutoreleaseReturnValue formation.
2033 return CanInterruptRV(Class);
2034 }
John McCall9fbd3182011-06-15 23:37:01 +00002035 }
2036
2037 case RetainRVDep:
2038 return CanInterruptRV(GetBasicInstructionClass(Inst));
2039 }
2040
2041 llvm_unreachable("Invalid dependence flavor");
John McCall9fbd3182011-06-15 23:37:01 +00002042}
2043
2044/// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2045/// find local and non-local dependencies on Arg.
2046/// TODO: Cache results?
2047static void
2048FindDependencies(DependenceKind Flavor,
2049 const Value *Arg,
2050 BasicBlock *StartBB, Instruction *StartInst,
2051 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2052 SmallPtrSet<const BasicBlock *, 4> &Visited,
2053 ProvenanceAnalysis &PA) {
2054 BasicBlock::iterator StartPos = StartInst;
2055
2056 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2057 Worklist.push_back(std::make_pair(StartBB, StartPos));
2058 do {
2059 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2060 Worklist.pop_back_val();
2061 BasicBlock *LocalStartBB = Pair.first;
2062 BasicBlock::iterator LocalStartPos = Pair.second;
2063 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2064 for (;;) {
2065 if (LocalStartPos == StartBBBegin) {
2066 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2067 if (PI == PE)
2068 // If we've reached the function entry, produce a null dependence.
2069 DependingInstructions.insert(0);
2070 else
2071 // Add the predecessors to the worklist.
2072 do {
2073 BasicBlock *PredBB = *PI;
2074 if (Visited.insert(PredBB))
2075 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2076 } while (++PI != PE);
2077 break;
2078 }
2079
2080 Instruction *Inst = --LocalStartPos;
2081 if (Depends(Flavor, Inst, Arg, PA)) {
2082 DependingInstructions.insert(Inst);
2083 break;
2084 }
2085 }
2086 } while (!Worklist.empty());
2087
2088 // Determine whether the original StartBB post-dominates all of the blocks we
2089 // visited. If not, insert a sentinal indicating that most optimizations are
2090 // not safe.
2091 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2092 E = Visited.end(); I != E; ++I) {
2093 const BasicBlock *BB = *I;
2094 if (BB == StartBB)
2095 continue;
2096 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2097 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2098 const BasicBlock *Succ = *SI;
2099 if (Succ != StartBB && !Visited.count(Succ)) {
2100 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2101 return;
2102 }
2103 }
2104 }
2105}
2106
2107static bool isNullOrUndef(const Value *V) {
2108 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2109}
2110
2111static bool isNoopInstruction(const Instruction *I) {
2112 return isa<BitCastInst>(I) ||
2113 (isa<GetElementPtrInst>(I) &&
2114 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2115}
2116
2117/// OptimizeRetainCall - Turn objc_retain into
2118/// objc_retainAutoreleasedReturnValue if the operand is a return value.
2119void
2120ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
2121 CallSite CS(GetObjCArg(Retain));
2122 Instruction *Call = CS.getInstruction();
2123 if (!Call) return;
2124 if (Call->getParent() != Retain->getParent()) return;
2125
2126 // Check that the call is next to the retain.
2127 BasicBlock::iterator I = Call;
2128 ++I;
2129 while (isNoopInstruction(I)) ++I;
2130 if (&*I != Retain)
2131 return;
2132
2133 // Turn it to an objc_retainAutoreleasedReturnValue..
2134 Changed = true;
2135 ++NumPeeps;
2136 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2137}
2138
2139/// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
2140/// objc_retain if the operand is not a return value. Or, if it can be
2141/// paired with an objc_autoreleaseReturnValue, delete the pair and
2142/// return true.
2143bool
2144ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
2145 // Check for the argument being from an immediately preceding call.
2146 Value *Arg = GetObjCArg(RetainRV);
2147 CallSite CS(Arg);
2148 if (Instruction *Call = CS.getInstruction())
2149 if (Call->getParent() == RetainRV->getParent()) {
2150 BasicBlock::iterator I = Call;
2151 ++I;
2152 while (isNoopInstruction(I)) ++I;
2153 if (&*I == RetainRV)
2154 return false;
2155 }
2156
2157 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2158 // pointer. In this case, we can delete the pair.
2159 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2160 if (I != Begin) {
2161 do --I; while (I != Begin && isNoopInstruction(I));
2162 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2163 GetObjCArg(I) == Arg) {
2164 Changed = true;
2165 ++NumPeeps;
2166 EraseInstruction(I);
2167 EraseInstruction(RetainRV);
2168 return true;
2169 }
2170 }
2171
2172 // Turn it to a plain objc_retain.
2173 Changed = true;
2174 ++NumPeeps;
2175 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2176 return false;
2177}
2178
2179/// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2180/// objc_autorelease if the result is not used as a return value.
2181void
2182ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
2183 // Check for a return of the pointer value.
2184 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman126a54f2011-08-12 00:36:31 +00002185 SmallVector<const Value *, 2> Users;
2186 Users.push_back(Ptr);
2187 do {
2188 Ptr = Users.pop_back_val();
2189 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2190 UI != UE; ++UI) {
2191 const User *I = *UI;
2192 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2193 return;
2194 if (isa<BitCastInst>(I))
2195 Users.push_back(I);
2196 }
2197 } while (!Users.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002198
2199 Changed = true;
2200 ++NumPeeps;
2201 cast<CallInst>(AutoreleaseRV)->
2202 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2203}
2204
2205/// OptimizeIndividualCalls - Visit each call, one at a time, and make
2206/// simplifications without doing any additional analysis.
2207void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2208 // Reset all the flags in preparation for recomputing them.
2209 UsedInThisFunction = 0;
2210
2211 // Visit all objc_* calls in F.
2212 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2213 Instruction *Inst = &*I++;
2214 InstructionClass Class = GetBasicInstructionClass(Inst);
2215
2216 switch (Class) {
2217 default: break;
2218
2219 // Delete no-op casts. These function calls have special semantics, but
2220 // the semantics are entirely implemented via lowering in the front-end,
2221 // so by the time they reach the optimizer, they are just no-op calls
2222 // which return their argument.
2223 //
2224 // There are gray areas here, as the ability to cast reference-counted
2225 // pointers to raw void* and back allows code to break ARC assumptions,
2226 // however these are currently considered to be unimportant.
2227 case IC_NoopCast:
2228 Changed = true;
2229 ++NumNoops;
2230 EraseInstruction(Inst);
2231 continue;
2232
2233 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2234 case IC_StoreWeak:
2235 case IC_LoadWeak:
2236 case IC_LoadWeakRetained:
2237 case IC_InitWeak:
2238 case IC_DestroyWeak: {
2239 CallInst *CI = cast<CallInst>(Inst);
2240 if (isNullOrUndef(CI->getArgOperand(0))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002241 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002242 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2243 Constant::getNullValue(Ty),
2244 CI);
2245 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2246 CI->eraseFromParent();
2247 continue;
2248 }
2249 break;
2250 }
2251 case IC_CopyWeak:
2252 case IC_MoveWeak: {
2253 CallInst *CI = cast<CallInst>(Inst);
2254 if (isNullOrUndef(CI->getArgOperand(0)) ||
2255 isNullOrUndef(CI->getArgOperand(1))) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002256 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002257 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2258 Constant::getNullValue(Ty),
2259 CI);
2260 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2261 CI->eraseFromParent();
2262 continue;
2263 }
2264 break;
2265 }
2266 case IC_Retain:
2267 OptimizeRetainCall(F, Inst);
2268 break;
2269 case IC_RetainRV:
2270 if (OptimizeRetainRVCall(F, Inst))
2271 continue;
2272 break;
2273 case IC_AutoreleaseRV:
2274 OptimizeAutoreleaseRVCall(F, Inst);
2275 break;
2276 }
2277
2278 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2279 if (IsAutorelease(Class) && Inst->use_empty()) {
2280 CallInst *Call = cast<CallInst>(Inst);
2281 const Value *Arg = Call->getArgOperand(0);
2282 Arg = FindSingleUseIdentifiedObject(Arg);
2283 if (Arg) {
2284 Changed = true;
2285 ++NumAutoreleases;
2286
2287 // Create the declaration lazily.
2288 LLVMContext &C = Inst->getContext();
2289 CallInst *NewCall =
2290 CallInst::Create(getReleaseCallee(F.getParent()),
2291 Call->getArgOperand(0), "", Call);
2292 NewCall->setMetadata(ImpreciseReleaseMDKind,
2293 MDNode::get(C, ArrayRef<Value *>()));
2294 EraseInstruction(Call);
2295 Inst = NewCall;
2296 Class = IC_Release;
2297 }
2298 }
2299
2300 // For functions which can never be passed stack arguments, add
2301 // a tail keyword.
2302 if (IsAlwaysTail(Class)) {
2303 Changed = true;
2304 cast<CallInst>(Inst)->setTailCall();
2305 }
2306
2307 // Set nounwind as needed.
2308 if (IsNoThrow(Class)) {
2309 Changed = true;
2310 cast<CallInst>(Inst)->setDoesNotThrow();
2311 }
2312
2313 if (!IsNoopOnNull(Class)) {
2314 UsedInThisFunction |= 1 << Class;
2315 continue;
2316 }
2317
2318 const Value *Arg = GetObjCArg(Inst);
2319
2320 // ARC calls with null are no-ops. Delete them.
2321 if (isNullOrUndef(Arg)) {
2322 Changed = true;
2323 ++NumNoops;
2324 EraseInstruction(Inst);
2325 continue;
2326 }
2327
2328 // Keep track of which of retain, release, autorelease, and retain_block
2329 // are actually present in this function.
2330 UsedInThisFunction |= 1 << Class;
2331
2332 // If Arg is a PHI, and one or more incoming values to the
2333 // PHI are null, and the call is control-equivalent to the PHI, and there
2334 // are no relevant side effects between the PHI and the call, the call
2335 // could be pushed up to just those paths with non-null incoming values.
2336 // For now, don't bother splitting critical edges for this.
2337 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2338 Worklist.push_back(std::make_pair(Inst, Arg));
2339 do {
2340 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2341 Inst = Pair.first;
2342 Arg = Pair.second;
2343
2344 const PHINode *PN = dyn_cast<PHINode>(Arg);
2345 if (!PN) continue;
2346
2347 // Determine if the PHI has any null operands, or any incoming
2348 // critical edges.
2349 bool HasNull = false;
2350 bool HasCriticalEdges = false;
2351 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2352 Value *Incoming =
2353 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2354 if (isNullOrUndef(Incoming))
2355 HasNull = true;
2356 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2357 .getNumSuccessors() != 1) {
2358 HasCriticalEdges = true;
2359 break;
2360 }
2361 }
2362 // If we have null operands and no critical edges, optimize.
2363 if (!HasCriticalEdges && HasNull) {
2364 SmallPtrSet<Instruction *, 4> DependingInstructions;
2365 SmallPtrSet<const BasicBlock *, 4> Visited;
2366
2367 // Check that there is nothing that cares about the reference
2368 // count between the call and the phi.
2369 FindDependencies(NeedsPositiveRetainCount, Arg,
2370 Inst->getParent(), Inst,
2371 DependingInstructions, Visited, PA);
2372 if (DependingInstructions.size() == 1 &&
2373 *DependingInstructions.begin() == PN) {
2374 Changed = true;
2375 ++NumPartialNoops;
2376 // Clone the call into each predecessor that has a non-null value.
2377 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002378 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002379 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2380 Value *Incoming =
2381 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2382 if (!isNullOrUndef(Incoming)) {
2383 CallInst *Clone = cast<CallInst>(CInst->clone());
2384 Value *Op = PN->getIncomingValue(i);
2385 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2386 if (Op->getType() != ParamTy)
2387 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2388 Clone->setArgOperand(0, Op);
2389 Clone->insertBefore(InsertPos);
2390 Worklist.push_back(std::make_pair(Clone, Incoming));
2391 }
2392 }
2393 // Erase the original call.
2394 EraseInstruction(CInst);
2395 continue;
2396 }
2397 }
2398 } while (!Worklist.empty());
2399 }
2400}
2401
2402/// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2403/// control flow, or other CFG structures where moving code across the edge
2404/// would result in it being executed more.
2405void
2406ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2407 DenseMap<const BasicBlock *, BBState> &BBStates,
2408 BBState &MyStates) const {
2409 // If any top-down local-use or possible-dec has a succ which is earlier in
2410 // the sequence, forget it.
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002411 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCall9fbd3182011-06-15 23:37:01 +00002412 E = MyStates.top_down_ptr_end(); I != E; ++I)
2413 switch (I->second.GetSeq()) {
2414 default: break;
2415 case S_Use: {
2416 const Value *Arg = I->first;
2417 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2418 bool SomeSuccHasSame = false;
2419 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002420 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002421 succ_const_iterator SI(TI), SE(TI, false);
2422
2423 // If the terminator is an invoke marked with the
2424 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2425 // ignored, for ARC purposes.
2426 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2427 --SE;
2428
2429 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002430 Sequence SuccSSeq = S_None;
2431 bool SuccSRRIKnownSafe = false;
2432 // If VisitBottomUp has visited this successor, take what we know about it.
2433 DenseMap<const BasicBlock *, BBState>::iterator BBI = BBStates.find(*SI);
2434 if (BBI != BBStates.end()) {
2435 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2436 SuccSSeq = SuccS.GetSeq();
2437 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2438 }
2439 switch (SuccSSeq) {
John McCall9fbd3182011-06-15 23:37:01 +00002440 case S_None:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002441 case S_CanRelease: {
Dan Gohman70e29682012-03-02 01:26:46 +00002442 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002443 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002444 break;
2445 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002446 continue;
2447 }
John McCall9fbd3182011-06-15 23:37:01 +00002448 case S_Use:
2449 SomeSuccHasSame = true;
2450 break;
2451 case S_Stop:
2452 case S_Release:
2453 case S_MovableRelease:
Dan Gohman70e29682012-03-02 01:26:46 +00002454 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002455 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002456 break;
2457 case S_Retain:
2458 llvm_unreachable("bottom-up pointer in retain state!");
2459 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002460 }
John McCall9fbd3182011-06-15 23:37:01 +00002461 // If the state at the other end of any of the successor edges
2462 // matches the current state, require all edges to match. This
2463 // guards against loops in the middle of a sequence.
2464 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002465 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002466 break;
John McCall9fbd3182011-06-15 23:37:01 +00002467 }
2468 case S_CanRelease: {
2469 const Value *Arg = I->first;
2470 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2471 bool SomeSuccHasSame = false;
2472 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002473 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002474 succ_const_iterator SI(TI), SE(TI, false);
2475
2476 // If the terminator is an invoke marked with the
2477 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2478 // ignored, for ARC purposes.
2479 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2480 --SE;
2481
2482 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002483 Sequence SuccSSeq = S_None;
2484 bool SuccSRRIKnownSafe = false;
2485 // If VisitBottomUp has visited this successor, take what we know about it.
2486 DenseMap<const BasicBlock *, BBState>::iterator BBI = BBStates.find(*SI);
2487 if (BBI != BBStates.end()) {
2488 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2489 SuccSSeq = SuccS.GetSeq();
2490 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
2491 }
2492 switch (SuccSSeq) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002493 case S_None: {
Dan Gohman70e29682012-03-02 01:26:46 +00002494 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002495 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002496 break;
2497 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002498 continue;
2499 }
John McCall9fbd3182011-06-15 23:37:01 +00002500 case S_CanRelease:
2501 SomeSuccHasSame = true;
2502 break;
2503 case S_Stop:
2504 case S_Release:
2505 case S_MovableRelease:
2506 case S_Use:
Dan Gohman70e29682012-03-02 01:26:46 +00002507 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002508 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002509 break;
2510 case S_Retain:
2511 llvm_unreachable("bottom-up pointer in retain state!");
2512 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002513 }
John McCall9fbd3182011-06-15 23:37:01 +00002514 // If the state at the other end of any of the successor edges
2515 // matches the current state, require all edges to match. This
2516 // guards against loops in the middle of a sequence.
2517 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002518 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002519 break;
John McCall9fbd3182011-06-15 23:37:01 +00002520 }
2521 }
2522}
2523
2524bool
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002525ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
2526 MapVector<Value *, RRInfo> &Retains,
2527 BBState &MyStates) {
2528 bool NestingDetected = false;
2529 InstructionClass Class = GetInstructionClass(Inst);
2530 const Value *Arg = 0;
2531
2532 switch (Class) {
2533 case IC_Release: {
2534 Arg = GetObjCArg(Inst);
2535
2536 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2537
2538 // If we see two releases in a row on the same pointer. If so, make
2539 // a note, and we'll cicle back to revisit it after we've
2540 // hopefully eliminated the second release, which may allow us to
2541 // eliminate the first release too.
2542 // Theoretically we could implement removal of nested retain+release
2543 // pairs by making PtrState hold a stack of states, but this is
2544 // simple and avoids adding overhead for the non-nested case.
2545 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2546 NestingDetected = true;
2547
2548 S.RRI.clear();
2549
2550 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2551 S.SetSeq(ReleaseMetadata ? S_MovableRelease : S_Release);
2552 S.RRI.ReleaseMetadata = ReleaseMetadata;
2553 S.RRI.KnownSafe = S.IsKnownNested() || S.IsKnownIncremented();
2554 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2555 S.RRI.Calls.insert(Inst);
2556
2557 S.IncrementRefCount();
2558 S.IncrementNestCount();
2559 break;
2560 }
2561 case IC_RetainBlock:
2562 // An objc_retainBlock call with just a use may need to be kept,
2563 // because it may be copying a block from the stack to the heap.
2564 if (!IsRetainBlockOptimizable(Inst))
2565 break;
2566 // FALLTHROUGH
2567 case IC_Retain:
2568 case IC_RetainRV: {
2569 Arg = GetObjCArg(Inst);
2570
2571 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2572 S.DecrementRefCount();
2573 S.SetAtLeastOneRefCount();
2574 S.DecrementNestCount();
2575
2576 switch (S.GetSeq()) {
2577 case S_Stop:
2578 case S_Release:
2579 case S_MovableRelease:
2580 case S_Use:
2581 S.RRI.ReverseInsertPts.clear();
2582 // FALL THROUGH
2583 case S_CanRelease:
2584 // Don't do retain+release tracking for IC_RetainRV, because it's
2585 // better to let it remain as the first instruction after a call.
2586 if (Class != IC_RetainRV) {
2587 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2588 Retains[Inst] = S.RRI;
2589 }
2590 S.ClearSequenceProgress();
2591 break;
2592 case S_None:
2593 break;
2594 case S_Retain:
2595 llvm_unreachable("bottom-up pointer in retain state!");
2596 }
2597 return NestingDetected;
2598 }
2599 case IC_AutoreleasepoolPop:
2600 // Conservatively, clear MyStates for all known pointers.
2601 MyStates.clearBottomUpPointers();
2602 return NestingDetected;
2603 case IC_AutoreleasepoolPush:
2604 case IC_None:
2605 // These are irrelevant.
2606 return NestingDetected;
2607 default:
2608 break;
2609 }
2610
2611 // Consider any other possible effects of this instruction on each
2612 // pointer being tracked.
2613 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2614 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2615 const Value *Ptr = MI->first;
2616 if (Ptr == Arg)
2617 continue; // Handled above.
2618 PtrState &S = MI->second;
2619 Sequence Seq = S.GetSeq();
2620
2621 // Check for possible releases.
2622 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
2623 S.DecrementRefCount();
2624 switch (Seq) {
2625 case S_Use:
2626 S.SetSeq(S_CanRelease);
2627 continue;
2628 case S_CanRelease:
2629 case S_Release:
2630 case S_MovableRelease:
2631 case S_Stop:
2632 case S_None:
2633 break;
2634 case S_Retain:
2635 llvm_unreachable("bottom-up pointer in retain state!");
2636 }
2637 }
2638
2639 // Check for possible direct uses.
2640 switch (Seq) {
2641 case S_Release:
2642 case S_MovableRelease:
2643 if (CanUse(Inst, Ptr, PA, Class)) {
2644 assert(S.RRI.ReverseInsertPts.empty());
2645 S.RRI.ReverseInsertPts.insert(Inst);
2646 S.SetSeq(S_Use);
2647 } else if (Seq == S_Release &&
2648 (Class == IC_User || Class == IC_CallOrUser)) {
2649 // Non-movable releases depend on any possible objc pointer use.
2650 S.SetSeq(S_Stop);
2651 assert(S.RRI.ReverseInsertPts.empty());
2652 S.RRI.ReverseInsertPts.insert(Inst);
2653 }
2654 break;
2655 case S_Stop:
2656 if (CanUse(Inst, Ptr, PA, Class))
2657 S.SetSeq(S_Use);
2658 break;
2659 case S_CanRelease:
2660 case S_Use:
2661 case S_None:
2662 break;
2663 case S_Retain:
2664 llvm_unreachable("bottom-up pointer in retain state!");
2665 }
2666 }
2667
2668 return NestingDetected;
2669}
2670
2671bool
John McCall9fbd3182011-06-15 23:37:01 +00002672ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2673 DenseMap<const BasicBlock *, BBState> &BBStates,
2674 MapVector<Value *, RRInfo> &Retains) {
2675 bool NestingDetected = false;
2676 BBState &MyStates = BBStates[BB];
2677
2678 // Merge the states from each successor to compute the initial state
2679 // for the current block.
2680 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2681 succ_const_iterator SI(TI), SE(TI, false);
2682 if (SI == SE)
2683 MyStates.SetAsExit();
Dan Gohmandbe266b2012-02-17 18:59:53 +00002684 else {
2685 // If the terminator is an invoke marked with the
2686 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2687 // ignored, for ARC purposes.
2688 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2689 --SE;
2690
John McCall9fbd3182011-06-15 23:37:01 +00002691 do {
2692 const BasicBlock *Succ = *SI++;
2693 if (Succ == BB)
2694 continue;
2695 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
Dan Gohmana7f7db22011-08-12 00:26:31 +00002696 // If we haven't seen this node yet, then we've found a CFG cycle.
2697 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
John McCall9fbd3182011-06-15 23:37:01 +00002698 if (I == BBStates.end())
2699 continue;
2700 MyStates.InitFromSucc(I->second);
2701 while (SI != SE) {
2702 Succ = *SI++;
2703 if (Succ != BB) {
2704 I = BBStates.find(Succ);
2705 if (I != BBStates.end())
2706 MyStates.MergeSucc(I->second);
2707 }
2708 }
2709 break;
2710 } while (SI != SE);
Dan Gohmandbe266b2012-02-17 18:59:53 +00002711 }
John McCall9fbd3182011-06-15 23:37:01 +00002712
2713 // Visit all the instructions, bottom-up.
2714 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2715 Instruction *Inst = llvm::prior(I);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002716 NestingDetected |= VisitInstructionBottomUp(Inst, Retains, MyStates);
2717 }
John McCall9fbd3182011-06-15 23:37:01 +00002718
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002719 return NestingDetected;
2720}
John McCall9fbd3182011-06-15 23:37:01 +00002721
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002722bool
2723ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2724 DenseMap<Value *, RRInfo> &Releases,
2725 BBState &MyStates) {
2726 bool NestingDetected = false;
2727 InstructionClass Class = GetInstructionClass(Inst);
2728 const Value *Arg = 0;
John McCall9fbd3182011-06-15 23:37:01 +00002729
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002730 switch (Class) {
2731 case IC_RetainBlock:
2732 // An objc_retainBlock call with just a use may need to be kept,
2733 // because it may be copying a block from the stack to the heap.
2734 if (!IsRetainBlockOptimizable(Inst))
2735 break;
2736 // FALLTHROUGH
2737 case IC_Retain:
2738 case IC_RetainRV: {
2739 Arg = GetObjCArg(Inst);
2740
2741 PtrState &S = MyStates.getPtrTopDownState(Arg);
2742
2743 // Don't do retain+release tracking for IC_RetainRV, because it's
2744 // better to let it remain as the first instruction after a call.
2745 if (Class != IC_RetainRV) {
2746 // If we see two retains in a row on the same pointer. If so, make
John McCall9fbd3182011-06-15 23:37:01 +00002747 // a note, and we'll cicle back to revisit it after we've
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002748 // hopefully eliminated the second retain, which may allow us to
2749 // eliminate the first retain too.
John McCall9fbd3182011-06-15 23:37:01 +00002750 // Theoretically we could implement removal of nested retain+release
2751 // pairs by making PtrState hold a stack of states, but this is
2752 // simple and avoids adding overhead for the non-nested case.
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002753 if (S.GetSeq() == S_Retain)
John McCall9fbd3182011-06-15 23:37:01 +00002754 NestingDetected = true;
2755
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002756 S.SetSeq(S_Retain);
John McCall9fbd3182011-06-15 23:37:01 +00002757 S.RRI.clear();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002758 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2759 // Don't check S.IsKnownIncremented() here because it's not
2760 // sufficient.
2761 S.RRI.KnownSafe = S.IsKnownNested();
John McCall9fbd3182011-06-15 23:37:01 +00002762 S.RRI.Calls.insert(Inst);
John McCall9fbd3182011-06-15 23:37:01 +00002763 }
John McCall9fbd3182011-06-15 23:37:01 +00002764
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002765 S.SetAtLeastOneRefCount();
2766 S.IncrementRefCount();
2767 S.IncrementNestCount();
2768 return NestingDetected;
2769 }
2770 case IC_Release: {
2771 Arg = GetObjCArg(Inst);
2772
2773 PtrState &S = MyStates.getPtrTopDownState(Arg);
2774 S.DecrementRefCount();
2775 S.DecrementNestCount();
2776
2777 switch (S.GetSeq()) {
2778 case S_Retain:
2779 case S_CanRelease:
2780 S.RRI.ReverseInsertPts.clear();
2781 // FALL THROUGH
2782 case S_Use:
2783 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2784 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2785 Releases[Inst] = S.RRI;
2786 S.ClearSequenceProgress();
2787 break;
2788 case S_None:
2789 break;
2790 case S_Stop:
2791 case S_Release:
2792 case S_MovableRelease:
2793 llvm_unreachable("top-down pointer in release state!");
2794 }
2795 break;
2796 }
2797 case IC_AutoreleasepoolPop:
2798 // Conservatively, clear MyStates for all known pointers.
2799 MyStates.clearTopDownPointers();
2800 return NestingDetected;
2801 case IC_AutoreleasepoolPush:
2802 case IC_None:
2803 // These are irrelevant.
2804 return NestingDetected;
2805 default:
2806 break;
2807 }
2808
2809 // Consider any other possible effects of this instruction on each
2810 // pointer being tracked.
2811 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2812 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2813 const Value *Ptr = MI->first;
2814 if (Ptr == Arg)
2815 continue; // Handled above.
2816 PtrState &S = MI->second;
2817 Sequence Seq = S.GetSeq();
2818
2819 // Check for possible releases.
2820 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
John McCall9fbd3182011-06-15 23:37:01 +00002821 S.DecrementRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00002822 switch (Seq) {
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002823 case S_Retain:
2824 S.SetSeq(S_CanRelease);
2825 assert(S.RRI.ReverseInsertPts.empty());
2826 S.RRI.ReverseInsertPts.insert(Inst);
2827
2828 // One call can't cause a transition from S_Retain to S_CanRelease
2829 // and S_CanRelease to S_Use. If we've made the first transition,
2830 // we're done.
2831 continue;
John McCall9fbd3182011-06-15 23:37:01 +00002832 case S_Use:
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002833 case S_CanRelease:
John McCall9fbd3182011-06-15 23:37:01 +00002834 case S_None:
2835 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002836 case S_Stop:
2837 case S_Release:
2838 case S_MovableRelease:
2839 llvm_unreachable("top-down pointer in release state!");
John McCall9fbd3182011-06-15 23:37:01 +00002840 }
2841 }
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002842
2843 // Check for possible direct uses.
2844 switch (Seq) {
2845 case S_CanRelease:
2846 if (CanUse(Inst, Ptr, PA, Class))
2847 S.SetSeq(S_Use);
2848 break;
2849 case S_Retain:
2850 case S_Use:
2851 case S_None:
2852 break;
2853 case S_Stop:
2854 case S_Release:
2855 case S_MovableRelease:
2856 llvm_unreachable("top-down pointer in release state!");
2857 }
John McCall9fbd3182011-06-15 23:37:01 +00002858 }
2859
2860 return NestingDetected;
2861}
2862
2863bool
2864ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2865 DenseMap<const BasicBlock *, BBState> &BBStates,
2866 DenseMap<Value *, RRInfo> &Releases) {
2867 bool NestingDetected = false;
2868 BBState &MyStates = BBStates[BB];
2869
2870 // Merge the states from each predecessor to compute the initial state
2871 // for the current block.
2872 const_pred_iterator PI(BB), PE(BB, false);
2873 if (PI == PE)
2874 MyStates.SetAsEntry();
2875 else
2876 do {
Dan Gohmandbe266b2012-02-17 18:59:53 +00002877 unsigned OperandNo = PI.getOperandNo();
2878 const Use &Us = PI.getUse();
2879 ++PI;
2880
2881 // Skip invoke unwind edges on invoke instructions marked with
2882 // clang.arc.no_objc_arc_exceptions.
2883 if (const InvokeInst *II = dyn_cast<InvokeInst>(Us.getUser()))
2884 if (OperandNo == II->getNumArgOperands() + 2 &&
2885 II->getMetadata(NoObjCARCExceptionsMDKind))
2886 continue;
2887
2888 const BasicBlock *Pred = cast<TerminatorInst>(Us.getUser())->getParent();
John McCall9fbd3182011-06-15 23:37:01 +00002889 if (Pred == BB)
2890 continue;
2891 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
Dan Gohmana7f7db22011-08-12 00:26:31 +00002892 // If we haven't seen this node yet, then we've found a CFG cycle.
2893 // Be optimistic here; it's CheckForCFGHazards' job detect trouble.
Dan Gohman59a1c932011-12-12 19:42:25 +00002894 if (I == BBStates.end() || !I->second.isVisitedTopDown())
John McCall9fbd3182011-06-15 23:37:01 +00002895 continue;
2896 MyStates.InitFromPred(I->second);
2897 while (PI != PE) {
2898 Pred = *PI++;
2899 if (Pred != BB) {
2900 I = BBStates.find(Pred);
Dan Gohman48371602011-12-21 21:43:50 +00002901 if (I != BBStates.end() && I->second.isVisitedTopDown())
John McCall9fbd3182011-06-15 23:37:01 +00002902 MyStates.MergePred(I->second);
2903 }
2904 }
2905 break;
2906 } while (PI != PE);
2907
2908 // Visit all the instructions, top-down.
2909 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2910 Instruction *Inst = I;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002911 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00002912 }
2913
2914 CheckForCFGHazards(BB, BBStates, MyStates);
2915 return NestingDetected;
2916}
2917
Dan Gohman59a1c932011-12-12 19:42:25 +00002918static void
2919ComputePostOrders(Function &F,
2920 SmallVectorImpl<BasicBlock *> &PostOrder,
2921 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder) {
2922 /// Backedges - Backedges detected in the DFS. These edges will be
2923 /// ignored in the reverse-CFG DFS, so that loops with multiple exits will be
2924 /// traversed in the desired order.
2925 DenseSet<std::pair<BasicBlock *, BasicBlock *> > Backedges;
2926
2927 /// Visited - The visited set, for doing DFS walks.
2928 SmallPtrSet<BasicBlock *, 16> Visited;
2929
2930 // Do DFS, computing the PostOrder.
2931 SmallPtrSet<BasicBlock *, 16> OnStack;
2932 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
2933 BasicBlock *EntryBB = &F.getEntryBlock();
2934 SuccStack.push_back(std::make_pair(EntryBB, succ_begin(EntryBB)));
2935 Visited.insert(EntryBB);
2936 OnStack.insert(EntryBB);
2937 do {
2938 dfs_next_succ:
Dan Gohmandbe266b2012-02-17 18:59:53 +00002939 TerminatorInst *TI = cast<TerminatorInst>(&SuccStack.back().first->back());
2940 succ_iterator End = succ_iterator(TI, true);
Dan Gohman59a1c932011-12-12 19:42:25 +00002941 while (SuccStack.back().second != End) {
2942 BasicBlock *BB = *SuccStack.back().second++;
2943 if (Visited.insert(BB)) {
2944 SuccStack.push_back(std::make_pair(BB, succ_begin(BB)));
2945 OnStack.insert(BB);
2946 goto dfs_next_succ;
2947 }
2948 if (OnStack.count(BB))
2949 Backedges.insert(std::make_pair(SuccStack.back().first, BB));
2950 }
2951 OnStack.erase(SuccStack.back().first);
2952 PostOrder.push_back(SuccStack.pop_back_val().first);
2953 } while (!SuccStack.empty());
2954
2955 Visited.clear();
2956
2957 // Compute the exits, which are the starting points for reverse-CFG DFS.
Dan Gohman5992f672012-03-09 18:50:52 +00002958 // This includes blocks where all the successors are backedges that
2959 // we're skipping.
Dan Gohman59a1c932011-12-12 19:42:25 +00002960 SmallVector<BasicBlock *, 4> Exits;
2961 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2962 BasicBlock *BB = I;
Dan Gohman5992f672012-03-09 18:50:52 +00002963 TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2964 for (succ_iterator SI(TI), SE(TI, true); SI != SE; ++SI)
2965 if (!Backedges.count(std::make_pair(BB, *SI)))
2966 goto HasNonBackedgeSucc;
2967 Exits.push_back(BB);
2968 HasNonBackedgeSucc:;
Dan Gohman59a1c932011-12-12 19:42:25 +00002969 }
2970
2971 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
2972 SmallVector<std::pair<BasicBlock *, pred_iterator>, 16> PredStack;
2973 for (SmallVectorImpl<BasicBlock *>::iterator I = Exits.begin(), E = Exits.end();
2974 I != E; ++I) {
2975 BasicBlock *ExitBB = *I;
2976 PredStack.push_back(std::make_pair(ExitBB, pred_begin(ExitBB)));
2977 Visited.insert(ExitBB);
2978 while (!PredStack.empty()) {
2979 reverse_dfs_next_succ:
2980 pred_iterator End = pred_end(PredStack.back().first);
2981 while (PredStack.back().second != End) {
2982 BasicBlock *BB = *PredStack.back().second++;
2983 // Skip backedges detected in the forward-CFG DFS.
2984 if (Backedges.count(std::make_pair(BB, PredStack.back().first)))
2985 continue;
2986 if (Visited.insert(BB)) {
2987 PredStack.push_back(std::make_pair(BB, pred_begin(BB)));
2988 goto reverse_dfs_next_succ;
2989 }
2990 }
2991 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
2992 }
2993 }
2994}
2995
John McCall9fbd3182011-06-15 23:37:01 +00002996// Visit - Visit the function both top-down and bottom-up.
2997bool
2998ObjCARCOpt::Visit(Function &F,
2999 DenseMap<const BasicBlock *, BBState> &BBStates,
3000 MapVector<Value *, RRInfo> &Retains,
3001 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003002
3003 // Use reverse-postorder traversals, because we magically know that loops
3004 // will be well behaved, i.e. they won't repeatedly call retain on a single
3005 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3006 // class here because we want the reverse-CFG postorder to consider each
3007 // function exit point, and we want to ignore selected cycle edges.
3008 SmallVector<BasicBlock *, 16> PostOrder;
3009 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
3010 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder);
3011
3012 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCall9fbd3182011-06-15 23:37:01 +00003013 bool BottomUpNestingDetected = false;
Dan Gohmanb48ef3a2011-08-18 21:27:42 +00003014 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohman59a1c932011-12-12 19:42:25 +00003015 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3016 I != E; ++I)
3017 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCall9fbd3182011-06-15 23:37:01 +00003018
Dan Gohman59a1c932011-12-12 19:42:25 +00003019 // Use reverse-postorder for top-down.
John McCall9fbd3182011-06-15 23:37:01 +00003020 bool TopDownNestingDetected = false;
Dan Gohman59a1c932011-12-12 19:42:25 +00003021 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3022 PostOrder.rbegin(), E = PostOrder.rend();
3023 I != E; ++I)
3024 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCall9fbd3182011-06-15 23:37:01 +00003025
3026 return TopDownNestingDetected && BottomUpNestingDetected;
3027}
3028
3029/// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
3030void ObjCARCOpt::MoveCalls(Value *Arg,
3031 RRInfo &RetainsToMove,
3032 RRInfo &ReleasesToMove,
3033 MapVector<Value *, RRInfo> &Retains,
3034 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00003035 SmallVectorImpl<Instruction *> &DeadInsts,
3036 Module *M) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003037 Type *ArgTy = Arg->getType();
Dan Gohman44280692011-07-22 22:29:21 +00003038 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCall9fbd3182011-06-15 23:37:01 +00003039
3040 // Insert the new retain and release calls.
3041 for (SmallPtrSet<Instruction *, 2>::const_iterator
3042 PI = ReleasesToMove.ReverseInsertPts.begin(),
3043 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3044 Instruction *InsertPt = *PI;
3045 Value *MyArg = ArgTy == ParamTy ? Arg :
3046 new BitCastInst(Arg, ParamTy, "", InsertPt);
3047 CallInst *Call =
3048 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman44280692011-07-22 22:29:21 +00003049 getRetainBlockCallee(M) : getRetainCallee(M),
John McCall9fbd3182011-06-15 23:37:01 +00003050 MyArg, "", InsertPt);
3051 Call->setDoesNotThrow();
Dan Gohman79522dc2012-01-13 00:39:07 +00003052 if (RetainsToMove.IsRetainBlock)
Dan Gohmana974bea2011-10-17 22:53:25 +00003053 Call->setMetadata(CopyOnEscapeMDKind,
3054 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman79522dc2012-01-13 00:39:07 +00003055 else
John McCall9fbd3182011-06-15 23:37:01 +00003056 Call->setTailCall();
3057 }
3058 for (SmallPtrSet<Instruction *, 2>::const_iterator
3059 PI = RetainsToMove.ReverseInsertPts.begin(),
3060 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohman0860d0b2011-06-16 20:57:14 +00003061 Instruction *LastUse = *PI;
3062 Instruction *InsertPts[] = { 0, 0, 0 };
3063 if (InvokeInst *II = dyn_cast<InvokeInst>(LastUse)) {
3064 // We can't insert code immediately after an invoke instruction, so
3065 // insert code at the beginning of both successor blocks instead.
3066 // The invoke's return value isn't available in the unwind block,
3067 // but our releases will never depend on it, because they must be
3068 // paired with retains from before the invoke.
Bill Wendling89d44112011-08-25 01:08:34 +00003069 InsertPts[0] = II->getNormalDest()->getFirstInsertionPt();
Dan Gohman8b11fdd2012-03-14 23:05:06 +00003070 if (!II->getMetadata(NoObjCARCExceptionsMDKind))
3071 InsertPts[1] = II->getUnwindDest()->getFirstInsertionPt();
Dan Gohman0860d0b2011-06-16 20:57:14 +00003072 } else {
3073 // Insert code immediately after the last use.
3074 InsertPts[0] = llvm::next(BasicBlock::iterator(LastUse));
3075 }
3076
3077 for (Instruction **I = InsertPts; *I; ++I) {
3078 Instruction *InsertPt = *I;
3079 Value *MyArg = ArgTy == ParamTy ? Arg :
3080 new BitCastInst(Arg, ParamTy, "", InsertPt);
Dan Gohman44280692011-07-22 22:29:21 +00003081 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3082 "", InsertPt);
Dan Gohman0860d0b2011-06-16 20:57:14 +00003083 // Attach a clang.imprecise_release metadata tag, if appropriate.
3084 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3085 Call->setMetadata(ImpreciseReleaseMDKind, M);
3086 Call->setDoesNotThrow();
3087 if (ReleasesToMove.IsTailCallRelease)
3088 Call->setTailCall();
3089 }
John McCall9fbd3182011-06-15 23:37:01 +00003090 }
3091
3092 // Delete the original retain and release calls.
3093 for (SmallPtrSet<Instruction *, 2>::const_iterator
3094 AI = RetainsToMove.Calls.begin(),
3095 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3096 Instruction *OrigRetain = *AI;
3097 Retains.blot(OrigRetain);
3098 DeadInsts.push_back(OrigRetain);
3099 }
3100 for (SmallPtrSet<Instruction *, 2>::const_iterator
3101 AI = ReleasesToMove.Calls.begin(),
3102 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3103 Instruction *OrigRelease = *AI;
3104 Releases.erase(OrigRelease);
3105 DeadInsts.push_back(OrigRelease);
3106 }
3107}
3108
3109bool
3110ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3111 &BBStates,
3112 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00003113 DenseMap<Value *, RRInfo> &Releases,
3114 Module *M) {
John McCall9fbd3182011-06-15 23:37:01 +00003115 bool AnyPairsCompletelyEliminated = false;
3116 RRInfo RetainsToMove;
3117 RRInfo ReleasesToMove;
3118 SmallVector<Instruction *, 4> NewRetains;
3119 SmallVector<Instruction *, 4> NewReleases;
3120 SmallVector<Instruction *, 8> DeadInsts;
3121
3122 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman597fece2011-09-29 22:25:23 +00003123 E = Retains.end(); I != E; ++I) {
3124 Value *V = I->first;
John McCall9fbd3182011-06-15 23:37:01 +00003125 if (!V) continue; // blotted
3126
3127 Instruction *Retain = cast<Instruction>(V);
3128 Value *Arg = GetObjCArg(Retain);
3129
Dan Gohman79522dc2012-01-13 00:39:07 +00003130 // If the object being released is in static or stack storage, we know it's
John McCall9fbd3182011-06-15 23:37:01 +00003131 // not being managed by ObjC reference counting, so we can delete pairs
3132 // regardless of what possible decrements or uses lie between them.
Dan Gohman79522dc2012-01-13 00:39:07 +00003133 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman597fece2011-09-29 22:25:23 +00003134
Dan Gohman1b31ea82011-08-22 17:29:11 +00003135 // A constant pointer can't be pointing to an object on the heap. It may
3136 // be reference-counted, but it won't be deleted.
3137 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3138 if (const GlobalVariable *GV =
3139 dyn_cast<GlobalVariable>(
3140 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3141 if (GV->isConstant())
3142 KnownSafe = true;
3143
John McCall9fbd3182011-06-15 23:37:01 +00003144 // If a pair happens in a region where it is known that the reference count
3145 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmane6d5e882011-08-19 00:26:36 +00003146 bool KnownSafeTD = true, KnownSafeBU = true;
John McCall9fbd3182011-06-15 23:37:01 +00003147
3148 // Connect the dots between the top-down-collected RetainsToMove and
3149 // bottom-up-collected ReleasesToMove to form sets of related calls.
3150 // This is an iterative process so that we connect multiple releases
3151 // to multiple retains if needed.
3152 unsigned OldDelta = 0;
3153 unsigned NewDelta = 0;
3154 unsigned OldCount = 0;
3155 unsigned NewCount = 0;
3156 bool FirstRelease = true;
3157 bool FirstRetain = true;
3158 NewRetains.push_back(Retain);
3159 for (;;) {
3160 for (SmallVectorImpl<Instruction *>::const_iterator
3161 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3162 Instruction *NewRetain = *NI;
3163 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3164 assert(It != Retains.end());
3165 const RRInfo &NewRetainRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003166 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003167 for (SmallPtrSet<Instruction *, 2>::const_iterator
3168 LI = NewRetainRRI.Calls.begin(),
3169 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3170 Instruction *NewRetainRelease = *LI;
3171 DenseMap<Value *, RRInfo>::const_iterator Jt =
3172 Releases.find(NewRetainRelease);
3173 if (Jt == Releases.end())
3174 goto next_retain;
3175 const RRInfo &NewRetainReleaseRRI = Jt->second;
3176 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3177 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3178 OldDelta -=
3179 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3180
3181 // Merge the ReleaseMetadata and IsTailCallRelease values.
3182 if (FirstRelease) {
3183 ReleasesToMove.ReleaseMetadata =
3184 NewRetainReleaseRRI.ReleaseMetadata;
3185 ReleasesToMove.IsTailCallRelease =
3186 NewRetainReleaseRRI.IsTailCallRelease;
3187 FirstRelease = false;
3188 } else {
3189 if (ReleasesToMove.ReleaseMetadata !=
3190 NewRetainReleaseRRI.ReleaseMetadata)
3191 ReleasesToMove.ReleaseMetadata = 0;
3192 if (ReleasesToMove.IsTailCallRelease !=
3193 NewRetainReleaseRRI.IsTailCallRelease)
3194 ReleasesToMove.IsTailCallRelease = false;
3195 }
3196
3197 // Collect the optimal insertion points.
3198 if (!KnownSafe)
3199 for (SmallPtrSet<Instruction *, 2>::const_iterator
3200 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3201 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3202 RI != RE; ++RI) {
3203 Instruction *RIP = *RI;
3204 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3205 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3206 }
3207 NewReleases.push_back(NewRetainRelease);
3208 }
3209 }
3210 }
3211 NewRetains.clear();
3212 if (NewReleases.empty()) break;
3213
3214 // Back the other way.
3215 for (SmallVectorImpl<Instruction *>::const_iterator
3216 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3217 Instruction *NewRelease = *NI;
3218 DenseMap<Value *, RRInfo>::const_iterator It =
3219 Releases.find(NewRelease);
3220 assert(It != Releases.end());
3221 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003222 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003223 for (SmallPtrSet<Instruction *, 2>::const_iterator
3224 LI = NewReleaseRRI.Calls.begin(),
3225 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3226 Instruction *NewReleaseRetain = *LI;
3227 MapVector<Value *, RRInfo>::const_iterator Jt =
3228 Retains.find(NewReleaseRetain);
3229 if (Jt == Retains.end())
3230 goto next_retain;
3231 const RRInfo &NewReleaseRetainRRI = Jt->second;
3232 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3233 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3234 unsigned PathCount =
3235 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3236 OldDelta += PathCount;
3237 OldCount += PathCount;
3238
3239 // Merge the IsRetainBlock values.
3240 if (FirstRetain) {
3241 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3242 FirstRetain = false;
3243 } else if (ReleasesToMove.IsRetainBlock !=
3244 NewReleaseRetainRRI.IsRetainBlock)
3245 // It's not possible to merge the sequences if one uses
3246 // objc_retain and the other uses objc_retainBlock.
3247 goto next_retain;
3248
3249 // Collect the optimal insertion points.
3250 if (!KnownSafe)
3251 for (SmallPtrSet<Instruction *, 2>::const_iterator
3252 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3253 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3254 RI != RE; ++RI) {
3255 Instruction *RIP = *RI;
3256 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3257 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3258 NewDelta += PathCount;
3259 NewCount += PathCount;
3260 }
3261 }
3262 NewRetains.push_back(NewReleaseRetain);
3263 }
3264 }
3265 }
3266 NewReleases.clear();
3267 if (NewRetains.empty()) break;
3268 }
3269
Dan Gohmane6d5e882011-08-19 00:26:36 +00003270 // If the pointer is known incremented or nested, we can safely delete the
3271 // pair regardless of what's between them.
3272 if (KnownSafeTD || KnownSafeBU) {
John McCall9fbd3182011-06-15 23:37:01 +00003273 RetainsToMove.ReverseInsertPts.clear();
3274 ReleasesToMove.ReverseInsertPts.clear();
3275 NewCount = 0;
Dan Gohmana7f7db22011-08-12 00:26:31 +00003276 } else {
3277 // Determine whether the new insertion points we computed preserve the
3278 // balance of retain and release calls through the program.
3279 // TODO: If the fully aggressive solution isn't valid, try to find a
3280 // less aggressive solution which is.
3281 if (NewDelta != 0)
3282 goto next_retain;
John McCall9fbd3182011-06-15 23:37:01 +00003283 }
3284
3285 // Determine whether the original call points are balanced in the retain and
3286 // release calls through the program. If not, conservatively don't touch
3287 // them.
3288 // TODO: It's theoretically possible to do code motion in this case, as
3289 // long as the existing imbalances are maintained.
3290 if (OldDelta != 0)
3291 goto next_retain;
3292
John McCall9fbd3182011-06-15 23:37:01 +00003293 // Ok, everything checks out and we're all set. Let's move some code!
3294 Changed = true;
3295 AnyPairsCompletelyEliminated = NewCount == 0;
3296 NumRRs += OldCount - NewCount;
Dan Gohman44280692011-07-22 22:29:21 +00003297 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3298 Retains, Releases, DeadInsts, M);
John McCall9fbd3182011-06-15 23:37:01 +00003299
3300 next_retain:
3301 NewReleases.clear();
3302 NewRetains.clear();
3303 RetainsToMove.clear();
3304 ReleasesToMove.clear();
3305 }
3306
3307 // Now that we're done moving everything, we can delete the newly dead
3308 // instructions, as we no longer need them as insert points.
3309 while (!DeadInsts.empty())
3310 EraseInstruction(DeadInsts.pop_back_val());
3311
3312 return AnyPairsCompletelyEliminated;
3313}
3314
3315/// OptimizeWeakCalls - Weak pointer optimizations.
3316void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3317 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3318 // itself because it uses AliasAnalysis and we need to do provenance
3319 // queries instead.
3320 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3321 Instruction *Inst = &*I++;
3322 InstructionClass Class = GetBasicInstructionClass(Inst);
3323 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3324 continue;
3325
3326 // Delete objc_loadWeak calls with no users.
3327 if (Class == IC_LoadWeak && Inst->use_empty()) {
3328 Inst->eraseFromParent();
3329 continue;
3330 }
3331
3332 // TODO: For now, just look for an earlier available version of this value
3333 // within the same block. Theoretically, we could do memdep-style non-local
3334 // analysis too, but that would want caching. A better approach would be to
3335 // use the technique that EarlyCSE uses.
3336 inst_iterator Current = llvm::prior(I);
3337 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3338 for (BasicBlock::iterator B = CurrentBB->begin(),
3339 J = Current.getInstructionIterator();
3340 J != B; --J) {
3341 Instruction *EarlierInst = &*llvm::prior(J);
3342 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3343 switch (EarlierClass) {
3344 case IC_LoadWeak:
3345 case IC_LoadWeakRetained: {
3346 // If this is loading from the same pointer, replace this load's value
3347 // with that one.
3348 CallInst *Call = cast<CallInst>(Inst);
3349 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3350 Value *Arg = Call->getArgOperand(0);
3351 Value *EarlierArg = EarlierCall->getArgOperand(0);
3352 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3353 case AliasAnalysis::MustAlias:
3354 Changed = true;
3355 // If the load has a builtin retain, insert a plain retain for it.
3356 if (Class == IC_LoadWeakRetained) {
3357 CallInst *CI =
3358 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3359 "", Call);
3360 CI->setTailCall();
3361 }
3362 // Zap the fully redundant load.
3363 Call->replaceAllUsesWith(EarlierCall);
3364 Call->eraseFromParent();
3365 goto clobbered;
3366 case AliasAnalysis::MayAlias:
3367 case AliasAnalysis::PartialAlias:
3368 goto clobbered;
3369 case AliasAnalysis::NoAlias:
3370 break;
3371 }
3372 break;
3373 }
3374 case IC_StoreWeak:
3375 case IC_InitWeak: {
3376 // If this is storing to the same pointer and has the same size etc.
3377 // replace this load's value with the stored value.
3378 CallInst *Call = cast<CallInst>(Inst);
3379 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3380 Value *Arg = Call->getArgOperand(0);
3381 Value *EarlierArg = EarlierCall->getArgOperand(0);
3382 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3383 case AliasAnalysis::MustAlias:
3384 Changed = true;
3385 // If the load has a builtin retain, insert a plain retain for it.
3386 if (Class == IC_LoadWeakRetained) {
3387 CallInst *CI =
3388 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3389 "", Call);
3390 CI->setTailCall();
3391 }
3392 // Zap the fully redundant load.
3393 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3394 Call->eraseFromParent();
3395 goto clobbered;
3396 case AliasAnalysis::MayAlias:
3397 case AliasAnalysis::PartialAlias:
3398 goto clobbered;
3399 case AliasAnalysis::NoAlias:
3400 break;
3401 }
3402 break;
3403 }
3404 case IC_MoveWeak:
3405 case IC_CopyWeak:
3406 // TOOD: Grab the copied value.
3407 goto clobbered;
3408 case IC_AutoreleasepoolPush:
3409 case IC_None:
3410 case IC_User:
3411 // Weak pointers are only modified through the weak entry points
3412 // (and arbitrary calls, which could call the weak entry points).
3413 break;
3414 default:
3415 // Anything else could modify the weak pointer.
3416 goto clobbered;
3417 }
3418 }
3419 clobbered:;
3420 }
3421
3422 // Then, for each destroyWeak with an alloca operand, check to see if
3423 // the alloca and all its users can be zapped.
3424 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3425 Instruction *Inst = &*I++;
3426 InstructionClass Class = GetBasicInstructionClass(Inst);
3427 if (Class != IC_DestroyWeak)
3428 continue;
3429
3430 CallInst *Call = cast<CallInst>(Inst);
3431 Value *Arg = Call->getArgOperand(0);
3432 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3433 for (Value::use_iterator UI = Alloca->use_begin(),
3434 UE = Alloca->use_end(); UI != UE; ++UI) {
3435 Instruction *UserInst = cast<Instruction>(*UI);
3436 switch (GetBasicInstructionClass(UserInst)) {
3437 case IC_InitWeak:
3438 case IC_StoreWeak:
3439 case IC_DestroyWeak:
3440 continue;
3441 default:
3442 goto done;
3443 }
3444 }
3445 Changed = true;
3446 for (Value::use_iterator UI = Alloca->use_begin(),
3447 UE = Alloca->use_end(); UI != UE; ) {
3448 CallInst *UserInst = cast<CallInst>(*UI++);
3449 if (!UserInst->use_empty())
Dan Gohman8a9eebe2011-12-12 18:19:12 +00003450 UserInst->replaceAllUsesWith(UserInst->getArgOperand(0));
John McCall9fbd3182011-06-15 23:37:01 +00003451 UserInst->eraseFromParent();
3452 }
3453 Alloca->eraseFromParent();
3454 done:;
3455 }
3456 }
3457}
3458
3459/// OptimizeSequences - Identify program paths which execute sequences of
3460/// retains and releases which can be eliminated.
3461bool ObjCARCOpt::OptimizeSequences(Function &F) {
3462 /// Releases, Retains - These are used to store the results of the main flow
3463 /// analysis. These use Value* as the key instead of Instruction* so that the
3464 /// map stays valid when we get around to rewriting code and calls get
3465 /// replaced by arguments.
3466 DenseMap<Value *, RRInfo> Releases;
3467 MapVector<Value *, RRInfo> Retains;
3468
3469 /// BBStates, This is used during the traversal of the function to track the
3470 /// states for each identified object at each block.
3471 DenseMap<const BasicBlock *, BBState> BBStates;
3472
3473 // Analyze the CFG of the function, and all instructions.
3474 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3475
3476 // Transform.
Dan Gohman44280692011-07-22 22:29:21 +00003477 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3478 NestingDetected;
John McCall9fbd3182011-06-15 23:37:01 +00003479}
3480
3481/// OptimizeReturns - Look for this pattern:
3482///
3483/// %call = call i8* @something(...)
3484/// %2 = call i8* @objc_retain(i8* %call)
3485/// %3 = call i8* @objc_autorelease(i8* %2)
3486/// ret i8* %3
3487///
3488/// And delete the retain and autorelease.
3489///
3490/// Otherwise if it's just this:
3491///
3492/// %3 = call i8* @objc_autorelease(i8* %2)
3493/// ret i8* %3
3494///
3495/// convert the autorelease to autoreleaseRV.
3496void ObjCARCOpt::OptimizeReturns(Function &F) {
3497 if (!F.getReturnType()->isPointerTy())
3498 return;
3499
3500 SmallPtrSet<Instruction *, 4> DependingInstructions;
3501 SmallPtrSet<const BasicBlock *, 4> Visited;
3502 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3503 BasicBlock *BB = FI;
3504 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
3505 if (!Ret) continue;
3506
3507 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3508 FindDependencies(NeedsPositiveRetainCount, Arg,
3509 BB, Ret, DependingInstructions, Visited, PA);
3510 if (DependingInstructions.size() != 1)
3511 goto next_block;
3512
3513 {
3514 CallInst *Autorelease =
3515 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3516 if (!Autorelease)
3517 goto next_block;
3518 InstructionClass AutoreleaseClass =
3519 GetBasicInstructionClass(Autorelease);
3520 if (!IsAutorelease(AutoreleaseClass))
3521 goto next_block;
3522 if (GetObjCArg(Autorelease) != Arg)
3523 goto next_block;
3524
3525 DependingInstructions.clear();
3526 Visited.clear();
3527
3528 // Check that there is nothing that can affect the reference
3529 // count between the autorelease and the retain.
3530 FindDependencies(CanChangeRetainCount, Arg,
3531 BB, Autorelease, DependingInstructions, Visited, PA);
3532 if (DependingInstructions.size() != 1)
3533 goto next_block;
3534
3535 {
3536 CallInst *Retain =
3537 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3538
3539 // Check that we found a retain with the same argument.
3540 if (!Retain ||
3541 !IsRetain(GetBasicInstructionClass(Retain)) ||
3542 GetObjCArg(Retain) != Arg)
3543 goto next_block;
3544
3545 DependingInstructions.clear();
3546 Visited.clear();
3547
3548 // Convert the autorelease to an autoreleaseRV, since it's
3549 // returning the value.
3550 if (AutoreleaseClass == IC_Autorelease) {
3551 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3552 AutoreleaseClass = IC_AutoreleaseRV;
3553 }
3554
3555 // Check that there is nothing that can affect the reference
3556 // count between the retain and the call.
Dan Gohman27e06662011-09-29 22:27:34 +00003557 // Note that Retain need not be in BB.
3558 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCall9fbd3182011-06-15 23:37:01 +00003559 DependingInstructions, Visited, PA);
3560 if (DependingInstructions.size() != 1)
3561 goto next_block;
3562
3563 {
3564 CallInst *Call =
3565 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3566
3567 // Check that the pointer is the return value of the call.
3568 if (!Call || Arg != Call)
3569 goto next_block;
3570
3571 // Check that the call is a regular call.
3572 InstructionClass Class = GetBasicInstructionClass(Call);
3573 if (Class != IC_CallOrUser && Class != IC_Call)
3574 goto next_block;
3575
3576 // If so, we can zap the retain and autorelease.
3577 Changed = true;
3578 ++NumRets;
3579 EraseInstruction(Retain);
3580 EraseInstruction(Autorelease);
3581 }
3582 }
3583 }
3584
3585 next_block:
3586 DependingInstructions.clear();
3587 Visited.clear();
3588 }
3589}
3590
3591bool ObjCARCOpt::doInitialization(Module &M) {
3592 if (!EnableARCOpts)
3593 return false;
3594
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003595 Run = ModuleHasARC(M);
3596 if (!Run)
3597 return false;
3598
John McCall9fbd3182011-06-15 23:37:01 +00003599 // Identify the imprecise release metadata kind.
3600 ImpreciseReleaseMDKind =
3601 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana974bea2011-10-17 22:53:25 +00003602 CopyOnEscapeMDKind =
3603 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohmandbe266b2012-02-17 18:59:53 +00003604 NoObjCARCExceptionsMDKind =
3605 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCall9fbd3182011-06-15 23:37:01 +00003606
John McCall9fbd3182011-06-15 23:37:01 +00003607 // Intuitively, objc_retain and others are nocapture, however in practice
3608 // they are not, because they return their argument value. And objc_release
3609 // calls finalizers.
3610
3611 // These are initialized lazily.
3612 RetainRVCallee = 0;
3613 AutoreleaseRVCallee = 0;
3614 ReleaseCallee = 0;
3615 RetainCallee = 0;
Dan Gohman44280692011-07-22 22:29:21 +00003616 RetainBlockCallee = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003617 AutoreleaseCallee = 0;
3618
3619 return false;
3620}
3621
3622bool ObjCARCOpt::runOnFunction(Function &F) {
3623 if (!EnableARCOpts)
3624 return false;
3625
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003626 // If nothing in the Module uses ARC, don't do anything.
3627 if (!Run)
3628 return false;
3629
John McCall9fbd3182011-06-15 23:37:01 +00003630 Changed = false;
3631
3632 PA.setAA(&getAnalysis<AliasAnalysis>());
3633
3634 // This pass performs several distinct transformations. As a compile-time aid
3635 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3636 // library functions aren't declared.
3637
3638 // Preliminary optimizations. This also computs UsedInThisFunction.
3639 OptimizeIndividualCalls(F);
3640
3641 // Optimizations for weak pointers.
3642 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3643 (1 << IC_LoadWeakRetained) |
3644 (1 << IC_StoreWeak) |
3645 (1 << IC_InitWeak) |
3646 (1 << IC_CopyWeak) |
3647 (1 << IC_MoveWeak) |
3648 (1 << IC_DestroyWeak)))
3649 OptimizeWeakCalls(F);
3650
3651 // Optimizations for retain+release pairs.
3652 if (UsedInThisFunction & ((1 << IC_Retain) |
3653 (1 << IC_RetainRV) |
3654 (1 << IC_RetainBlock)))
3655 if (UsedInThisFunction & (1 << IC_Release))
3656 // Run OptimizeSequences until it either stops making changes or
3657 // no retain+release pair nesting is detected.
3658 while (OptimizeSequences(F)) {}
3659
3660 // Optimizations if objc_autorelease is used.
3661 if (UsedInThisFunction &
3662 ((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
3663 OptimizeReturns(F);
3664
3665 return Changed;
3666}
3667
3668void ObjCARCOpt::releaseMemory() {
3669 PA.clear();
3670}
3671
3672//===----------------------------------------------------------------------===//
3673// ARC contraction.
3674//===----------------------------------------------------------------------===//
3675
3676// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3677// dominated by single calls.
3678
3679#include "llvm/Operator.h"
3680#include "llvm/InlineAsm.h"
3681#include "llvm/Analysis/Dominators.h"
3682
3683STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3684
3685namespace {
3686 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3687 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3688 class ObjCARCContract : public FunctionPass {
3689 bool Changed;
3690 AliasAnalysis *AA;
3691 DominatorTree *DT;
3692 ProvenanceAnalysis PA;
3693
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003694 /// Run - A flag indicating whether this optimization pass should run.
3695 bool Run;
3696
John McCall9fbd3182011-06-15 23:37:01 +00003697 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3698 /// functions, for use in creating calls to them. These are initialized
3699 /// lazily to avoid cluttering up the Module with unused declarations.
3700 Constant *StoreStrongCallee,
3701 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3702
3703 /// RetainRVMarker - The inline asm string to insert between calls and
3704 /// RetainRV calls to make the optimization work on targets which need it.
3705 const MDString *RetainRVMarker;
3706
Dan Gohman0cdece42012-01-19 19:14:36 +00003707 /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
3708 /// at the end of walking the function we have found no alloca
3709 /// instructions, these calls can be marked "tail".
3710 DenseSet<CallInst *> StoreStrongCalls;
3711
John McCall9fbd3182011-06-15 23:37:01 +00003712 Constant *getStoreStrongCallee(Module *M);
3713 Constant *getRetainAutoreleaseCallee(Module *M);
3714 Constant *getRetainAutoreleaseRVCallee(Module *M);
3715
3716 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3717 InstructionClass Class,
3718 SmallPtrSet<Instruction *, 4>
3719 &DependingInstructions,
3720 SmallPtrSet<const BasicBlock *, 4>
3721 &Visited);
3722
3723 void ContractRelease(Instruction *Release,
3724 inst_iterator &Iter);
3725
3726 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3727 virtual bool doInitialization(Module &M);
3728 virtual bool runOnFunction(Function &F);
3729
3730 public:
3731 static char ID;
3732 ObjCARCContract() : FunctionPass(ID) {
3733 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3734 }
3735 };
3736}
3737
3738char ObjCARCContract::ID = 0;
3739INITIALIZE_PASS_BEGIN(ObjCARCContract,
3740 "objc-arc-contract", "ObjC ARC contraction", false, false)
3741INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3742INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3743INITIALIZE_PASS_END(ObjCARCContract,
3744 "objc-arc-contract", "ObjC ARC contraction", false, false)
3745
3746Pass *llvm::createObjCARCContractPass() {
3747 return new ObjCARCContract();
3748}
3749
3750void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3751 AU.addRequired<AliasAnalysis>();
3752 AU.addRequired<DominatorTree>();
3753 AU.setPreservesCFG();
3754}
3755
3756Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3757 if (!StoreStrongCallee) {
3758 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003759 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3760 Type *I8XX = PointerType::getUnqual(I8X);
3761 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003762 Params.push_back(I8XX);
3763 Params.push_back(I8X);
3764
3765 AttrListPtr Attributes;
3766 Attributes.addAttr(~0u, Attribute::NoUnwind);
3767 Attributes.addAttr(1, Attribute::NoCapture);
3768
3769 StoreStrongCallee =
3770 M->getOrInsertFunction(
3771 "objc_storeStrong",
3772 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
3773 Attributes);
3774 }
3775 return StoreStrongCallee;
3776}
3777
3778Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3779 if (!RetainAutoreleaseCallee) {
3780 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003781 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3782 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003783 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003784 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00003785 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3786 AttrListPtr Attributes;
3787 Attributes.addAttr(~0u, Attribute::NoUnwind);
3788 RetainAutoreleaseCallee =
3789 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
3790 }
3791 return RetainAutoreleaseCallee;
3792}
3793
3794Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3795 if (!RetainAutoreleaseRVCallee) {
3796 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003797 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3798 std::vector<Type *> Params;
John McCall9fbd3182011-06-15 23:37:01 +00003799 Params.push_back(I8X);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003800 FunctionType *FTy =
John McCall9fbd3182011-06-15 23:37:01 +00003801 FunctionType::get(I8X, Params, /*isVarArg=*/false);
3802 AttrListPtr Attributes;
3803 Attributes.addAttr(~0u, Attribute::NoUnwind);
3804 RetainAutoreleaseRVCallee =
3805 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
3806 Attributes);
3807 }
3808 return RetainAutoreleaseRVCallee;
3809}
3810
3811/// ContractAutorelease - Merge an autorelease with a retain into a fused
3812/// call.
3813bool
3814ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3815 InstructionClass Class,
3816 SmallPtrSet<Instruction *, 4>
3817 &DependingInstructions,
3818 SmallPtrSet<const BasicBlock *, 4>
3819 &Visited) {
3820 const Value *Arg = GetObjCArg(Autorelease);
3821
3822 // Check that there are no instructions between the retain and the autorelease
3823 // (such as an autorelease_pop) which may change the count.
3824 CallInst *Retain = 0;
3825 if (Class == IC_AutoreleaseRV)
3826 FindDependencies(RetainAutoreleaseRVDep, Arg,
3827 Autorelease->getParent(), Autorelease,
3828 DependingInstructions, Visited, PA);
3829 else
3830 FindDependencies(RetainAutoreleaseDep, Arg,
3831 Autorelease->getParent(), Autorelease,
3832 DependingInstructions, Visited, PA);
3833
3834 Visited.clear();
3835 if (DependingInstructions.size() != 1) {
3836 DependingInstructions.clear();
3837 return false;
3838 }
3839
3840 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3841 DependingInstructions.clear();
3842
3843 if (!Retain ||
3844 GetBasicInstructionClass(Retain) != IC_Retain ||
3845 GetObjCArg(Retain) != Arg)
3846 return false;
3847
3848 Changed = true;
3849 ++NumPeeps;
3850
3851 if (Class == IC_AutoreleaseRV)
3852 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3853 else
3854 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3855
3856 EraseInstruction(Autorelease);
3857 return true;
3858}
3859
3860/// ContractRelease - Attempt to merge an objc_release with a store, load, and
3861/// objc_retain to form an objc_storeStrong. This can be a little tricky because
3862/// the instructions don't always appear in order, and there may be unrelated
3863/// intervening instructions.
3864void ObjCARCContract::ContractRelease(Instruction *Release,
3865 inst_iterator &Iter) {
3866 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman2bc3d522011-09-12 20:23:13 +00003867 if (!Load || !Load->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00003868
3869 // For now, require everything to be in one basic block.
3870 BasicBlock *BB = Release->getParent();
3871 if (Load->getParent() != BB) return;
3872
3873 // Walk down to find the store.
3874 BasicBlock::iterator I = Load, End = BB->end();
3875 ++I;
3876 AliasAnalysis::Location Loc = AA->getLocation(Load);
3877 while (I != End &&
3878 (&*I == Release ||
3879 IsRetain(GetBasicInstructionClass(I)) ||
3880 !(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
3881 ++I;
3882 StoreInst *Store = dyn_cast<StoreInst>(I);
Eli Friedman2bc3d522011-09-12 20:23:13 +00003883 if (!Store || !Store->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00003884 if (Store->getPointerOperand() != Loc.Ptr) return;
3885
3886 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
3887
3888 // Walk up to find the retain.
3889 I = Store;
3890 BasicBlock::iterator Begin = BB->begin();
3891 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
3892 --I;
3893 Instruction *Retain = I;
3894 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
3895 if (GetObjCArg(Retain) != New) return;
3896
3897 Changed = true;
3898 ++NumStoreStrongs;
3899
3900 LLVMContext &C = Release->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003901 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3902 Type *I8XX = PointerType::getUnqual(I8X);
John McCall9fbd3182011-06-15 23:37:01 +00003903
3904 Value *Args[] = { Load->getPointerOperand(), New };
3905 if (Args[0]->getType() != I8XX)
3906 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
3907 if (Args[1]->getType() != I8X)
3908 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
3909 CallInst *StoreStrong =
3910 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foada3efbb12011-07-15 08:37:34 +00003911 Args, "", Store);
John McCall9fbd3182011-06-15 23:37:01 +00003912 StoreStrong->setDoesNotThrow();
3913 StoreStrong->setDebugLoc(Store->getDebugLoc());
3914
Dan Gohman0cdece42012-01-19 19:14:36 +00003915 // We can't set the tail flag yet, because we haven't yet determined
3916 // whether there are any escaping allocas. Remember this call, so that
3917 // we can set the tail flag once we know it's safe.
3918 StoreStrongCalls.insert(StoreStrong);
3919
John McCall9fbd3182011-06-15 23:37:01 +00003920 if (&*Iter == Store) ++Iter;
3921 Store->eraseFromParent();
3922 Release->eraseFromParent();
3923 EraseInstruction(Retain);
3924 if (Load->use_empty())
3925 Load->eraseFromParent();
3926}
3927
3928bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003929 Run = ModuleHasARC(M);
3930 if (!Run)
3931 return false;
3932
John McCall9fbd3182011-06-15 23:37:01 +00003933 // These are initialized lazily.
3934 StoreStrongCallee = 0;
3935 RetainAutoreleaseCallee = 0;
3936 RetainAutoreleaseRVCallee = 0;
3937
3938 // Initialize RetainRVMarker.
3939 RetainRVMarker = 0;
3940 if (NamedMDNode *NMD =
3941 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
3942 if (NMD->getNumOperands() == 1) {
3943 const MDNode *N = NMD->getOperand(0);
3944 if (N->getNumOperands() == 1)
3945 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
3946 RetainRVMarker = S;
3947 }
3948
3949 return false;
3950}
3951
3952bool ObjCARCContract::runOnFunction(Function &F) {
3953 if (!EnableARCOpts)
3954 return false;
3955
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003956 // If nothing in the Module uses ARC, don't do anything.
3957 if (!Run)
3958 return false;
3959
John McCall9fbd3182011-06-15 23:37:01 +00003960 Changed = false;
3961 AA = &getAnalysis<AliasAnalysis>();
3962 DT = &getAnalysis<DominatorTree>();
3963
3964 PA.setAA(&getAnalysis<AliasAnalysis>());
3965
Dan Gohman0cdece42012-01-19 19:14:36 +00003966 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
3967 // keyword. Be conservative if the function has variadic arguments.
3968 // It seems that functions which "return twice" are also unsafe for the
3969 // "tail" argument, because they are setjmp, which could need to
3970 // return to an earlier stack state.
3971 bool TailOkForStoreStrongs = !F.isVarArg() && !F.callsFunctionThatReturnsTwice();
3972
John McCall9fbd3182011-06-15 23:37:01 +00003973 // For ObjC library calls which return their argument, replace uses of the
3974 // argument with uses of the call return value, if it dominates the use. This
3975 // reduces register pressure.
3976 SmallPtrSet<Instruction *, 4> DependingInstructions;
3977 SmallPtrSet<const BasicBlock *, 4> Visited;
3978 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3979 Instruction *Inst = &*I++;
3980
3981 // Only these library routines return their argument. In particular,
3982 // objc_retainBlock does not necessarily return its argument.
3983 InstructionClass Class = GetBasicInstructionClass(Inst);
3984 switch (Class) {
3985 case IC_Retain:
3986 case IC_FusedRetainAutorelease:
3987 case IC_FusedRetainAutoreleaseRV:
3988 break;
3989 case IC_Autorelease:
3990 case IC_AutoreleaseRV:
3991 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
3992 continue;
3993 break;
3994 case IC_RetainRV: {
3995 // If we're compiling for a target which needs a special inline-asm
3996 // marker to do the retainAutoreleasedReturnValue optimization,
3997 // insert it now.
3998 if (!RetainRVMarker)
3999 break;
4000 BasicBlock::iterator BBI = Inst;
4001 --BBI;
4002 while (isNoopInstruction(BBI)) --BBI;
4003 if (&*BBI == GetObjCArg(Inst)) {
4004 InlineAsm *IA =
4005 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4006 /*isVarArg=*/false),
4007 RetainRVMarker->getString(),
4008 /*Constraints=*/"", /*hasSideEffects=*/true);
4009 CallInst::Create(IA, "", Inst);
4010 }
4011 break;
4012 }
4013 case IC_InitWeak: {
4014 // objc_initWeak(p, null) => *p = null
4015 CallInst *CI = cast<CallInst>(Inst);
4016 if (isNullOrUndef(CI->getArgOperand(1))) {
4017 Value *Null =
4018 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4019 Changed = true;
4020 new StoreInst(Null, CI->getArgOperand(0), CI);
4021 CI->replaceAllUsesWith(Null);
4022 CI->eraseFromParent();
4023 }
4024 continue;
4025 }
4026 case IC_Release:
4027 ContractRelease(Inst, I);
4028 continue;
Dan Gohman0cdece42012-01-19 19:14:36 +00004029 case IC_User:
4030 // Be conservative if the function has any alloca instructions.
4031 // Technically we only care about escaping alloca instructions,
4032 // but this is sufficient to handle some interesting cases.
4033 if (isa<AllocaInst>(Inst))
4034 TailOkForStoreStrongs = false;
4035 continue;
John McCall9fbd3182011-06-15 23:37:01 +00004036 default:
4037 continue;
4038 }
4039
4040 // Don't use GetObjCArg because we don't want to look through bitcasts
4041 // and such; to do the replacement, the argument must have type i8*.
4042 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4043 for (;;) {
4044 // If we're compiling bugpointed code, don't get in trouble.
4045 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4046 break;
4047 // Look through the uses of the pointer.
4048 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4049 UI != UE; ) {
4050 Use &U = UI.getUse();
4051 unsigned OperandNo = UI.getOperandNo();
4052 ++UI; // Increment UI now, because we may unlink its element.
Rafael Espindola2453dff2012-03-15 15:52:59 +00004053 Instruction *UserInst = dyn_cast<Instruction>(U.getUser());
4054 if (!UserInst)
4055 continue;
4056 // FIXME: dominates should return true for unreachable UserInst.
4057 if (!DT->isReachableFromEntry(UserInst->getParent()) ||
4058 DT->dominates(Inst, UserInst)) {
4059 Changed = true;
4060 Instruction *Replacement = Inst;
4061 Type *UseTy = U.get()->getType();
4062 if (PHINode *PHI = dyn_cast<PHINode>(UserInst)) {
4063 // For PHI nodes, insert the bitcast in the predecessor block.
4064 unsigned ValNo =
4065 PHINode::getIncomingValueNumForOperand(OperandNo);
4066 BasicBlock *BB =
4067 PHI->getIncomingBlock(ValNo);
4068 if (Replacement->getType() != UseTy)
4069 Replacement = new BitCastInst(Replacement, UseTy, "",
4070 &BB->back());
4071 for (unsigned i = 0, e = PHI->getNumIncomingValues();
4072 i != e; ++i)
4073 if (PHI->getIncomingBlock(i) == BB) {
4074 // Keep the UI iterator valid.
4075 if (&PHI->getOperandUse(
4076 PHINode::getOperandNumForIncomingValue(i)) ==
4077 &UI.getUse())
4078 ++UI;
4079 PHI->setIncomingValue(i, Replacement);
4080 }
4081 } else {
4082 if (Replacement->getType() != UseTy)
4083 Replacement = new BitCastInst(Replacement, UseTy, "", UserInst);
4084 U.set(Replacement);
John McCall9fbd3182011-06-15 23:37:01 +00004085 }
Rafael Espindola2453dff2012-03-15 15:52:59 +00004086 }
John McCall9fbd3182011-06-15 23:37:01 +00004087 }
4088
4089 // If Arg is a no-op casted pointer, strip one level of casts and
4090 // iterate.
4091 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4092 Arg = BI->getOperand(0);
4093 else if (isa<GEPOperator>(Arg) &&
4094 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4095 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4096 else if (isa<GlobalAlias>(Arg) &&
4097 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4098 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4099 else
4100 break;
4101 }
4102 }
4103
Dan Gohman0cdece42012-01-19 19:14:36 +00004104 // If this function has no escaping allocas or suspicious vararg usage,
4105 // objc_storeStrong calls can be marked with the "tail" keyword.
4106 if (TailOkForStoreStrongs)
4107 for (DenseSet<CallInst *>::iterator I = StoreStrongCalls.begin(),
4108 E = StoreStrongCalls.end(); I != E; ++I)
4109 (*I)->setTailCall();
4110 StoreStrongCalls.clear();
4111
John McCall9fbd3182011-06-15 23:37:01 +00004112 return Changed;
4113}