blob: 2bc7e2d1b7abc3fb3efb7f2c57949e1fff31ed6e [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
Chris Lattner55dc5c72012-05-27 19:37:05 +000023// by name, and hardwires knowledge of their semantics.
John McCall9fbd3182011-06-15 23:37:01 +000024//
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"
John McCall9fbd3182011-06-15 23:37:01 +000032#include "llvm/ADT/DenseMap.h"
Michael Gottesman8f22c8b2013-01-01 16:05:48 +000033#include "llvm/Support/Debug.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000034#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/raw_ostream.h"
John McCall9fbd3182011-06-15 23:37:01 +000036using namespace llvm;
37
38// A handy option to enable/disable all optimizations in this file.
39static cl::opt<bool> EnableARCOpts("enable-objc-arc-opts", cl::init(true));
40
41//===----------------------------------------------------------------------===//
42// Misc. Utilities
43//===----------------------------------------------------------------------===//
44
45namespace {
46 /// MapVector - An associative container with fast insertion-order
47 /// (deterministic) iteration over its elements. Plus the special
48 /// blot operation.
49 template<class KeyT, class ValueT>
50 class MapVector {
51 /// Map - Map keys to indices in Vector.
52 typedef DenseMap<KeyT, size_t> MapTy;
53 MapTy Map;
54
55 /// Vector - Keys and values.
56 typedef std::vector<std::pair<KeyT, ValueT> > VectorTy;
57 VectorTy Vector;
58
59 public:
60 typedef typename VectorTy::iterator iterator;
61 typedef typename VectorTy::const_iterator const_iterator;
62 iterator begin() { return Vector.begin(); }
63 iterator end() { return Vector.end(); }
64 const_iterator begin() const { return Vector.begin(); }
65 const_iterator end() const { return Vector.end(); }
66
67#ifdef XDEBUG
68 ~MapVector() {
69 assert(Vector.size() >= Map.size()); // May differ due to blotting.
70 for (typename MapTy::const_iterator I = Map.begin(), E = Map.end();
71 I != E; ++I) {
72 assert(I->second < Vector.size());
73 assert(Vector[I->second].first == I->first);
74 }
75 for (typename VectorTy::const_iterator I = Vector.begin(),
76 E = Vector.end(); I != E; ++I)
77 assert(!I->first ||
78 (Map.count(I->first) &&
79 Map[I->first] == size_t(I - Vector.begin())));
80 }
81#endif
82
Dan Gohman22cc4cc2012-03-02 01:13:53 +000083 ValueT &operator[](const KeyT &Arg) {
John McCall9fbd3182011-06-15 23:37:01 +000084 std::pair<typename MapTy::iterator, bool> Pair =
85 Map.insert(std::make_pair(Arg, size_t(0)));
86 if (Pair.second) {
Dan Gohman22cc4cc2012-03-02 01:13:53 +000087 size_t Num = Vector.size();
88 Pair.first->second = Num;
John McCall9fbd3182011-06-15 23:37:01 +000089 Vector.push_back(std::make_pair(Arg, ValueT()));
Dan Gohman22cc4cc2012-03-02 01:13:53 +000090 return Vector[Num].second;
John McCall9fbd3182011-06-15 23:37:01 +000091 }
92 return Vector[Pair.first->second].second;
93 }
94
95 std::pair<iterator, bool>
96 insert(const std::pair<KeyT, ValueT> &InsertPair) {
97 std::pair<typename MapTy::iterator, bool> Pair =
98 Map.insert(std::make_pair(InsertPair.first, size_t(0)));
99 if (Pair.second) {
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000100 size_t Num = Vector.size();
101 Pair.first->second = Num;
John McCall9fbd3182011-06-15 23:37:01 +0000102 Vector.push_back(InsertPair);
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000103 return std::make_pair(Vector.begin() + Num, true);
John McCall9fbd3182011-06-15 23:37:01 +0000104 }
105 return std::make_pair(Vector.begin() + Pair.first->second, false);
106 }
107
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000108 const_iterator find(const KeyT &Key) const {
John McCall9fbd3182011-06-15 23:37:01 +0000109 typename MapTy::const_iterator It = Map.find(Key);
110 if (It == Map.end()) return Vector.end();
111 return Vector.begin() + It->second;
112 }
113
114 /// blot - This is similar to erase, but instead of removing the element
115 /// from the vector, it just zeros out the key in the vector. This leaves
116 /// iterators intact, but clients must be prepared for zeroed-out keys when
117 /// iterating.
Dan Gohman22cc4cc2012-03-02 01:13:53 +0000118 void blot(const KeyT &Key) {
John McCall9fbd3182011-06-15 23:37:01 +0000119 typename MapTy::iterator It = Map.find(Key);
120 if (It == Map.end()) return;
121 Vector[It->second].first = KeyT();
122 Map.erase(It);
123 }
124
125 void clear() {
126 Map.clear();
127 Vector.clear();
128 }
129 };
130}
131
132//===----------------------------------------------------------------------===//
133// ARC Utilities.
134//===----------------------------------------------------------------------===//
135
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000136#include "llvm/ADT/StringSwitch.h"
137#include "llvm/Analysis/ValueTracking.h"
Dan Gohman0daef3d2012-05-08 23:39:44 +0000138#include "llvm/Intrinsics.h"
139#include "llvm/Module.h"
Dan Gohman0daef3d2012-05-08 23:39:44 +0000140#include "llvm/Support/CallSite.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000141#include "llvm/Transforms/Utils/Local.h"
Dan Gohman0daef3d2012-05-08 23:39:44 +0000142
John McCall9fbd3182011-06-15 23:37:01 +0000143namespace {
144 /// InstructionClass - A simple classification for instructions.
145 enum InstructionClass {
146 IC_Retain, ///< objc_retain
147 IC_RetainRV, ///< objc_retainAutoreleasedReturnValue
148 IC_RetainBlock, ///< objc_retainBlock
149 IC_Release, ///< objc_release
150 IC_Autorelease, ///< objc_autorelease
151 IC_AutoreleaseRV, ///< objc_autoreleaseReturnValue
152 IC_AutoreleasepoolPush, ///< objc_autoreleasePoolPush
153 IC_AutoreleasepoolPop, ///< objc_autoreleasePoolPop
154 IC_NoopCast, ///< objc_retainedObject, etc.
155 IC_FusedRetainAutorelease, ///< objc_retainAutorelease
156 IC_FusedRetainAutoreleaseRV, ///< objc_retainAutoreleaseReturnValue
157 IC_LoadWeakRetained, ///< objc_loadWeakRetained (primitive)
158 IC_StoreWeak, ///< objc_storeWeak (primitive)
159 IC_InitWeak, ///< objc_initWeak (derived)
160 IC_LoadWeak, ///< objc_loadWeak (derived)
161 IC_MoveWeak, ///< objc_moveWeak (derived)
162 IC_CopyWeak, ///< objc_copyWeak (derived)
163 IC_DestroyWeak, ///< objc_destroyWeak (derived)
Dan Gohman44234772012-04-13 18:28:58 +0000164 IC_StoreStrong, ///< objc_storeStrong (derived)
John McCall9fbd3182011-06-15 23:37:01 +0000165 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)
Dan Gohman44234772012-04-13 18:28:58 +0000265 .Case("objc_storeStrong", IC_StoreStrong)
John McCall9fbd3182011-06-15 23:37:01 +0000266 .Default(IC_CallOrUser);
267 // Second argument is i8**.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000268 if (PointerType *Pte1 = dyn_cast<PointerType>(ETy1))
John McCall9fbd3182011-06-15 23:37:01 +0000269 if (Pte1->getElementType()->isIntegerTy(8))
270 return StringSwitch<InstructionClass>(F->getName())
271 .Case("objc_moveWeak", IC_MoveWeak)
272 .Case("objc_copyWeak", IC_CopyWeak)
273 .Default(IC_CallOrUser);
274 }
275
276 // Anything else.
277 return IC_CallOrUser;
278}
279
280/// GetInstructionClass - Determine what kind of construct V is.
281static InstructionClass GetInstructionClass(const Value *V) {
282 if (const Instruction *I = dyn_cast<Instruction>(V)) {
283 // Any instruction other than bitcast and gep with a pointer operand have a
284 // use of an objc pointer. Bitcasts, GEPs, Selects, PHIs transfer a pointer
285 // to a subsequent use, rather than using it themselves, in this sense.
286 // As a short cut, several other opcodes are known to have no pointer
287 // operands of interest. And ret is never followed by a release, so it's
288 // not interesting to examine.
289 switch (I->getOpcode()) {
290 case Instruction::Call: {
291 const CallInst *CI = cast<CallInst>(I);
292 // Check for calls to special functions.
293 if (const Function *F = CI->getCalledFunction()) {
294 InstructionClass Class = GetFunctionClass(F);
295 if (Class != IC_CallOrUser)
296 return Class;
297
298 // None of the intrinsic functions do objc_release. For intrinsics, the
299 // only question is whether or not they may be users.
300 switch (F->getIntrinsicID()) {
John McCall9fbd3182011-06-15 23:37:01 +0000301 case Intrinsic::returnaddress: case Intrinsic::frameaddress:
302 case Intrinsic::stacksave: case Intrinsic::stackrestore:
303 case Intrinsic::vastart: case Intrinsic::vacopy: case Intrinsic::vaend:
Dan Gohman0daef3d2012-05-08 23:39:44 +0000304 case Intrinsic::objectsize: case Intrinsic::prefetch:
305 case Intrinsic::stackprotector:
306 case Intrinsic::eh_return_i32: case Intrinsic::eh_return_i64:
307 case Intrinsic::eh_typeid_for: case Intrinsic::eh_dwarf_cfa:
308 case Intrinsic::eh_sjlj_lsda: case Intrinsic::eh_sjlj_functioncontext:
309 case Intrinsic::init_trampoline: case Intrinsic::adjust_trampoline:
310 case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
311 case Intrinsic::invariant_start: case Intrinsic::invariant_end:
John McCall9fbd3182011-06-15 23:37:01 +0000312 // Don't let dbg info affect our results.
313 case Intrinsic::dbg_declare: case Intrinsic::dbg_value:
314 // Short cut: Some intrinsics obviously don't use ObjC pointers.
315 return IC_None;
316 default:
Dan Gohman0daef3d2012-05-08 23:39:44 +0000317 break;
John McCall9fbd3182011-06-15 23:37:01 +0000318 }
319 }
320 return GetCallSiteClass(CI);
321 }
322 case Instruction::Invoke:
323 return GetCallSiteClass(cast<InvokeInst>(I));
324 case Instruction::BitCast:
325 case Instruction::GetElementPtr:
326 case Instruction::Select: case Instruction::PHI:
327 case Instruction::Ret: case Instruction::Br:
328 case Instruction::Switch: case Instruction::IndirectBr:
329 case Instruction::Alloca: case Instruction::VAArg:
330 case Instruction::Add: case Instruction::FAdd:
331 case Instruction::Sub: case Instruction::FSub:
332 case Instruction::Mul: case Instruction::FMul:
333 case Instruction::SDiv: case Instruction::UDiv: case Instruction::FDiv:
334 case Instruction::SRem: case Instruction::URem: case Instruction::FRem:
335 case Instruction::Shl: case Instruction::LShr: case Instruction::AShr:
336 case Instruction::And: case Instruction::Or: case Instruction::Xor:
337 case Instruction::SExt: case Instruction::ZExt: case Instruction::Trunc:
338 case Instruction::IntToPtr: case Instruction::FCmp:
339 case Instruction::FPTrunc: case Instruction::FPExt:
340 case Instruction::FPToUI: case Instruction::FPToSI:
341 case Instruction::UIToFP: case Instruction::SIToFP:
342 case Instruction::InsertElement: case Instruction::ExtractElement:
343 case Instruction::ShuffleVector:
344 case Instruction::ExtractValue:
345 break;
346 case Instruction::ICmp:
347 // Comparing a pointer with null, or any other constant, isn't an
348 // interesting use, because we don't care what the pointer points to, or
349 // about the values of any other dynamic reference-counted pointers.
350 if (IsPotentialUse(I->getOperand(1)))
351 return IC_User;
352 break;
353 default:
354 // For anything else, check all the operands.
Dan Gohmand4464602011-08-22 17:29:37 +0000355 // Note that this includes both operands of a Store: while the first
356 // operand isn't actually being dereferenced, it is being stored to
357 // memory where we can no longer track who might read it and dereference
358 // it, so we have to consider it potentially used.
John McCall9fbd3182011-06-15 23:37:01 +0000359 for (User::const_op_iterator OI = I->op_begin(), OE = I->op_end();
360 OI != OE; ++OI)
361 if (IsPotentialUse(*OI))
362 return IC_User;
363 }
364 }
365
366 // Otherwise, it's totally inert for ARC purposes.
367 return IC_None;
368}
369
370/// GetBasicInstructionClass - Determine what kind of construct V is. This is
371/// similar to GetInstructionClass except that it only detects objc runtine
372/// calls. This allows it to be faster.
373static InstructionClass GetBasicInstructionClass(const Value *V) {
374 if (const CallInst *CI = dyn_cast<CallInst>(V)) {
375 if (const Function *F = CI->getCalledFunction())
376 return GetFunctionClass(F);
377 // Otherwise, be conservative.
378 return IC_CallOrUser;
379 }
380
381 // Otherwise, be conservative.
Dan Gohman2f6263c2012-01-17 20:52:24 +0000382 return isa<InvokeInst>(V) ? IC_CallOrUser : IC_User;
John McCall9fbd3182011-06-15 23:37:01 +0000383}
384
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000385/// IsRetain - Test if the given class is objc_retain or
John McCall9fbd3182011-06-15 23:37:01 +0000386/// equivalent.
387static bool IsRetain(InstructionClass Class) {
388 return Class == IC_Retain ||
389 Class == IC_RetainRV;
390}
391
Sylvestre Ledruc8e41c52012-07-23 08:51:15 +0000392/// IsAutorelease - Test if the given class is objc_autorelease or
John McCall9fbd3182011-06-15 23:37:01 +0000393/// equivalent.
394static bool IsAutorelease(InstructionClass Class) {
395 return Class == IC_Autorelease ||
396 Class == IC_AutoreleaseRV;
397}
398
399/// IsForwarding - Test if the given class represents instructions which return
400/// their argument verbatim.
401static bool IsForwarding(InstructionClass Class) {
402 // objc_retainBlock technically doesn't always return its argument
403 // verbatim, but it doesn't matter for our purposes here.
404 return Class == IC_Retain ||
405 Class == IC_RetainRV ||
406 Class == IC_Autorelease ||
407 Class == IC_AutoreleaseRV ||
408 Class == IC_RetainBlock ||
409 Class == IC_NoopCast;
410}
411
412/// IsNoopOnNull - Test if the given class represents instructions which do
413/// nothing if passed a null pointer.
414static bool IsNoopOnNull(InstructionClass Class) {
415 return Class == IC_Retain ||
416 Class == IC_RetainRV ||
417 Class == IC_Release ||
418 Class == IC_Autorelease ||
419 Class == IC_AutoreleaseRV ||
420 Class == IC_RetainBlock;
421}
422
423/// IsAlwaysTail - Test if the given class represents instructions which are
424/// always safe to mark with the "tail" keyword.
425static bool IsAlwaysTail(InstructionClass Class) {
426 // IC_RetainBlock may be given a stack argument.
427 return Class == IC_Retain ||
428 Class == IC_RetainRV ||
429 Class == IC_Autorelease ||
430 Class == IC_AutoreleaseRV;
431}
432
433/// IsNoThrow - Test if the given class represents instructions which are always
434/// safe to mark with the nounwind attribute..
435static bool IsNoThrow(InstructionClass Class) {
Dan Gohman1d2fd752011-09-14 18:33:34 +0000436 // objc_retainBlock is not nounwind because it calls user copy constructors
437 // which could theoretically throw.
John McCall9fbd3182011-06-15 23:37:01 +0000438 return Class == IC_Retain ||
439 Class == IC_RetainRV ||
John McCall9fbd3182011-06-15 23:37:01 +0000440 Class == IC_Release ||
441 Class == IC_Autorelease ||
442 Class == IC_AutoreleaseRV ||
443 Class == IC_AutoreleasepoolPush ||
444 Class == IC_AutoreleasepoolPop;
445}
446
Dan Gohman447989c2012-04-27 18:56:31 +0000447/// EraseInstruction - Erase the given instruction. Many ObjC calls return their
John McCall9fbd3182011-06-15 23:37:01 +0000448/// argument verbatim, so if it's such a call and the return value has users,
449/// replace them with the argument value.
450static void EraseInstruction(Instruction *CI) {
451 Value *OldArg = cast<CallInst>(CI)->getArgOperand(0);
452
453 bool Unused = CI->use_empty();
454
455 if (!Unused) {
456 // Replace the return value with the argument.
457 assert(IsForwarding(GetBasicInstructionClass(CI)) &&
458 "Can't delete non-forwarding instruction with users!");
459 CI->replaceAllUsesWith(OldArg);
460 }
461
462 CI->eraseFromParent();
463
464 if (Unused)
465 RecursivelyDeleteTriviallyDeadInstructions(OldArg);
466}
467
468/// GetUnderlyingObjCPtr - This is a wrapper around getUnderlyingObject which
469/// also knows how to look through objc_retain and objc_autorelease calls, which
470/// we know to return their argument verbatim.
471static const Value *GetUnderlyingObjCPtr(const Value *V) {
472 for (;;) {
473 V = GetUnderlyingObject(V);
474 if (!IsForwarding(GetBasicInstructionClass(V)))
475 break;
476 V = cast<CallInst>(V)->getArgOperand(0);
477 }
478
479 return V;
480}
481
482/// StripPointerCastsAndObjCCalls - This is a wrapper around
483/// Value::stripPointerCasts which also knows how to look through objc_retain
484/// and objc_autorelease calls, which we know to return their argument verbatim.
485static const Value *StripPointerCastsAndObjCCalls(const Value *V) {
486 for (;;) {
487 V = V->stripPointerCasts();
488 if (!IsForwarding(GetBasicInstructionClass(V)))
489 break;
490 V = cast<CallInst>(V)->getArgOperand(0);
491 }
492 return V;
493}
494
495/// StripPointerCastsAndObjCCalls - This is a wrapper around
496/// Value::stripPointerCasts which also knows how to look through objc_retain
497/// and objc_autorelease calls, which we know to return their argument verbatim.
498static Value *StripPointerCastsAndObjCCalls(Value *V) {
499 for (;;) {
500 V = V->stripPointerCasts();
501 if (!IsForwarding(GetBasicInstructionClass(V)))
502 break;
503 V = cast<CallInst>(V)->getArgOperand(0);
504 }
505 return V;
506}
507
508/// GetObjCArg - Assuming the given instruction is one of the special calls such
509/// as objc_retain or objc_release, return the argument value, stripped of no-op
510/// casts and forwarding calls.
511static Value *GetObjCArg(Value *Inst) {
512 return StripPointerCastsAndObjCCalls(cast<CallInst>(Inst)->getArgOperand(0));
513}
514
515/// IsObjCIdentifiedObject - This is similar to AliasAnalysis'
516/// isObjCIdentifiedObject, except that it uses special knowledge of
517/// ObjC conventions...
518static bool IsObjCIdentifiedObject(const Value *V) {
519 // Assume that call results and arguments have their own "provenance".
520 // Constants (including GlobalVariables) and Allocas are never
521 // reference-counted.
522 if (isa<CallInst>(V) || isa<InvokeInst>(V) ||
523 isa<Argument>(V) || isa<Constant>(V) ||
524 isa<AllocaInst>(V))
525 return true;
526
527 if (const LoadInst *LI = dyn_cast<LoadInst>(V)) {
528 const Value *Pointer =
529 StripPointerCastsAndObjCCalls(LI->getPointerOperand());
530 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Pointer)) {
Dan Gohman1b31ea82011-08-22 17:29:11 +0000531 // A constant pointer can't be pointing to an object on the heap. It may
532 // be reference-counted, but it won't be deleted.
533 if (GV->isConstant())
534 return true;
John McCall9fbd3182011-06-15 23:37:01 +0000535 StringRef Name = GV->getName();
536 // These special variables are known to hold values which are not
537 // reference-counted pointers.
538 if (Name.startswith("\01L_OBJC_SELECTOR_REFERENCES_") ||
539 Name.startswith("\01L_OBJC_CLASSLIST_REFERENCES_") ||
540 Name.startswith("\01L_OBJC_CLASSLIST_SUP_REFS_$_") ||
541 Name.startswith("\01L_OBJC_METH_VAR_NAME_") ||
542 Name.startswith("\01l_objc_msgSend_fixup_"))
543 return true;
544 }
545 }
546
547 return false;
548}
549
550/// FindSingleUseIdentifiedObject - This is similar to
551/// StripPointerCastsAndObjCCalls but it stops as soon as it finds a value
552/// with multiple uses.
553static const Value *FindSingleUseIdentifiedObject(const Value *Arg) {
554 if (Arg->hasOneUse()) {
555 if (const BitCastInst *BC = dyn_cast<BitCastInst>(Arg))
556 return FindSingleUseIdentifiedObject(BC->getOperand(0));
557 if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Arg))
558 if (GEP->hasAllZeroIndices())
559 return FindSingleUseIdentifiedObject(GEP->getPointerOperand());
560 if (IsForwarding(GetBasicInstructionClass(Arg)))
561 return FindSingleUseIdentifiedObject(
562 cast<CallInst>(Arg)->getArgOperand(0));
563 if (!IsObjCIdentifiedObject(Arg))
564 return 0;
565 return Arg;
566 }
567
Dan Gohman0daef3d2012-05-08 23:39:44 +0000568 // If we found an identifiable object but it has multiple uses, but they are
569 // trivial uses, we can still consider this to be a single-use value.
John McCall9fbd3182011-06-15 23:37:01 +0000570 if (IsObjCIdentifiedObject(Arg)) {
571 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
572 UI != UE; ++UI) {
573 const User *U = *UI;
574 if (!U->use_empty() || StripPointerCastsAndObjCCalls(U) != Arg)
575 return 0;
576 }
577
578 return Arg;
579 }
580
581 return 0;
582}
583
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000584/// ModuleHasARC - Test if the given module looks interesting to run ARC
585/// optimization on.
586static bool ModuleHasARC(const Module &M) {
587 return
588 M.getNamedValue("objc_retain") ||
589 M.getNamedValue("objc_release") ||
590 M.getNamedValue("objc_autorelease") ||
591 M.getNamedValue("objc_retainAutoreleasedReturnValue") ||
592 M.getNamedValue("objc_retainBlock") ||
593 M.getNamedValue("objc_autoreleaseReturnValue") ||
594 M.getNamedValue("objc_autoreleasePoolPush") ||
595 M.getNamedValue("objc_loadWeakRetained") ||
596 M.getNamedValue("objc_loadWeak") ||
597 M.getNamedValue("objc_destroyWeak") ||
598 M.getNamedValue("objc_storeWeak") ||
599 M.getNamedValue("objc_initWeak") ||
600 M.getNamedValue("objc_moveWeak") ||
601 M.getNamedValue("objc_copyWeak") ||
602 M.getNamedValue("objc_retainedObject") ||
603 M.getNamedValue("objc_unretainedObject") ||
604 M.getNamedValue("objc_unretainedPointer");
605}
606
Dan Gohman79522dc2012-01-13 00:39:07 +0000607/// DoesObjCBlockEscape - Test whether the given pointer, which is an
608/// Objective C block pointer, does not "escape". This differs from regular
609/// escape analysis in that a use as an argument to a call is not considered
610/// an escape.
611static bool DoesObjCBlockEscape(const Value *BlockPtr) {
612 // Walk the def-use chains.
613 SmallVector<const Value *, 4> Worklist;
614 Worklist.push_back(BlockPtr);
615 do {
616 const Value *V = Worklist.pop_back_val();
617 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
618 UI != UE; ++UI) {
619 const User *UUser = *UI;
620 // Special - Use by a call (callee or argument) is not considered
621 // to be an escape.
Dan Gohman44234772012-04-13 18:28:58 +0000622 switch (GetBasicInstructionClass(UUser)) {
623 case IC_StoreWeak:
624 case IC_InitWeak:
625 case IC_StoreStrong:
626 case IC_Autorelease:
627 case IC_AutoreleaseRV:
628 // These special functions make copies of their pointer arguments.
629 return true;
630 case IC_User:
631 case IC_None:
632 // Use by an instruction which copies the value is an escape if the
633 // result is an escape.
634 if (isa<BitCastInst>(UUser) || isa<GetElementPtrInst>(UUser) ||
635 isa<PHINode>(UUser) || isa<SelectInst>(UUser)) {
636 Worklist.push_back(UUser);
637 continue;
638 }
639 // Use by a load is not an escape.
640 if (isa<LoadInst>(UUser))
641 continue;
642 // Use by a store is not an escape if the use is the address.
643 if (const StoreInst *SI = dyn_cast<StoreInst>(UUser))
644 if (V != SI->getValueOperand())
645 continue;
646 break;
647 default:
648 // Regular calls and other stuff are not considered escapes.
Dan Gohman79522dc2012-01-13 00:39:07 +0000649 continue;
650 }
Dan Gohmana3b08d62012-02-13 22:57:02 +0000651 // Otherwise, conservatively assume an escape.
Dan Gohman79522dc2012-01-13 00:39:07 +0000652 return true;
653 }
654 } while (!Worklist.empty());
655
656 // No escapes found.
657 return false;
658}
659
John McCall9fbd3182011-06-15 23:37:01 +0000660//===----------------------------------------------------------------------===//
661// ARC AliasAnalysis.
662//===----------------------------------------------------------------------===//
663
John McCall9fbd3182011-06-15 23:37:01 +0000664#include "llvm/Analysis/AliasAnalysis.h"
665#include "llvm/Analysis/Passes.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000666#include "llvm/Pass.h"
John McCall9fbd3182011-06-15 23:37:01 +0000667
668namespace {
669 /// ObjCARCAliasAnalysis - This is a simple alias analysis
670 /// implementation that uses knowledge of ARC constructs to answer queries.
671 ///
672 /// TODO: This class could be generalized to know about other ObjC-specific
673 /// tricks. Such as knowing that ivars in the non-fragile ABI are non-aliasing
674 /// even though their offsets are dynamic.
675 class ObjCARCAliasAnalysis : public ImmutablePass,
676 public AliasAnalysis {
677 public:
678 static char ID; // Class identification, replacement for typeinfo
679 ObjCARCAliasAnalysis() : ImmutablePass(ID) {
680 initializeObjCARCAliasAnalysisPass(*PassRegistry::getPassRegistry());
681 }
682
683 private:
684 virtual void initializePass() {
685 InitializeAliasAnalysis(this);
686 }
687
688 /// getAdjustedAnalysisPointer - This method is used when a pass implements
689 /// an analysis interface through multiple inheritance. If needed, it
690 /// should override this to adjust the this pointer as needed for the
691 /// specified pass info.
692 virtual void *getAdjustedAnalysisPointer(const void *PI) {
693 if (PI == &AliasAnalysis::ID)
Dan Gohman447989c2012-04-27 18:56:31 +0000694 return static_cast<AliasAnalysis *>(this);
John McCall9fbd3182011-06-15 23:37:01 +0000695 return this;
696 }
697
698 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
699 virtual AliasResult alias(const Location &LocA, const Location &LocB);
700 virtual bool pointsToConstantMemory(const Location &Loc, bool OrLocal);
701 virtual ModRefBehavior getModRefBehavior(ImmutableCallSite CS);
702 virtual ModRefBehavior getModRefBehavior(const Function *F);
703 virtual ModRefResult getModRefInfo(ImmutableCallSite CS,
704 const Location &Loc);
705 virtual ModRefResult getModRefInfo(ImmutableCallSite CS1,
706 ImmutableCallSite CS2);
707 };
708} // End of anonymous namespace
709
710// Register this pass...
711char ObjCARCAliasAnalysis::ID = 0;
712INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
713 "ObjC-ARC-Based Alias Analysis", false, true, false)
714
715ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
716 return new ObjCARCAliasAnalysis();
717}
718
719void
720ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
721 AU.setPreservesAll();
722 AliasAnalysis::getAnalysisUsage(AU);
723}
724
725AliasAnalysis::AliasResult
726ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
727 if (!EnableARCOpts)
728 return AliasAnalysis::alias(LocA, LocB);
729
730 // First, strip off no-ops, including ObjC-specific no-ops, and try making a
731 // precise alias query.
732 const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
733 const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
734 AliasResult Result =
735 AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
736 Location(SB, LocB.Size, LocB.TBAATag));
737 if (Result != MayAlias)
738 return Result;
739
740 // If that failed, climb to the underlying object, including climbing through
741 // ObjC-specific no-ops, and try making an imprecise alias query.
742 const Value *UA = GetUnderlyingObjCPtr(SA);
743 const Value *UB = GetUnderlyingObjCPtr(SB);
744 if (UA != SA || UB != SB) {
745 Result = AliasAnalysis::alias(Location(UA), Location(UB));
746 // We can't use MustAlias or PartialAlias results here because
747 // GetUnderlyingObjCPtr may return an offsetted pointer value.
748 if (Result == NoAlias)
749 return NoAlias;
750 }
751
752 // If that failed, fail. We don't need to chain here, since that's covered
753 // by the earlier precise query.
754 return MayAlias;
755}
756
757bool
758ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
759 bool OrLocal) {
760 if (!EnableARCOpts)
761 return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
762
763 // First, strip off no-ops, including ObjC-specific no-ops, and try making
764 // a precise alias query.
765 const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
766 if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
767 OrLocal))
768 return true;
769
770 // If that failed, climb to the underlying object, including climbing through
771 // ObjC-specific no-ops, and try making an imprecise alias query.
772 const Value *U = GetUnderlyingObjCPtr(S);
773 if (U != S)
774 return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
775
776 // If that failed, fail. We don't need to chain here, since that's covered
777 // by the earlier precise query.
778 return false;
779}
780
781AliasAnalysis::ModRefBehavior
782ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
783 // We have nothing to do. Just chain to the next AliasAnalysis.
784 return AliasAnalysis::getModRefBehavior(CS);
785}
786
787AliasAnalysis::ModRefBehavior
788ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
789 if (!EnableARCOpts)
790 return AliasAnalysis::getModRefBehavior(F);
791
792 switch (GetFunctionClass(F)) {
793 case IC_NoopCast:
794 return DoesNotAccessMemory;
795 default:
796 break;
797 }
798
799 return AliasAnalysis::getModRefBehavior(F);
800}
801
802AliasAnalysis::ModRefResult
803ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
804 if (!EnableARCOpts)
805 return AliasAnalysis::getModRefInfo(CS, Loc);
806
807 switch (GetBasicInstructionClass(CS.getInstruction())) {
808 case IC_Retain:
809 case IC_RetainRV:
John McCall9fbd3182011-06-15 23:37:01 +0000810 case IC_Autorelease:
811 case IC_AutoreleaseRV:
812 case IC_NoopCast:
813 case IC_AutoreleasepoolPush:
814 case IC_FusedRetainAutorelease:
815 case IC_FusedRetainAutoreleaseRV:
816 // These functions don't access any memory visible to the compiler.
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000817 // Note that this doesn't include objc_retainBlock, because it updates
Dan Gohman21104822011-09-14 18:13:00 +0000818 // pointers when it copies block data.
John McCall9fbd3182011-06-15 23:37:01 +0000819 return NoModRef;
820 default:
821 break;
822 }
823
824 return AliasAnalysis::getModRefInfo(CS, Loc);
825}
826
827AliasAnalysis::ModRefResult
828ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
829 ImmutableCallSite CS2) {
830 // TODO: Theoretically we could check for dependencies between objc_* calls
831 // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
832 return AliasAnalysis::getModRefInfo(CS1, CS2);
833}
834
835//===----------------------------------------------------------------------===//
836// ARC expansion.
837//===----------------------------------------------------------------------===//
838
839#include "llvm/Support/InstIterator.h"
840#include "llvm/Transforms/Scalar.h"
841
842namespace {
843 /// ObjCARCExpand - Early ARC transformations.
844 class ObjCARCExpand : public FunctionPass {
845 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000846 virtual bool doInitialization(Module &M);
John McCall9fbd3182011-06-15 23:37:01 +0000847 virtual bool runOnFunction(Function &F);
848
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000849 /// Run - A flag indicating whether this optimization pass should run.
850 bool Run;
851
John McCall9fbd3182011-06-15 23:37:01 +0000852 public:
853 static char ID;
854 ObjCARCExpand() : FunctionPass(ID) {
855 initializeObjCARCExpandPass(*PassRegistry::getPassRegistry());
856 }
857 };
858}
859
860char ObjCARCExpand::ID = 0;
861INITIALIZE_PASS(ObjCARCExpand,
862 "objc-arc-expand", "ObjC ARC expansion", false, false)
863
864Pass *llvm::createObjCARCExpandPass() {
865 return new ObjCARCExpand();
866}
867
868void ObjCARCExpand::getAnalysisUsage(AnalysisUsage &AU) const {
869 AU.setPreservesCFG();
870}
871
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000872bool ObjCARCExpand::doInitialization(Module &M) {
873 Run = ModuleHasARC(M);
874 return false;
875}
876
John McCall9fbd3182011-06-15 23:37:01 +0000877bool ObjCARCExpand::runOnFunction(Function &F) {
878 if (!EnableARCOpts)
879 return false;
880
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +0000881 // If nothing in the Module uses ARC, don't do anything.
882 if (!Run)
883 return false;
884
John McCall9fbd3182011-06-15 23:37:01 +0000885 bool Changed = false;
886
887 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ++I) {
888 Instruction *Inst = &*I;
Michael Gottesman8f22c8b2013-01-01 16:05:48 +0000889
890 DEBUG(dbgs() << "ObjCARCExpand: Visiting: " << *Inst << "\n");
891
John McCall9fbd3182011-06-15 23:37:01 +0000892 switch (GetBasicInstructionClass(Inst)) {
893 case IC_Retain:
894 case IC_RetainRV:
895 case IC_Autorelease:
896 case IC_AutoreleaseRV:
897 case IC_FusedRetainAutorelease:
898 case IC_FusedRetainAutoreleaseRV:
899 // These calls return their argument verbatim, as a low-level
900 // optimization. However, this makes high-level optimizations
901 // harder. Undo any uses of this optimization that the front-end
Dan Gohmand6bf2012012-04-13 18:57:48 +0000902 // emitted here. We'll redo them in the contract pass.
John McCall9fbd3182011-06-15 23:37:01 +0000903 Changed = true;
904 Inst->replaceAllUsesWith(cast<CallInst>(Inst)->getArgOperand(0));
905 break;
906 default:
907 break;
908 }
909 }
Michael Gottesman8f22c8b2013-01-01 16:05:48 +0000910
911 DEBUG(dbgs() << "ObjCARCExpand: Finished Queue.\n\n");
912
John McCall9fbd3182011-06-15 23:37:01 +0000913 return Changed;
914}
915
916//===----------------------------------------------------------------------===//
Dan Gohman2f6263c2012-01-17 20:52:24 +0000917// ARC autorelease pool elimination.
918//===----------------------------------------------------------------------===//
919
Dan Gohman0daef3d2012-05-08 23:39:44 +0000920#include "llvm/ADT/STLExtras.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +0000921#include "llvm/Constants.h"
Dan Gohman1dae3e92012-01-18 21:19:38 +0000922
Dan Gohman2f6263c2012-01-17 20:52:24 +0000923namespace {
924 /// ObjCARCAPElim - Autorelease pool elimination.
925 class ObjCARCAPElim : public ModulePass {
926 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
927 virtual bool runOnModule(Module &M);
928
Dan Gohman447989c2012-04-27 18:56:31 +0000929 static bool MayAutorelease(ImmutableCallSite CS, unsigned Depth = 0);
930 static bool OptimizeBB(BasicBlock *BB);
Dan Gohman2f6263c2012-01-17 20:52:24 +0000931
932 public:
933 static char ID;
934 ObjCARCAPElim() : ModulePass(ID) {
935 initializeObjCARCAPElimPass(*PassRegistry::getPassRegistry());
936 }
937 };
938}
939
940char ObjCARCAPElim::ID = 0;
941INITIALIZE_PASS(ObjCARCAPElim,
942 "objc-arc-apelim",
943 "ObjC ARC autorelease pool elimination",
944 false, false)
945
946Pass *llvm::createObjCARCAPElimPass() {
947 return new ObjCARCAPElim();
948}
949
950void ObjCARCAPElim::getAnalysisUsage(AnalysisUsage &AU) const {
951 AU.setPreservesCFG();
952}
953
954/// MayAutorelease - Interprocedurally determine if calls made by the
955/// given call site can possibly produce autoreleases.
Dan Gohman447989c2012-04-27 18:56:31 +0000956bool ObjCARCAPElim::MayAutorelease(ImmutableCallSite CS, unsigned Depth) {
957 if (const Function *Callee = CS.getCalledFunction()) {
Dan Gohman2f6263c2012-01-17 20:52:24 +0000958 if (Callee->isDeclaration() || Callee->mayBeOverridden())
959 return true;
Dan Gohman447989c2012-04-27 18:56:31 +0000960 for (Function::const_iterator I = Callee->begin(), E = Callee->end();
Dan Gohman2f6263c2012-01-17 20:52:24 +0000961 I != E; ++I) {
Dan Gohman447989c2012-04-27 18:56:31 +0000962 const BasicBlock *BB = I;
963 for (BasicBlock::const_iterator J = BB->begin(), F = BB->end();
964 J != F; ++J)
965 if (ImmutableCallSite JCS = ImmutableCallSite(J))
Dan Gohman2f77bbd2012-01-18 21:24:45 +0000966 // This recursion depth limit is arbitrary. It's just great
967 // enough to cover known interesting testcases.
968 if (Depth < 3 &&
969 !JCS.onlyReadsMemory() &&
970 MayAutorelease(JCS, Depth + 1))
Dan Gohman2f6263c2012-01-17 20:52:24 +0000971 return true;
972 }
973 return false;
974 }
975
976 return true;
977}
978
979bool ObjCARCAPElim::OptimizeBB(BasicBlock *BB) {
980 bool Changed = false;
981
982 Instruction *Push = 0;
983 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
984 Instruction *Inst = I++;
985 switch (GetBasicInstructionClass(Inst)) {
986 case IC_AutoreleasepoolPush:
987 Push = Inst;
988 break;
989 case IC_AutoreleasepoolPop:
990 // If this pop matches a push and nothing in between can autorelease,
991 // zap the pair.
992 if (Push && cast<CallInst>(Inst)->getArgOperand(0) == Push) {
993 Changed = true;
994 Inst->eraseFromParent();
995 Push->eraseFromParent();
996 }
997 Push = 0;
998 break;
999 case IC_CallOrUser:
Dan Gohman447989c2012-04-27 18:56:31 +00001000 if (MayAutorelease(ImmutableCallSite(Inst)))
Dan Gohman2f6263c2012-01-17 20:52:24 +00001001 Push = 0;
1002 break;
1003 default:
1004 break;
1005 }
1006 }
1007
1008 return Changed;
1009}
1010
1011bool ObjCARCAPElim::runOnModule(Module &M) {
1012 if (!EnableARCOpts)
1013 return false;
1014
1015 // If nothing in the Module uses ARC, don't do anything.
1016 if (!ModuleHasARC(M))
1017 return false;
1018
Dan Gohman1dae3e92012-01-18 21:19:38 +00001019 // Find the llvm.global_ctors variable, as the first step in
Dan Gohmand6bf2012012-04-13 18:57:48 +00001020 // identifying the global constructors. In theory, unnecessary autorelease
1021 // pools could occur anywhere, but in practice it's pretty rare. Global
1022 // ctors are a place where autorelease pools get inserted automatically,
1023 // so it's pretty common for them to be unnecessary, and it's pretty
1024 // profitable to eliminate them.
Dan Gohman1dae3e92012-01-18 21:19:38 +00001025 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1026 if (!GV)
1027 return false;
1028
1029 assert(GV->hasDefinitiveInitializer() &&
1030 "llvm.global_ctors is uncooperative!");
1031
Dan Gohman2f6263c2012-01-17 20:52:24 +00001032 bool Changed = false;
1033
Dan Gohman1dae3e92012-01-18 21:19:38 +00001034 // Dig the constructor functions out of GV's initializer.
1035 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
1036 for (User::op_iterator OI = Init->op_begin(), OE = Init->op_end();
1037 OI != OE; ++OI) {
1038 Value *Op = *OI;
1039 // llvm.global_ctors is an array of pairs where the second members
1040 // are constructor functions.
Dan Gohman3b5b2a22012-04-18 22:24:33 +00001041 Function *F = dyn_cast<Function>(cast<ConstantStruct>(Op)->getOperand(1));
1042 // If the user used a constructor function with the wrong signature and
1043 // it got bitcasted or whatever, look the other way.
1044 if (!F)
1045 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001046 // Only look at function definitions.
1047 if (F->isDeclaration())
1048 continue;
Dan Gohman2f6263c2012-01-17 20:52:24 +00001049 // Only look at functions with one basic block.
1050 if (llvm::next(F->begin()) != F->end())
1051 continue;
1052 // Ok, a single-block constructor function definition. Try to optimize it.
1053 Changed |= OptimizeBB(F->begin());
1054 }
1055
1056 return Changed;
1057}
1058
1059//===----------------------------------------------------------------------===//
John McCall9fbd3182011-06-15 23:37:01 +00001060// ARC optimization.
1061//===----------------------------------------------------------------------===//
1062
1063// TODO: On code like this:
1064//
1065// objc_retain(%x)
1066// stuff_that_cannot_release()
1067// objc_autorelease(%x)
1068// stuff_that_cannot_release()
1069// objc_retain(%x)
1070// stuff_that_cannot_release()
1071// objc_autorelease(%x)
1072//
1073// The second retain and autorelease can be deleted.
1074
1075// TODO: It should be possible to delete
1076// objc_autoreleasePoolPush and objc_autoreleasePoolPop
1077// pairs if nothing is actually autoreleased between them. Also, autorelease
1078// calls followed by objc_autoreleasePoolPop calls (perhaps in ObjC++ code
1079// after inlining) can be turned into plain release calls.
1080
1081// TODO: Critical-edge splitting. If the optimial insertion point is
1082// a critical edge, the current algorithm has to fail, because it doesn't
1083// know how to split edges. It should be possible to make the optimizer
1084// think in terms of edges, rather than blocks, and then split critical
1085// edges on demand.
1086
1087// TODO: OptimizeSequences could generalized to be Interprocedural.
1088
1089// TODO: Recognize that a bunch of other objc runtime calls have
1090// non-escaping arguments and non-releasing arguments, and may be
1091// non-autoreleasing.
1092
1093// TODO: Sink autorelease calls as far as possible. Unfortunately we
1094// usually can't sink them past other calls, which would be the main
1095// case where it would be useful.
1096
Dan Gohmane6d5e882011-08-19 00:26:36 +00001097// TODO: The pointer returned from objc_loadWeakRetained is retained.
1098
1099// TODO: Delete release+retain pairs (rare).
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001100
Chandler Carruthd04a8d42012-12-03 16:50:05 +00001101#include "llvm/ADT/SmallPtrSet.h"
1102#include "llvm/ADT/Statistic.h"
John McCall9fbd3182011-06-15 23:37:01 +00001103#include "llvm/LLVMContext.h"
John McCall9fbd3182011-06-15 23:37:01 +00001104#include "llvm/Support/CFG.h"
John McCall9fbd3182011-06-15 23:37:01 +00001105
1106STATISTIC(NumNoops, "Number of no-op objc calls eliminated");
1107STATISTIC(NumPartialNoops, "Number of partially no-op objc calls eliminated");
1108STATISTIC(NumAutoreleases,"Number of autoreleases converted to releases");
1109STATISTIC(NumRets, "Number of return value forwarding "
1110 "retain+autoreleaes eliminated");
1111STATISTIC(NumRRs, "Number of retain+release paths eliminated");
1112STATISTIC(NumPeeps, "Number of calls peephole-optimized");
1113
1114namespace {
1115 /// ProvenanceAnalysis - This is similar to BasicAliasAnalysis, and it
1116 /// uses many of the same techniques, except it uses special ObjC-specific
1117 /// reasoning about pointer relationships.
1118 class ProvenanceAnalysis {
1119 AliasAnalysis *AA;
1120
1121 typedef std::pair<const Value *, const Value *> ValuePairTy;
1122 typedef DenseMap<ValuePairTy, bool> CachedResultsTy;
1123 CachedResultsTy CachedResults;
1124
1125 bool relatedCheck(const Value *A, const Value *B);
1126 bool relatedSelect(const SelectInst *A, const Value *B);
1127 bool relatedPHI(const PHINode *A, const Value *B);
1128
Craig Topperc2945e42012-09-18 02:01:41 +00001129 void operator=(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
1130 ProvenanceAnalysis(const ProvenanceAnalysis &) LLVM_DELETED_FUNCTION;
John McCall9fbd3182011-06-15 23:37:01 +00001131
1132 public:
1133 ProvenanceAnalysis() {}
1134
1135 void setAA(AliasAnalysis *aa) { AA = aa; }
1136
1137 AliasAnalysis *getAA() const { return AA; }
1138
1139 bool related(const Value *A, const Value *B);
1140
1141 void clear() {
1142 CachedResults.clear();
1143 }
1144 };
1145}
1146
1147bool ProvenanceAnalysis::relatedSelect(const SelectInst *A, const Value *B) {
1148 // If the values are Selects with the same condition, we can do a more precise
1149 // check: just check for relations between the values on corresponding arms.
1150 if (const SelectInst *SB = dyn_cast<SelectInst>(B))
Dan Gohman447989c2012-04-27 18:56:31 +00001151 if (A->getCondition() == SB->getCondition())
1152 return related(A->getTrueValue(), SB->getTrueValue()) ||
1153 related(A->getFalseValue(), SB->getFalseValue());
John McCall9fbd3182011-06-15 23:37:01 +00001154
1155 // Check both arms of the Select node individually.
Dan Gohman447989c2012-04-27 18:56:31 +00001156 return related(A->getTrueValue(), B) ||
1157 related(A->getFalseValue(), B);
John McCall9fbd3182011-06-15 23:37:01 +00001158}
1159
1160bool ProvenanceAnalysis::relatedPHI(const PHINode *A, const Value *B) {
1161 // If the values are PHIs in the same block, we can do a more precise as well
1162 // as efficient check: just check for relations between the values on
1163 // corresponding edges.
1164 if (const PHINode *PNB = dyn_cast<PHINode>(B))
1165 if (PNB->getParent() == A->getParent()) {
1166 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
1167 if (related(A->getIncomingValue(i),
1168 PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
1169 return true;
1170 return false;
1171 }
1172
1173 // Check each unique source of the PHI node against B.
1174 SmallPtrSet<const Value *, 4> UniqueSrc;
1175 for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i) {
1176 const Value *PV1 = A->getIncomingValue(i);
1177 if (UniqueSrc.insert(PV1) && related(PV1, B))
1178 return true;
1179 }
1180
1181 // All of the arms checked out.
1182 return false;
1183}
1184
1185/// isStoredObjCPointer - Test if the value of P, or any value covered by its
1186/// provenance, is ever stored within the function (not counting callees).
1187static bool isStoredObjCPointer(const Value *P) {
1188 SmallPtrSet<const Value *, 8> Visited;
1189 SmallVector<const Value *, 8> Worklist;
1190 Worklist.push_back(P);
1191 Visited.insert(P);
1192 do {
1193 P = Worklist.pop_back_val();
1194 for (Value::const_use_iterator UI = P->use_begin(), UE = P->use_end();
1195 UI != UE; ++UI) {
1196 const User *Ur = *UI;
1197 if (isa<StoreInst>(Ur)) {
1198 if (UI.getOperandNo() == 0)
1199 // The pointer is stored.
1200 return true;
1201 // The pointed is stored through.
1202 continue;
1203 }
1204 if (isa<CallInst>(Ur))
1205 // The pointer is passed as an argument, ignore this.
1206 continue;
1207 if (isa<PtrToIntInst>(P))
1208 // Assume the worst.
1209 return true;
1210 if (Visited.insert(Ur))
1211 Worklist.push_back(Ur);
1212 }
1213 } while (!Worklist.empty());
1214
1215 // Everything checked out.
1216 return false;
1217}
1218
1219bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
1220 // Skip past provenance pass-throughs.
1221 A = GetUnderlyingObjCPtr(A);
1222 B = GetUnderlyingObjCPtr(B);
1223
1224 // Quick check.
1225 if (A == B)
1226 return true;
1227
1228 // Ask regular AliasAnalysis, for a first approximation.
1229 switch (AA->alias(A, B)) {
1230 case AliasAnalysis::NoAlias:
1231 return false;
1232 case AliasAnalysis::MustAlias:
1233 case AliasAnalysis::PartialAlias:
1234 return true;
1235 case AliasAnalysis::MayAlias:
1236 break;
1237 }
1238
1239 bool AIsIdentified = IsObjCIdentifiedObject(A);
1240 bool BIsIdentified = IsObjCIdentifiedObject(B);
1241
1242 // An ObjC-Identified object can't alias a load if it is never locally stored.
1243 if (AIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001244 // Check for an obvious escape.
1245 if (isa<LoadInst>(B))
1246 return isStoredObjCPointer(A);
John McCall9fbd3182011-06-15 23:37:01 +00001247 if (BIsIdentified) {
Dan Gohman230768b2012-09-04 23:16:20 +00001248 // Check for an obvious escape.
1249 if (isa<LoadInst>(A))
1250 return isStoredObjCPointer(B);
1251 // Both pointers are identified and escapes aren't an evident problem.
1252 return false;
John McCall9fbd3182011-06-15 23:37:01 +00001253 }
Dan Gohman230768b2012-09-04 23:16:20 +00001254 } else if (BIsIdentified) {
1255 // Check for an obvious escape.
1256 if (isa<LoadInst>(A))
John McCall9fbd3182011-06-15 23:37:01 +00001257 return isStoredObjCPointer(B);
1258 }
1259
1260 // Special handling for PHI and Select.
1261 if (const PHINode *PN = dyn_cast<PHINode>(A))
1262 return relatedPHI(PN, B);
1263 if (const PHINode *PN = dyn_cast<PHINode>(B))
1264 return relatedPHI(PN, A);
1265 if (const SelectInst *S = dyn_cast<SelectInst>(A))
1266 return relatedSelect(S, B);
1267 if (const SelectInst *S = dyn_cast<SelectInst>(B))
1268 return relatedSelect(S, A);
1269
1270 // Conservative.
1271 return true;
1272}
1273
1274bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
1275 // Begin by inserting a conservative value into the map. If the insertion
1276 // fails, we have the answer already. If it succeeds, leave it there until we
1277 // compute the real answer to guard against recursive queries.
1278 if (A > B) std::swap(A, B);
1279 std::pair<CachedResultsTy::iterator, bool> Pair =
1280 CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
1281 if (!Pair.second)
1282 return Pair.first->second;
1283
1284 bool Result = relatedCheck(A, B);
1285 CachedResults[ValuePairTy(A, B)] = Result;
1286 return Result;
1287}
1288
1289namespace {
1290 // Sequence - A sequence of states that a pointer may go through in which an
1291 // objc_retain and objc_release are actually needed.
1292 enum Sequence {
1293 S_None,
1294 S_Retain, ///< objc_retain(x)
1295 S_CanRelease, ///< foo(x) -- x could possibly see a ref count decrement
1296 S_Use, ///< any use of x
1297 S_Stop, ///< like S_Release, but code motion is stopped
1298 S_Release, ///< objc_release(x)
1299 S_MovableRelease ///< objc_release(x), !clang.imprecise_release
1300 };
1301}
1302
1303static Sequence MergeSeqs(Sequence A, Sequence B, bool TopDown) {
1304 // The easy cases.
1305 if (A == B)
1306 return A;
1307 if (A == S_None || B == S_None)
1308 return S_None;
1309
John McCall9fbd3182011-06-15 23:37:01 +00001310 if (A > B) std::swap(A, B);
1311 if (TopDown) {
1312 // Choose the side which is further along in the sequence.
Dan Gohmana7f7db22011-08-12 00:26:31 +00001313 if ((A == S_Retain || A == S_CanRelease) &&
1314 (B == S_CanRelease || B == S_Use))
John McCall9fbd3182011-06-15 23:37:01 +00001315 return B;
1316 } else {
1317 // Choose the side which is further along in the sequence.
1318 if ((A == S_Use || A == S_CanRelease) &&
Dan Gohmana7f7db22011-08-12 00:26:31 +00001319 (B == S_Use || B == S_Release || B == S_Stop || B == S_MovableRelease))
John McCall9fbd3182011-06-15 23:37:01 +00001320 return A;
1321 // If both sides are releases, choose the more conservative one.
1322 if (A == S_Stop && (B == S_Release || B == S_MovableRelease))
1323 return A;
1324 if (A == S_Release && B == S_MovableRelease)
1325 return A;
1326 }
1327
1328 return S_None;
1329}
1330
1331namespace {
1332 /// RRInfo - Unidirectional information about either a
1333 /// retain-decrement-use-release sequence or release-use-decrement-retain
1334 /// reverese sequence.
1335 struct RRInfo {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001336 /// KnownSafe - After an objc_retain, the reference count of the referenced
1337 /// object is known to be positive. Similarly, before an objc_release, the
1338 /// reference count of the referenced object is known to be positive. If
1339 /// there are retain-release pairs in code regions where the retain count
1340 /// is known to be positive, they can be eliminated, regardless of any side
1341 /// effects between them.
1342 ///
1343 /// Also, a retain+release pair nested within another retain+release
1344 /// pair all on the known same pointer value can be eliminated, regardless
1345 /// of any intervening side effects.
1346 ///
1347 /// KnownSafe is true when either of these conditions is satisfied.
1348 bool KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00001349
1350 /// IsRetainBlock - True if the Calls are objc_retainBlock calls (as
1351 /// opposed to objc_retain calls).
1352 bool IsRetainBlock;
1353
1354 /// IsTailCallRelease - True of the objc_release calls are all marked
1355 /// with the "tail" keyword.
1356 bool IsTailCallRelease;
1357
1358 /// ReleaseMetadata - If the Calls are objc_release calls and they all have
1359 /// a clang.imprecise_release tag, this is the metadata tag.
1360 MDNode *ReleaseMetadata;
1361
1362 /// Calls - For a top-down sequence, the set of objc_retains or
1363 /// objc_retainBlocks. For bottom-up, the set of objc_releases.
1364 SmallPtrSet<Instruction *, 2> Calls;
1365
1366 /// ReverseInsertPts - The set of optimal insert positions for
1367 /// moving calls in the opposite sequence.
1368 SmallPtrSet<Instruction *, 2> ReverseInsertPts;
1369
1370 RRInfo() :
Dan Gohman79522dc2012-01-13 00:39:07 +00001371 KnownSafe(false), IsRetainBlock(false),
Dan Gohman50ade652012-04-25 00:50:46 +00001372 IsTailCallRelease(false),
John McCall9fbd3182011-06-15 23:37:01 +00001373 ReleaseMetadata(0) {}
1374
1375 void clear();
1376 };
1377}
1378
1379void RRInfo::clear() {
Dan Gohmane6d5e882011-08-19 00:26:36 +00001380 KnownSafe = false;
John McCall9fbd3182011-06-15 23:37:01 +00001381 IsRetainBlock = false;
1382 IsTailCallRelease = false;
1383 ReleaseMetadata = 0;
1384 Calls.clear();
1385 ReverseInsertPts.clear();
1386}
1387
1388namespace {
1389 /// PtrState - This class summarizes several per-pointer runtime properties
1390 /// which are propogated through the flow graph.
1391 class PtrState {
Dan Gohman50ade652012-04-25 00:50:46 +00001392 /// KnownPositiveRefCount - True if the reference count is known to
1393 /// be incremented.
1394 bool KnownPositiveRefCount;
1395
1396 /// Partial - True of we've seen an opportunity for partial RR elimination,
1397 /// such as pushing calls into a CFG triangle or into one side of a
1398 /// CFG diamond.
1399 bool Partial;
John McCall9fbd3182011-06-15 23:37:01 +00001400
1401 /// Seq - The current position in the sequence.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001402 Sequence Seq : 8;
John McCall9fbd3182011-06-15 23:37:01 +00001403
1404 public:
1405 /// RRI - Unidirectional information about the current sequence.
1406 /// TODO: Encapsulate this better.
1407 RRInfo RRI;
1408
Dan Gohman230768b2012-09-04 23:16:20 +00001409 PtrState() : KnownPositiveRefCount(false), Partial(false),
Dan Gohman0daef3d2012-05-08 23:39:44 +00001410 Seq(S_None) {}
John McCall9fbd3182011-06-15 23:37:01 +00001411
Dan Gohman50ade652012-04-25 00:50:46 +00001412 void SetKnownPositiveRefCount() {
1413 KnownPositiveRefCount = true;
Dan Gohmana7f7db22011-08-12 00:26:31 +00001414 }
1415
Dan Gohman50ade652012-04-25 00:50:46 +00001416 void ClearRefCount() {
1417 KnownPositiveRefCount = false;
John McCall9fbd3182011-06-15 23:37:01 +00001418 }
1419
John McCall9fbd3182011-06-15 23:37:01 +00001420 bool IsKnownIncremented() const {
Dan Gohman50ade652012-04-25 00:50:46 +00001421 return KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001422 }
1423
1424 void SetSeq(Sequence NewSeq) {
1425 Seq = NewSeq;
1426 }
1427
John McCall9fbd3182011-06-15 23:37:01 +00001428 Sequence GetSeq() const {
1429 return Seq;
1430 }
1431
1432 void ClearSequenceProgress() {
Dan Gohman50ade652012-04-25 00:50:46 +00001433 ResetSequenceProgress(S_None);
1434 }
1435
1436 void ResetSequenceProgress(Sequence NewSeq) {
1437 Seq = NewSeq;
1438 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001439 RRI.clear();
1440 }
1441
1442 void Merge(const PtrState &Other, bool TopDown);
1443 };
1444}
1445
1446void
1447PtrState::Merge(const PtrState &Other, bool TopDown) {
1448 Seq = MergeSeqs(Seq, Other.Seq, TopDown);
Dan Gohman50ade652012-04-25 00:50:46 +00001449 KnownPositiveRefCount = KnownPositiveRefCount && Other.KnownPositiveRefCount;
John McCall9fbd3182011-06-15 23:37:01 +00001450
1451 // We can't merge a plain objc_retain with an objc_retainBlock.
1452 if (RRI.IsRetainBlock != Other.RRI.IsRetainBlock)
1453 Seq = S_None;
1454
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001455 // If we're not in a sequence (anymore), drop all associated state.
John McCall9fbd3182011-06-15 23:37:01 +00001456 if (Seq == S_None) {
Dan Gohman50ade652012-04-25 00:50:46 +00001457 Partial = false;
John McCall9fbd3182011-06-15 23:37:01 +00001458 RRI.clear();
Dan Gohman50ade652012-04-25 00:50:46 +00001459 } else if (Partial || Other.Partial) {
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001460 // If we're doing a merge on a path that's previously seen a partial
1461 // merge, conservatively drop the sequence, to avoid doing partial
1462 // RR elimination. If the branch predicates for the two merge differ,
1463 // mixing them is unsafe.
Dan Gohman50ade652012-04-25 00:50:46 +00001464 ClearSequenceProgress();
John McCall9fbd3182011-06-15 23:37:01 +00001465 } else {
1466 // Conservatively merge the ReleaseMetadata information.
1467 if (RRI.ReleaseMetadata != Other.RRI.ReleaseMetadata)
1468 RRI.ReleaseMetadata = 0;
1469
Dan Gohmane6d5e882011-08-19 00:26:36 +00001470 RRI.KnownSafe = RRI.KnownSafe && Other.RRI.KnownSafe;
Dan Gohman0daef3d2012-05-08 23:39:44 +00001471 RRI.IsTailCallRelease = RRI.IsTailCallRelease &&
1472 Other.RRI.IsTailCallRelease;
John McCall9fbd3182011-06-15 23:37:01 +00001473 RRI.Calls.insert(Other.RRI.Calls.begin(), Other.RRI.Calls.end());
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001474
1475 // Merge the insert point sets. If there are any differences,
1476 // that makes this a partial merge.
Dan Gohman0daef3d2012-05-08 23:39:44 +00001477 Partial = RRI.ReverseInsertPts.size() != Other.RRI.ReverseInsertPts.size();
Dan Gohman90b8bcd2011-10-17 18:48:25 +00001478 for (SmallPtrSet<Instruction *, 2>::const_iterator
1479 I = Other.RRI.ReverseInsertPts.begin(),
1480 E = Other.RRI.ReverseInsertPts.end(); I != E; ++I)
Dan Gohman50ade652012-04-25 00:50:46 +00001481 Partial |= RRI.ReverseInsertPts.insert(*I);
John McCall9fbd3182011-06-15 23:37:01 +00001482 }
1483}
1484
1485namespace {
1486 /// BBState - Per-BasicBlock state.
1487 class BBState {
1488 /// TopDownPathCount - The number of unique control paths from the entry
1489 /// which can reach this block.
1490 unsigned TopDownPathCount;
1491
1492 /// BottomUpPathCount - The number of unique control paths to exits
1493 /// from this block.
1494 unsigned BottomUpPathCount;
1495
1496 /// MapTy - A type for PerPtrTopDown and PerPtrBottomUp.
1497 typedef MapVector<const Value *, PtrState> MapTy;
1498
1499 /// PerPtrTopDown - The top-down traversal uses this to record information
1500 /// known about a pointer at the bottom of each block.
1501 MapTy PerPtrTopDown;
1502
1503 /// PerPtrBottomUp - The bottom-up traversal uses this to record information
1504 /// known about a pointer at the top of each block.
1505 MapTy PerPtrBottomUp;
1506
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001507 /// Preds, Succs - Effective successors and predecessors of the current
1508 /// block (this ignores ignorable edges and ignored backedges).
1509 SmallVector<BasicBlock *, 2> Preds;
1510 SmallVector<BasicBlock *, 2> Succs;
1511
John McCall9fbd3182011-06-15 23:37:01 +00001512 public:
1513 BBState() : TopDownPathCount(0), BottomUpPathCount(0) {}
1514
1515 typedef MapTy::iterator ptr_iterator;
1516 typedef MapTy::const_iterator ptr_const_iterator;
1517
1518 ptr_iterator top_down_ptr_begin() { return PerPtrTopDown.begin(); }
1519 ptr_iterator top_down_ptr_end() { return PerPtrTopDown.end(); }
1520 ptr_const_iterator top_down_ptr_begin() const {
1521 return PerPtrTopDown.begin();
1522 }
1523 ptr_const_iterator top_down_ptr_end() const {
1524 return PerPtrTopDown.end();
1525 }
1526
1527 ptr_iterator bottom_up_ptr_begin() { return PerPtrBottomUp.begin(); }
1528 ptr_iterator bottom_up_ptr_end() { return PerPtrBottomUp.end(); }
1529 ptr_const_iterator bottom_up_ptr_begin() const {
1530 return PerPtrBottomUp.begin();
1531 }
1532 ptr_const_iterator bottom_up_ptr_end() const {
1533 return PerPtrBottomUp.end();
1534 }
1535
1536 /// SetAsEntry - Mark this block as being an entry block, which has one
1537 /// path from the entry by definition.
1538 void SetAsEntry() { TopDownPathCount = 1; }
1539
1540 /// SetAsExit - Mark this block as being an exit block, which has one
1541 /// path to an exit by definition.
1542 void SetAsExit() { BottomUpPathCount = 1; }
1543
1544 PtrState &getPtrTopDownState(const Value *Arg) {
1545 return PerPtrTopDown[Arg];
1546 }
1547
1548 PtrState &getPtrBottomUpState(const Value *Arg) {
1549 return PerPtrBottomUp[Arg];
1550 }
1551
1552 void clearBottomUpPointers() {
Evan Chenga81388f2011-08-04 18:40:26 +00001553 PerPtrBottomUp.clear();
John McCall9fbd3182011-06-15 23:37:01 +00001554 }
1555
1556 void clearTopDownPointers() {
1557 PerPtrTopDown.clear();
1558 }
1559
1560 void InitFromPred(const BBState &Other);
1561 void InitFromSucc(const BBState &Other);
1562 void MergePred(const BBState &Other);
1563 void MergeSucc(const BBState &Other);
1564
1565 /// GetAllPathCount - Return the number of possible unique paths from an
1566 /// entry to an exit which pass through this block. This is only valid
1567 /// after both the top-down and bottom-up traversals are complete.
1568 unsigned GetAllPathCount() const {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001569 assert(TopDownPathCount != 0);
1570 assert(BottomUpPathCount != 0);
John McCall9fbd3182011-06-15 23:37:01 +00001571 return TopDownPathCount * BottomUpPathCount;
1572 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00001573
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001574 // Specialized CFG utilities.
Dan Gohman447989c2012-04-27 18:56:31 +00001575 typedef SmallVectorImpl<BasicBlock *>::const_iterator edge_iterator;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00001576 edge_iterator pred_begin() { return Preds.begin(); }
1577 edge_iterator pred_end() { return Preds.end(); }
1578 edge_iterator succ_begin() { return Succs.begin(); }
1579 edge_iterator succ_end() { return Succs.end(); }
1580
1581 void addSucc(BasicBlock *Succ) { Succs.push_back(Succ); }
1582 void addPred(BasicBlock *Pred) { Preds.push_back(Pred); }
1583
1584 bool isExit() const { return Succs.empty(); }
John McCall9fbd3182011-06-15 23:37:01 +00001585 };
1586}
1587
1588void BBState::InitFromPred(const BBState &Other) {
1589 PerPtrTopDown = Other.PerPtrTopDown;
1590 TopDownPathCount = Other.TopDownPathCount;
1591}
1592
1593void BBState::InitFromSucc(const BBState &Other) {
1594 PerPtrBottomUp = Other.PerPtrBottomUp;
1595 BottomUpPathCount = Other.BottomUpPathCount;
1596}
1597
1598/// MergePred - The top-down traversal uses this to merge information about
1599/// predecessors to form the initial state for a new block.
1600void BBState::MergePred(const BBState &Other) {
1601 // Other.TopDownPathCount can be 0, in which case it is either dead or a
1602 // loop backedge. Loop backedges are special.
1603 TopDownPathCount += Other.TopDownPathCount;
1604
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001605 // Check for overflow. If we have overflow, fall back to conservative behavior.
1606 if (TopDownPathCount < Other.TopDownPathCount) {
1607 clearTopDownPointers();
1608 return;
1609 }
1610
John McCall9fbd3182011-06-15 23:37:01 +00001611 // For each entry in the other set, if our set has an entry with the same key,
1612 // merge the entries. Otherwise, copy the entry and merge it with an empty
1613 // entry.
1614 for (ptr_const_iterator MI = Other.top_down_ptr_begin(),
1615 ME = Other.top_down_ptr_end(); MI != ME; ++MI) {
1616 std::pair<ptr_iterator, bool> Pair = PerPtrTopDown.insert(*MI);
1617 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1618 /*TopDown=*/true);
1619 }
1620
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001621 // For each entry in our set, if the other set doesn't have an entry with the
John McCall9fbd3182011-06-15 23:37:01 +00001622 // same key, force it to merge with an empty entry.
1623 for (ptr_iterator MI = top_down_ptr_begin(),
1624 ME = top_down_ptr_end(); MI != ME; ++MI)
1625 if (Other.PerPtrTopDown.find(MI->first) == Other.PerPtrTopDown.end())
1626 MI->second.Merge(PtrState(), /*TopDown=*/true);
1627}
1628
1629/// MergeSucc - The bottom-up traversal uses this to merge information about
1630/// successors to form the initial state for a new block.
1631void BBState::MergeSucc(const BBState &Other) {
1632 // Other.BottomUpPathCount can be 0, in which case it is either dead or a
1633 // loop backedge. Loop backedges are special.
1634 BottomUpPathCount += Other.BottomUpPathCount;
1635
Dan Gohman0d1bc5f2012-09-12 20:45:17 +00001636 // Check for overflow. If we have overflow, fall back to conservative behavior.
1637 if (BottomUpPathCount < Other.BottomUpPathCount) {
1638 clearBottomUpPointers();
1639 return;
1640 }
1641
John McCall9fbd3182011-06-15 23:37:01 +00001642 // For each entry in the other set, if our set has an entry with the
1643 // same key, merge the entries. Otherwise, copy the entry and merge
1644 // it with an empty entry.
1645 for (ptr_const_iterator MI = Other.bottom_up_ptr_begin(),
1646 ME = Other.bottom_up_ptr_end(); MI != ME; ++MI) {
1647 std::pair<ptr_iterator, bool> Pair = PerPtrBottomUp.insert(*MI);
1648 Pair.first->second.Merge(Pair.second ? PtrState() : MI->second,
1649 /*TopDown=*/false);
1650 }
1651
Dan Gohmanfa7eed12011-08-11 21:06:32 +00001652 // For each entry in our set, if the other set doesn't have an entry
John McCall9fbd3182011-06-15 23:37:01 +00001653 // with the same key, force it to merge with an empty entry.
1654 for (ptr_iterator MI = bottom_up_ptr_begin(),
1655 ME = bottom_up_ptr_end(); MI != ME; ++MI)
1656 if (Other.PerPtrBottomUp.find(MI->first) == Other.PerPtrBottomUp.end())
1657 MI->second.Merge(PtrState(), /*TopDown=*/false);
1658}
1659
1660namespace {
1661 /// ObjCARCOpt - The main ARC optimization pass.
1662 class ObjCARCOpt : public FunctionPass {
1663 bool Changed;
1664 ProvenanceAnalysis PA;
1665
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00001666 /// Run - A flag indicating whether this optimization pass should run.
1667 bool Run;
1668
John McCall9fbd3182011-06-15 23:37:01 +00001669 /// RetainRVCallee, etc. - Declarations for ObjC runtime
1670 /// functions, for use in creating calls to them. These are initialized
1671 /// lazily to avoid cluttering up the Module with unused declarations.
1672 Constant *RetainRVCallee, *AutoreleaseRVCallee, *ReleaseCallee,
Dan Gohman44280692011-07-22 22:29:21 +00001673 *RetainCallee, *RetainBlockCallee, *AutoreleaseCallee;
John McCall9fbd3182011-06-15 23:37:01 +00001674
1675 /// UsedInThisFunciton - Flags which determine whether each of the
1676 /// interesting runtine functions is in fact used in the current function.
1677 unsigned UsedInThisFunction;
1678
1679 /// ImpreciseReleaseMDKind - The Metadata Kind for clang.imprecise_release
1680 /// metadata.
1681 unsigned ImpreciseReleaseMDKind;
1682
Dan Gohman62e5b402011-12-12 18:20:00 +00001683 /// CopyOnEscapeMDKind - The Metadata Kind for clang.arc.copy_on_escape
Dan Gohmana974bea2011-10-17 22:53:25 +00001684 /// metadata.
1685 unsigned CopyOnEscapeMDKind;
1686
Dan Gohmandbe266b2012-02-17 18:59:53 +00001687 /// NoObjCARCExceptionsMDKind - The Metadata Kind for
1688 /// clang.arc.no_objc_arc_exceptions metadata.
1689 unsigned NoObjCARCExceptionsMDKind;
1690
John McCall9fbd3182011-06-15 23:37:01 +00001691 Constant *getRetainRVCallee(Module *M);
1692 Constant *getAutoreleaseRVCallee(Module *M);
1693 Constant *getReleaseCallee(Module *M);
1694 Constant *getRetainCallee(Module *M);
Dan Gohman44280692011-07-22 22:29:21 +00001695 Constant *getRetainBlockCallee(Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001696 Constant *getAutoreleaseCallee(Module *M);
1697
Dan Gohman79522dc2012-01-13 00:39:07 +00001698 bool IsRetainBlockOptimizable(const Instruction *Inst);
1699
John McCall9fbd3182011-06-15 23:37:01 +00001700 void OptimizeRetainCall(Function &F, Instruction *Retain);
1701 bool OptimizeRetainRVCall(Function &F, Instruction *RetainRV);
1702 void OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV);
1703 void OptimizeIndividualCalls(Function &F);
1704
1705 void CheckForCFGHazards(const BasicBlock *BB,
1706 DenseMap<const BasicBlock *, BBState> &BBStates,
1707 BBState &MyStates) const;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001708 bool VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00001709 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001710 MapVector<Value *, RRInfo> &Retains,
1711 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001712 bool VisitBottomUp(BasicBlock *BB,
1713 DenseMap<const BasicBlock *, BBState> &BBStates,
1714 MapVector<Value *, RRInfo> &Retains);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00001715 bool VisitInstructionTopDown(Instruction *Inst,
1716 DenseMap<Value *, RRInfo> &Releases,
1717 BBState &MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00001718 bool VisitTopDown(BasicBlock *BB,
1719 DenseMap<const BasicBlock *, BBState> &BBStates,
1720 DenseMap<Value *, RRInfo> &Releases);
1721 bool Visit(Function &F,
1722 DenseMap<const BasicBlock *, BBState> &BBStates,
1723 MapVector<Value *, RRInfo> &Retains,
1724 DenseMap<Value *, RRInfo> &Releases);
1725
1726 void MoveCalls(Value *Arg, RRInfo &RetainsToMove, RRInfo &ReleasesToMove,
1727 MapVector<Value *, RRInfo> &Retains,
1728 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00001729 SmallVectorImpl<Instruction *> &DeadInsts,
1730 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001731
1732 bool PerformCodePlacement(DenseMap<const BasicBlock *, BBState> &BBStates,
1733 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00001734 DenseMap<Value *, RRInfo> &Releases,
1735 Module *M);
John McCall9fbd3182011-06-15 23:37:01 +00001736
1737 void OptimizeWeakCalls(Function &F);
1738
1739 bool OptimizeSequences(Function &F);
1740
1741 void OptimizeReturns(Function &F);
1742
1743 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
1744 virtual bool doInitialization(Module &M);
1745 virtual bool runOnFunction(Function &F);
1746 virtual void releaseMemory();
1747
1748 public:
1749 static char ID;
1750 ObjCARCOpt() : FunctionPass(ID) {
1751 initializeObjCARCOptPass(*PassRegistry::getPassRegistry());
1752 }
1753 };
1754}
1755
1756char ObjCARCOpt::ID = 0;
1757INITIALIZE_PASS_BEGIN(ObjCARCOpt,
1758 "objc-arc", "ObjC ARC optimization", false, false)
1759INITIALIZE_PASS_DEPENDENCY(ObjCARCAliasAnalysis)
1760INITIALIZE_PASS_END(ObjCARCOpt,
1761 "objc-arc", "ObjC ARC optimization", false, false)
1762
1763Pass *llvm::createObjCARCOptPass() {
1764 return new ObjCARCOpt();
1765}
1766
1767void ObjCARCOpt::getAnalysisUsage(AnalysisUsage &AU) const {
1768 AU.addRequired<ObjCARCAliasAnalysis>();
1769 AU.addRequired<AliasAnalysis>();
1770 // ARC optimization doesn't currently split critical edges.
1771 AU.setPreservesCFG();
1772}
1773
Dan Gohman79522dc2012-01-13 00:39:07 +00001774bool ObjCARCOpt::IsRetainBlockOptimizable(const Instruction *Inst) {
1775 // Without the magic metadata tag, we have to assume this might be an
1776 // objc_retainBlock call inserted to convert a block pointer to an id,
1777 // in which case it really is needed.
1778 if (!Inst->getMetadata(CopyOnEscapeMDKind))
1779 return false;
1780
1781 // If the pointer "escapes" (not including being used in a call),
1782 // the copy may be needed.
1783 if (DoesObjCBlockEscape(Inst))
1784 return false;
1785
1786 // Otherwise, it's not needed.
1787 return true;
1788}
1789
John McCall9fbd3182011-06-15 23:37:01 +00001790Constant *ObjCARCOpt::getRetainRVCallee(Module *M) {
1791 if (!RetainRVCallee) {
1792 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001793 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001794 Type *Params[] = { I8X };
1795 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00001796 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001797 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001798 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001799 RetainRVCallee =
1800 M->getOrInsertFunction("objc_retainAutoreleasedReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00001801 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001802 }
1803 return RetainRVCallee;
1804}
1805
1806Constant *ObjCARCOpt::getAutoreleaseRVCallee(Module *M) {
1807 if (!AutoreleaseRVCallee) {
1808 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00001809 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00001810 Type *Params[] = { I8X };
1811 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00001812 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001813 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001814 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001815 AutoreleaseRVCallee =
1816 M->getOrInsertFunction("objc_autoreleaseReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00001817 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001818 }
1819 return AutoreleaseRVCallee;
1820}
1821
1822Constant *ObjCARCOpt::getReleaseCallee(Module *M) {
1823 if (!ReleaseCallee) {
1824 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001825 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001826 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001827 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001828 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001829 ReleaseCallee =
1830 M->getOrInsertFunction(
1831 "objc_release",
1832 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001833 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001834 }
1835 return ReleaseCallee;
1836}
1837
1838Constant *ObjCARCOpt::getRetainCallee(Module *M) {
1839 if (!RetainCallee) {
1840 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001841 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001842 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001843 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001844 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001845 RetainCallee =
1846 M->getOrInsertFunction(
1847 "objc_retain",
1848 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001849 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001850 }
1851 return RetainCallee;
1852}
1853
Dan Gohman44280692011-07-22 22:29:21 +00001854Constant *ObjCARCOpt::getRetainBlockCallee(Module *M) {
1855 if (!RetainBlockCallee) {
1856 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001857 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Dan Gohman1d2fd752011-09-14 18:33:34 +00001858 // objc_retainBlock is not nounwind because it calls user copy constructors
1859 // which could theoretically throw.
Dan Gohman44280692011-07-22 22:29:21 +00001860 RetainBlockCallee =
1861 M->getOrInsertFunction(
1862 "objc_retainBlock",
1863 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling99faa3b2012-12-07 23:16:57 +00001864 AttributeSet());
Dan Gohman44280692011-07-22 22:29:21 +00001865 }
1866 return RetainBlockCallee;
1867}
1868
John McCall9fbd3182011-06-15 23:37:01 +00001869Constant *ObjCARCOpt::getAutoreleaseCallee(Module *M) {
1870 if (!AutoreleaseCallee) {
1871 LLVMContext &C = M->getContext();
Dan Gohman0daef3d2012-05-08 23:39:44 +00001872 Type *Params[] = { PointerType::getUnqual(Type::getInt8Ty(C)) };
Bill Wendling034b94b2012-12-19 07:18:57 +00001873 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00001874 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00001875 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00001876 AutoreleaseCallee =
1877 M->getOrInsertFunction(
1878 "objc_autorelease",
1879 FunctionType::get(Params[0], Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00001880 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00001881 }
1882 return AutoreleaseCallee;
1883}
1884
Dan Gohman230768b2012-09-04 23:16:20 +00001885/// IsPotentialUse - Test whether the given value is possible a
1886/// reference-counted pointer, including tests which utilize AliasAnalysis.
1887static bool IsPotentialUse(const Value *Op, AliasAnalysis &AA) {
1888 // First make the rudimentary check.
1889 if (!IsPotentialUse(Op))
1890 return false;
1891
1892 // Objects in constant memory are not reference-counted.
1893 if (AA.pointsToConstantMemory(Op))
1894 return false;
1895
1896 // Pointers in constant memory are not pointing to reference-counted objects.
1897 if (const LoadInst *LI = dyn_cast<LoadInst>(Op))
1898 if (AA.pointsToConstantMemory(LI->getPointerOperand()))
1899 return false;
1900
1901 // Otherwise assume the worst.
1902 return true;
1903}
1904
John McCall9fbd3182011-06-15 23:37:01 +00001905/// CanAlterRefCount - Test whether the given instruction can result in a
1906/// reference count modification (positive or negative) for the pointer's
1907/// object.
1908static bool
1909CanAlterRefCount(const Instruction *Inst, const Value *Ptr,
1910 ProvenanceAnalysis &PA, InstructionClass Class) {
1911 switch (Class) {
1912 case IC_Autorelease:
1913 case IC_AutoreleaseRV:
1914 case IC_User:
1915 // These operations never directly modify a reference count.
1916 return false;
1917 default: break;
1918 }
1919
1920 ImmutableCallSite CS = static_cast<const Value *>(Inst);
1921 assert(CS && "Only calls can alter reference counts!");
1922
1923 // See if AliasAnalysis can help us with the call.
1924 AliasAnalysis::ModRefBehavior MRB = PA.getAA()->getModRefBehavior(CS);
1925 if (AliasAnalysis::onlyReadsMemory(MRB))
1926 return false;
1927 if (AliasAnalysis::onlyAccessesArgPointees(MRB)) {
1928 for (ImmutableCallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1929 I != E; ++I) {
1930 const Value *Op = *I;
Dan Gohman230768b2012-09-04 23:16:20 +00001931 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001932 return true;
1933 }
1934 return false;
1935 }
1936
1937 // Assume the worst.
1938 return true;
1939}
1940
1941/// CanUse - Test whether the given instruction can "use" the given pointer's
1942/// object in a way that requires the reference count to be positive.
1943static bool
1944CanUse(const Instruction *Inst, const Value *Ptr, ProvenanceAnalysis &PA,
1945 InstructionClass Class) {
1946 // IC_Call operations (as opposed to IC_CallOrUser) never "use" objc pointers.
1947 if (Class == IC_Call)
1948 return false;
1949
1950 // Consider various instructions which may have pointer arguments which are
1951 // not "uses".
1952 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(Inst)) {
1953 // Comparing a pointer with null, or any other constant, isn't really a use,
1954 // because we don't care what the pointer points to, or about the values
1955 // of any other dynamic reference-counted pointers.
Dan Gohman230768b2012-09-04 23:16:20 +00001956 if (!IsPotentialUse(ICI->getOperand(1), *PA.getAA()))
John McCall9fbd3182011-06-15 23:37:01 +00001957 return false;
1958 } else if (ImmutableCallSite CS = static_cast<const Value *>(Inst)) {
1959 // For calls, just check the arguments (and not the callee operand).
1960 for (ImmutableCallSite::arg_iterator OI = CS.arg_begin(),
1961 OE = CS.arg_end(); OI != OE; ++OI) {
1962 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00001963 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001964 return true;
1965 }
1966 return false;
1967 } else if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1968 // Special-case stores, because we don't care about the stored value, just
1969 // the store address.
1970 const Value *Op = GetUnderlyingObjCPtr(SI->getPointerOperand());
1971 // If we can't tell what the underlying object was, assume there is a
1972 // dependence.
Dan Gohman230768b2012-09-04 23:16:20 +00001973 return IsPotentialUse(Op, *PA.getAA()) && PA.related(Op, Ptr);
John McCall9fbd3182011-06-15 23:37:01 +00001974 }
1975
1976 // Check each operand for a match.
1977 for (User::const_op_iterator OI = Inst->op_begin(), OE = Inst->op_end();
1978 OI != OE; ++OI) {
1979 const Value *Op = *OI;
Dan Gohman230768b2012-09-04 23:16:20 +00001980 if (IsPotentialUse(Op, *PA.getAA()) && PA.related(Ptr, Op))
John McCall9fbd3182011-06-15 23:37:01 +00001981 return true;
1982 }
1983 return false;
1984}
1985
1986/// CanInterruptRV - Test whether the given instruction can autorelease
1987/// any pointer or cause an autoreleasepool pop.
1988static bool
1989CanInterruptRV(InstructionClass Class) {
1990 switch (Class) {
1991 case IC_AutoreleasepoolPop:
1992 case IC_CallOrUser:
1993 case IC_Call:
1994 case IC_Autorelease:
1995 case IC_AutoreleaseRV:
1996 case IC_FusedRetainAutorelease:
1997 case IC_FusedRetainAutoreleaseRV:
1998 return true;
1999 default:
2000 return false;
2001 }
2002}
2003
2004namespace {
2005 /// DependenceKind - There are several kinds of dependence-like concepts in
2006 /// use here.
2007 enum DependenceKind {
2008 NeedsPositiveRetainCount,
Dan Gohman511568d2012-04-13 00:59:57 +00002009 AutoreleasePoolBoundary,
John McCall9fbd3182011-06-15 23:37:01 +00002010 CanChangeRetainCount,
2011 RetainAutoreleaseDep, ///< Blocks objc_retainAutorelease.
2012 RetainAutoreleaseRVDep, ///< Blocks objc_retainAutoreleaseReturnValue.
2013 RetainRVDep ///< Blocks objc_retainAutoreleasedReturnValue.
2014 };
2015}
2016
2017/// Depends - Test if there can be dependencies on Inst through Arg. This
2018/// function only tests dependencies relevant for removing pairs of calls.
2019static bool
2020Depends(DependenceKind Flavor, Instruction *Inst, const Value *Arg,
2021 ProvenanceAnalysis &PA) {
2022 // If we've reached the definition of Arg, stop.
2023 if (Inst == Arg)
2024 return true;
2025
2026 switch (Flavor) {
2027 case NeedsPositiveRetainCount: {
2028 InstructionClass Class = GetInstructionClass(Inst);
2029 switch (Class) {
2030 case IC_AutoreleasepoolPop:
2031 case IC_AutoreleasepoolPush:
2032 case IC_None:
2033 return false;
2034 default:
2035 return CanUse(Inst, Arg, PA, Class);
2036 }
2037 }
2038
Dan Gohman511568d2012-04-13 00:59:57 +00002039 case AutoreleasePoolBoundary: {
2040 InstructionClass Class = GetInstructionClass(Inst);
2041 switch (Class) {
2042 case IC_AutoreleasepoolPop:
2043 case IC_AutoreleasepoolPush:
2044 // These mark the end and begin of an autorelease pool scope.
2045 return true;
2046 default:
2047 // Nothing else does this.
2048 return false;
2049 }
2050 }
2051
John McCall9fbd3182011-06-15 23:37:01 +00002052 case CanChangeRetainCount: {
2053 InstructionClass Class = GetInstructionClass(Inst);
2054 switch (Class) {
2055 case IC_AutoreleasepoolPop:
2056 // Conservatively assume this can decrement any count.
2057 return true;
2058 case IC_AutoreleasepoolPush:
2059 case IC_None:
2060 return false;
2061 default:
2062 return CanAlterRefCount(Inst, Arg, PA, Class);
2063 }
2064 }
2065
2066 case RetainAutoreleaseDep:
2067 switch (GetBasicInstructionClass(Inst)) {
2068 case IC_AutoreleasepoolPop:
Dan Gohman511568d2012-04-13 00:59:57 +00002069 case IC_AutoreleasepoolPush:
John McCall9fbd3182011-06-15 23:37:01 +00002070 // Don't merge an objc_autorelease with an objc_retain inside a different
2071 // autoreleasepool scope.
2072 return true;
2073 case IC_Retain:
2074 case IC_RetainRV:
2075 // Check for a retain of the same pointer for merging.
2076 return GetObjCArg(Inst) == Arg;
2077 default:
2078 // Nothing else matters for objc_retainAutorelease formation.
2079 return false;
2080 }
John McCall9fbd3182011-06-15 23:37:01 +00002081
2082 case RetainAutoreleaseRVDep: {
2083 InstructionClass Class = GetBasicInstructionClass(Inst);
2084 switch (Class) {
2085 case IC_Retain:
2086 case IC_RetainRV:
2087 // Check for a retain of the same pointer for merging.
2088 return GetObjCArg(Inst) == Arg;
2089 default:
2090 // Anything that can autorelease interrupts
2091 // retainAutoreleaseReturnValue formation.
2092 return CanInterruptRV(Class);
2093 }
John McCall9fbd3182011-06-15 23:37:01 +00002094 }
2095
2096 case RetainRVDep:
2097 return CanInterruptRV(GetBasicInstructionClass(Inst));
2098 }
2099
2100 llvm_unreachable("Invalid dependence flavor");
John McCall9fbd3182011-06-15 23:37:01 +00002101}
2102
2103/// FindDependencies - Walk up the CFG from StartPos (which is in StartBB) and
2104/// find local and non-local dependencies on Arg.
2105/// TODO: Cache results?
2106static void
2107FindDependencies(DependenceKind Flavor,
2108 const Value *Arg,
2109 BasicBlock *StartBB, Instruction *StartInst,
2110 SmallPtrSet<Instruction *, 4> &DependingInstructions,
2111 SmallPtrSet<const BasicBlock *, 4> &Visited,
2112 ProvenanceAnalysis &PA) {
2113 BasicBlock::iterator StartPos = StartInst;
2114
2115 SmallVector<std::pair<BasicBlock *, BasicBlock::iterator>, 4> Worklist;
2116 Worklist.push_back(std::make_pair(StartBB, StartPos));
2117 do {
2118 std::pair<BasicBlock *, BasicBlock::iterator> Pair =
2119 Worklist.pop_back_val();
2120 BasicBlock *LocalStartBB = Pair.first;
2121 BasicBlock::iterator LocalStartPos = Pair.second;
2122 BasicBlock::iterator StartBBBegin = LocalStartBB->begin();
2123 for (;;) {
2124 if (LocalStartPos == StartBBBegin) {
2125 pred_iterator PI(LocalStartBB), PE(LocalStartBB, false);
2126 if (PI == PE)
2127 // If we've reached the function entry, produce a null dependence.
2128 DependingInstructions.insert(0);
2129 else
2130 // Add the predecessors to the worklist.
2131 do {
2132 BasicBlock *PredBB = *PI;
2133 if (Visited.insert(PredBB))
2134 Worklist.push_back(std::make_pair(PredBB, PredBB->end()));
2135 } while (++PI != PE);
2136 break;
2137 }
2138
2139 Instruction *Inst = --LocalStartPos;
2140 if (Depends(Flavor, Inst, Arg, PA)) {
2141 DependingInstructions.insert(Inst);
2142 break;
2143 }
2144 }
2145 } while (!Worklist.empty());
2146
2147 // Determine whether the original StartBB post-dominates all of the blocks we
2148 // visited. If not, insert a sentinal indicating that most optimizations are
2149 // not safe.
2150 for (SmallPtrSet<const BasicBlock *, 4>::const_iterator I = Visited.begin(),
2151 E = Visited.end(); I != E; ++I) {
2152 const BasicBlock *BB = *I;
2153 if (BB == StartBB)
2154 continue;
2155 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2156 for (succ_const_iterator SI(TI), SE(TI, false); SI != SE; ++SI) {
2157 const BasicBlock *Succ = *SI;
2158 if (Succ != StartBB && !Visited.count(Succ)) {
2159 DependingInstructions.insert(reinterpret_cast<Instruction *>(-1));
2160 return;
2161 }
2162 }
2163 }
2164}
2165
2166static bool isNullOrUndef(const Value *V) {
2167 return isa<ConstantPointerNull>(V) || isa<UndefValue>(V);
2168}
2169
2170static bool isNoopInstruction(const Instruction *I) {
2171 return isa<BitCastInst>(I) ||
2172 (isa<GetElementPtrInst>(I) &&
2173 cast<GetElementPtrInst>(I)->hasAllZeroIndices());
2174}
2175
2176/// OptimizeRetainCall - Turn objc_retain into
2177/// objc_retainAutoreleasedReturnValue if the operand is a return value.
2178void
2179ObjCARCOpt::OptimizeRetainCall(Function &F, Instruction *Retain) {
Dan Gohman447989c2012-04-27 18:56:31 +00002180 ImmutableCallSite CS(GetObjCArg(Retain));
2181 const Instruction *Call = CS.getInstruction();
John McCall9fbd3182011-06-15 23:37:01 +00002182 if (!Call) return;
2183 if (Call->getParent() != Retain->getParent()) return;
2184
2185 // Check that the call is next to the retain.
Dan Gohman447989c2012-04-27 18:56:31 +00002186 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002187 ++I;
2188 while (isNoopInstruction(I)) ++I;
2189 if (&*I != Retain)
2190 return;
2191
2192 // Turn it to an objc_retainAutoreleasedReturnValue..
2193 Changed = true;
2194 ++NumPeeps;
2195 cast<CallInst>(Retain)->setCalledFunction(getRetainRVCallee(F.getParent()));
2196}
2197
2198/// OptimizeRetainRVCall - Turn objc_retainAutoreleasedReturnValue into
Dan Gohman447989c2012-04-27 18:56:31 +00002199/// objc_retain if the operand is not a return value. Or, if it can be paired
2200/// with an objc_autoreleaseReturnValue, delete the pair and return true.
John McCall9fbd3182011-06-15 23:37:01 +00002201bool
2202ObjCARCOpt::OptimizeRetainRVCall(Function &F, Instruction *RetainRV) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002203 // Check for the argument being from an immediately preceding call or invoke.
Dan Gohman447989c2012-04-27 18:56:31 +00002204 const Value *Arg = GetObjCArg(RetainRV);
2205 ImmutableCallSite CS(Arg);
2206 if (const Instruction *Call = CS.getInstruction()) {
John McCall9fbd3182011-06-15 23:37:01 +00002207 if (Call->getParent() == RetainRV->getParent()) {
Dan Gohman447989c2012-04-27 18:56:31 +00002208 BasicBlock::const_iterator I = Call;
John McCall9fbd3182011-06-15 23:37:01 +00002209 ++I;
2210 while (isNoopInstruction(I)) ++I;
2211 if (&*I == RetainRV)
2212 return false;
Dan Gohman447989c2012-04-27 18:56:31 +00002213 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002214 BasicBlock *RetainRVParent = RetainRV->getParent();
2215 if (II->getNormalDest() == RetainRVParent) {
Dan Gohman447989c2012-04-27 18:56:31 +00002216 BasicBlock::const_iterator I = RetainRVParent->begin();
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002217 while (isNoopInstruction(I)) ++I;
2218 if (&*I == RetainRV)
2219 return false;
2220 }
John McCall9fbd3182011-06-15 23:37:01 +00002221 }
Dan Gohman6fedb3c2012-03-23 18:09:00 +00002222 }
John McCall9fbd3182011-06-15 23:37:01 +00002223
2224 // Check for being preceded by an objc_autoreleaseReturnValue on the same
2225 // pointer. In this case, we can delete the pair.
2226 BasicBlock::iterator I = RetainRV, Begin = RetainRV->getParent()->begin();
2227 if (I != Begin) {
2228 do --I; while (I != Begin && isNoopInstruction(I));
2229 if (GetBasicInstructionClass(I) == IC_AutoreleaseRV &&
2230 GetObjCArg(I) == Arg) {
2231 Changed = true;
2232 ++NumPeeps;
2233 EraseInstruction(I);
2234 EraseInstruction(RetainRV);
2235 return true;
2236 }
2237 }
2238
2239 // Turn it to a plain objc_retain.
2240 Changed = true;
2241 ++NumPeeps;
2242 cast<CallInst>(RetainRV)->setCalledFunction(getRetainCallee(F.getParent()));
2243 return false;
2244}
2245
2246/// OptimizeAutoreleaseRVCall - Turn objc_autoreleaseReturnValue into
2247/// objc_autorelease if the result is not used as a return value.
2248void
2249ObjCARCOpt::OptimizeAutoreleaseRVCall(Function &F, Instruction *AutoreleaseRV) {
2250 // Check for a return of the pointer value.
2251 const Value *Ptr = GetObjCArg(AutoreleaseRV);
Dan Gohman126a54f2011-08-12 00:36:31 +00002252 SmallVector<const Value *, 2> Users;
2253 Users.push_back(Ptr);
2254 do {
2255 Ptr = Users.pop_back_val();
2256 for (Value::const_use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end();
2257 UI != UE; ++UI) {
2258 const User *I = *UI;
2259 if (isa<ReturnInst>(I) || GetBasicInstructionClass(I) == IC_RetainRV)
2260 return;
2261 if (isa<BitCastInst>(I))
2262 Users.push_back(I);
2263 }
2264 } while (!Users.empty());
John McCall9fbd3182011-06-15 23:37:01 +00002265
2266 Changed = true;
2267 ++NumPeeps;
2268 cast<CallInst>(AutoreleaseRV)->
2269 setCalledFunction(getAutoreleaseCallee(F.getParent()));
2270}
2271
2272/// OptimizeIndividualCalls - Visit each call, one at a time, and make
2273/// simplifications without doing any additional analysis.
2274void ObjCARCOpt::OptimizeIndividualCalls(Function &F) {
2275 // Reset all the flags in preparation for recomputing them.
2276 UsedInThisFunction = 0;
2277
2278 // Visit all objc_* calls in F.
2279 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
2280 Instruction *Inst = &*I++;
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00002281
2282 DEBUG(dbgs() << "ObjCARCOpt: OptimizeIndividualCalls: Visiting: " <<
2283 *Inst << "\n");
2284
John McCall9fbd3182011-06-15 23:37:01 +00002285 InstructionClass Class = GetBasicInstructionClass(Inst);
2286
2287 switch (Class) {
2288 default: break;
2289
2290 // Delete no-op casts. These function calls have special semantics, but
2291 // the semantics are entirely implemented via lowering in the front-end,
2292 // so by the time they reach the optimizer, they are just no-op calls
2293 // which return their argument.
2294 //
2295 // There are gray areas here, as the ability to cast reference-counted
2296 // pointers to raw void* and back allows code to break ARC assumptions,
2297 // however these are currently considered to be unimportant.
2298 case IC_NoopCast:
2299 Changed = true;
2300 ++NumNoops;
2301 EraseInstruction(Inst);
2302 continue;
2303
2304 // If the pointer-to-weak-pointer is null, it's undefined behavior.
2305 case IC_StoreWeak:
2306 case IC_LoadWeak:
2307 case IC_LoadWeakRetained:
2308 case IC_InitWeak:
2309 case IC_DestroyWeak: {
2310 CallInst *CI = cast<CallInst>(Inst);
2311 if (isNullOrUndef(CI->getArgOperand(0))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002312 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002313 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002314 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2315 Constant::getNullValue(Ty),
2316 CI);
2317 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2318 CI->eraseFromParent();
2319 continue;
2320 }
2321 break;
2322 }
2323 case IC_CopyWeak:
2324 case IC_MoveWeak: {
2325 CallInst *CI = cast<CallInst>(Inst);
2326 if (isNullOrUndef(CI->getArgOperand(0)) ||
2327 isNullOrUndef(CI->getArgOperand(1))) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00002328 Changed = true;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002329 Type *Ty = CI->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002330 new StoreInst(UndefValue::get(cast<PointerType>(Ty)->getElementType()),
2331 Constant::getNullValue(Ty),
2332 CI);
2333 CI->replaceAllUsesWith(UndefValue::get(CI->getType()));
2334 CI->eraseFromParent();
2335 continue;
2336 }
2337 break;
2338 }
2339 case IC_Retain:
2340 OptimizeRetainCall(F, Inst);
2341 break;
2342 case IC_RetainRV:
2343 if (OptimizeRetainRVCall(F, Inst))
2344 continue;
2345 break;
2346 case IC_AutoreleaseRV:
2347 OptimizeAutoreleaseRVCall(F, Inst);
2348 break;
2349 }
2350
2351 // objc_autorelease(x) -> objc_release(x) if x is otherwise unused.
2352 if (IsAutorelease(Class) && Inst->use_empty()) {
2353 CallInst *Call = cast<CallInst>(Inst);
2354 const Value *Arg = Call->getArgOperand(0);
2355 Arg = FindSingleUseIdentifiedObject(Arg);
2356 if (Arg) {
2357 Changed = true;
2358 ++NumAutoreleases;
2359
2360 // Create the declaration lazily.
2361 LLVMContext &C = Inst->getContext();
2362 CallInst *NewCall =
2363 CallInst::Create(getReleaseCallee(F.getParent()),
2364 Call->getArgOperand(0), "", Call);
2365 NewCall->setMetadata(ImpreciseReleaseMDKind,
2366 MDNode::get(C, ArrayRef<Value *>()));
2367 EraseInstruction(Call);
2368 Inst = NewCall;
2369 Class = IC_Release;
2370 }
2371 }
2372
2373 // For functions which can never be passed stack arguments, add
2374 // a tail keyword.
2375 if (IsAlwaysTail(Class)) {
2376 Changed = true;
2377 cast<CallInst>(Inst)->setTailCall();
2378 }
2379
2380 // Set nounwind as needed.
2381 if (IsNoThrow(Class)) {
2382 Changed = true;
2383 cast<CallInst>(Inst)->setDoesNotThrow();
2384 }
2385
2386 if (!IsNoopOnNull(Class)) {
2387 UsedInThisFunction |= 1 << Class;
2388 continue;
2389 }
2390
2391 const Value *Arg = GetObjCArg(Inst);
2392
2393 // ARC calls with null are no-ops. Delete them.
2394 if (isNullOrUndef(Arg)) {
2395 Changed = true;
2396 ++NumNoops;
2397 EraseInstruction(Inst);
2398 continue;
2399 }
2400
2401 // Keep track of which of retain, release, autorelease, and retain_block
2402 // are actually present in this function.
2403 UsedInThisFunction |= 1 << Class;
2404
2405 // If Arg is a PHI, and one or more incoming values to the
2406 // PHI are null, and the call is control-equivalent to the PHI, and there
2407 // are no relevant side effects between the PHI and the call, the call
2408 // could be pushed up to just those paths with non-null incoming values.
2409 // For now, don't bother splitting critical edges for this.
2410 SmallVector<std::pair<Instruction *, const Value *>, 4> Worklist;
2411 Worklist.push_back(std::make_pair(Inst, Arg));
2412 do {
2413 std::pair<Instruction *, const Value *> Pair = Worklist.pop_back_val();
2414 Inst = Pair.first;
2415 Arg = Pair.second;
2416
2417 const PHINode *PN = dyn_cast<PHINode>(Arg);
2418 if (!PN) continue;
2419
2420 // Determine if the PHI has any null operands, or any incoming
2421 // critical edges.
2422 bool HasNull = false;
2423 bool HasCriticalEdges = false;
2424 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2425 Value *Incoming =
2426 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2427 if (isNullOrUndef(Incoming))
2428 HasNull = true;
2429 else if (cast<TerminatorInst>(PN->getIncomingBlock(i)->back())
2430 .getNumSuccessors() != 1) {
2431 HasCriticalEdges = true;
2432 break;
2433 }
2434 }
2435 // If we have null operands and no critical edges, optimize.
2436 if (!HasCriticalEdges && HasNull) {
2437 SmallPtrSet<Instruction *, 4> DependingInstructions;
2438 SmallPtrSet<const BasicBlock *, 4> Visited;
2439
2440 // Check that there is nothing that cares about the reference
2441 // count between the call and the phi.
Dan Gohman511568d2012-04-13 00:59:57 +00002442 switch (Class) {
2443 case IC_Retain:
2444 case IC_RetainBlock:
2445 // These can always be moved up.
2446 break;
2447 case IC_Release:
Dan Gohman0daef3d2012-05-08 23:39:44 +00002448 // These can't be moved across things that care about the retain
2449 // count.
Dan Gohman511568d2012-04-13 00:59:57 +00002450 FindDependencies(NeedsPositiveRetainCount, Arg,
2451 Inst->getParent(), Inst,
2452 DependingInstructions, Visited, PA);
2453 break;
2454 case IC_Autorelease:
2455 // These can't be moved across autorelease pool scope boundaries.
2456 FindDependencies(AutoreleasePoolBoundary, Arg,
2457 Inst->getParent(), Inst,
2458 DependingInstructions, Visited, PA);
2459 break;
2460 case IC_RetainRV:
2461 case IC_AutoreleaseRV:
2462 // Don't move these; the RV optimization depends on the autoreleaseRV
2463 // being tail called, and the retainRV being immediately after a call
2464 // (which might still happen if we get lucky with codegen layout, but
2465 // it's not worth taking the chance).
2466 continue;
2467 default:
2468 llvm_unreachable("Invalid dependence flavor");
2469 }
2470
John McCall9fbd3182011-06-15 23:37:01 +00002471 if (DependingInstructions.size() == 1 &&
2472 *DependingInstructions.begin() == PN) {
2473 Changed = true;
2474 ++NumPartialNoops;
2475 // Clone the call into each predecessor that has a non-null value.
2476 CallInst *CInst = cast<CallInst>(Inst);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002477 Type *ParamTy = CInst->getArgOperand(0)->getType();
John McCall9fbd3182011-06-15 23:37:01 +00002478 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2479 Value *Incoming =
2480 StripPointerCastsAndObjCCalls(PN->getIncomingValue(i));
2481 if (!isNullOrUndef(Incoming)) {
2482 CallInst *Clone = cast<CallInst>(CInst->clone());
2483 Value *Op = PN->getIncomingValue(i);
2484 Instruction *InsertPos = &PN->getIncomingBlock(i)->back();
2485 if (Op->getType() != ParamTy)
2486 Op = new BitCastInst(Op, ParamTy, "", InsertPos);
2487 Clone->setArgOperand(0, Op);
2488 Clone->insertBefore(InsertPos);
2489 Worklist.push_back(std::make_pair(Clone, Incoming));
2490 }
2491 }
2492 // Erase the original call.
2493 EraseInstruction(CInst);
2494 continue;
2495 }
2496 }
2497 } while (!Worklist.empty());
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00002498
2499 DEBUG(dbgs() << "ObjCARCOpt: Finished Individual Call Queue.\n\n");
2500
John McCall9fbd3182011-06-15 23:37:01 +00002501 }
2502}
2503
2504/// CheckForCFGHazards - Check for critical edges, loop boundaries, irreducible
2505/// control flow, or other CFG structures where moving code across the edge
2506/// would result in it being executed more.
2507void
2508ObjCARCOpt::CheckForCFGHazards(const BasicBlock *BB,
2509 DenseMap<const BasicBlock *, BBState> &BBStates,
2510 BBState &MyStates) const {
2511 // If any top-down local-use or possible-dec has a succ which is earlier in
2512 // the sequence, forget it.
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002513 for (BBState::ptr_iterator I = MyStates.top_down_ptr_begin(),
John McCall9fbd3182011-06-15 23:37:01 +00002514 E = MyStates.top_down_ptr_end(); I != E; ++I)
2515 switch (I->second.GetSeq()) {
2516 default: break;
2517 case S_Use: {
2518 const Value *Arg = I->first;
2519 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2520 bool SomeSuccHasSame = false;
2521 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002522 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002523 succ_const_iterator SI(TI), SE(TI, false);
2524
2525 // If the terminator is an invoke marked with the
2526 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2527 // ignored, for ARC purposes.
2528 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2529 --SE;
2530
2531 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002532 Sequence SuccSSeq = S_None;
2533 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002534 // If VisitBottomUp has pointer information for this successor, take
2535 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002536 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2537 BBStates.find(*SI);
2538 assert(BBI != BBStates.end());
2539 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2540 SuccSSeq = SuccS.GetSeq();
2541 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002542 switch (SuccSSeq) {
John McCall9fbd3182011-06-15 23:37:01 +00002543 case S_None:
Dan Gohmana7f7db22011-08-12 00:26:31 +00002544 case S_CanRelease: {
Dan Gohman70e29682012-03-02 01:26:46 +00002545 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002546 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002547 break;
2548 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002549 continue;
2550 }
John McCall9fbd3182011-06-15 23:37:01 +00002551 case S_Use:
2552 SomeSuccHasSame = true;
2553 break;
2554 case S_Stop:
2555 case S_Release:
2556 case S_MovableRelease:
Dan Gohman70e29682012-03-02 01:26:46 +00002557 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002558 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002559 break;
2560 case S_Retain:
2561 llvm_unreachable("bottom-up pointer in retain state!");
2562 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002563 }
John McCall9fbd3182011-06-15 23:37:01 +00002564 // If the state at the other end of any of the successor edges
2565 // matches the current state, require all edges to match. This
2566 // guards against loops in the middle of a sequence.
2567 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002568 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002569 break;
John McCall9fbd3182011-06-15 23:37:01 +00002570 }
2571 case S_CanRelease: {
2572 const Value *Arg = I->first;
2573 const TerminatorInst *TI = cast<TerminatorInst>(&BB->back());
2574 bool SomeSuccHasSame = false;
2575 bool AllSuccsHaveSame = true;
Dan Gohman22cc4cc2012-03-02 01:13:53 +00002576 PtrState &S = I->second;
Dan Gohmandbe266b2012-02-17 18:59:53 +00002577 succ_const_iterator SI(TI), SE(TI, false);
2578
2579 // If the terminator is an invoke marked with the
2580 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
2581 // ignored, for ARC purposes.
2582 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
2583 --SE;
2584
2585 for (; SI != SE; ++SI) {
Dan Gohman70e29682012-03-02 01:26:46 +00002586 Sequence SuccSSeq = S_None;
2587 bool SuccSRRIKnownSafe = false;
Dan Gohman0daef3d2012-05-08 23:39:44 +00002588 // If VisitBottomUp has pointer information for this successor, take
2589 // what we know about it.
Dan Gohman447989c2012-04-27 18:56:31 +00002590 DenseMap<const BasicBlock *, BBState>::iterator BBI =
2591 BBStates.find(*SI);
2592 assert(BBI != BBStates.end());
2593 const PtrState &SuccS = BBI->second.getPtrBottomUpState(Arg);
2594 SuccSSeq = SuccS.GetSeq();
2595 SuccSRRIKnownSafe = SuccS.RRI.KnownSafe;
Dan Gohman70e29682012-03-02 01:26:46 +00002596 switch (SuccSSeq) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002597 case S_None: {
Dan Gohman70e29682012-03-02 01:26:46 +00002598 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe) {
Dan Gohmana7f7db22011-08-12 00:26:31 +00002599 S.ClearSequenceProgress();
Dan Gohman70e29682012-03-02 01:26:46 +00002600 break;
2601 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002602 continue;
2603 }
John McCall9fbd3182011-06-15 23:37:01 +00002604 case S_CanRelease:
2605 SomeSuccHasSame = true;
2606 break;
2607 case S_Stop:
2608 case S_Release:
2609 case S_MovableRelease:
2610 case S_Use:
Dan Gohman70e29682012-03-02 01:26:46 +00002611 if (!S.RRI.KnownSafe && !SuccSRRIKnownSafe)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002612 AllSuccsHaveSame = false;
John McCall9fbd3182011-06-15 23:37:01 +00002613 break;
2614 case S_Retain:
2615 llvm_unreachable("bottom-up pointer in retain state!");
2616 }
Dan Gohmana7f7db22011-08-12 00:26:31 +00002617 }
John McCall9fbd3182011-06-15 23:37:01 +00002618 // If the state at the other end of any of the successor edges
2619 // matches the current state, require all edges to match. This
2620 // guards against loops in the middle of a sequence.
2621 if (SomeSuccHasSame && !AllSuccsHaveSame)
Dan Gohmana7f7db22011-08-12 00:26:31 +00002622 S.ClearSequenceProgress();
Dan Gohman2e68beb2011-12-12 18:13:53 +00002623 break;
John McCall9fbd3182011-06-15 23:37:01 +00002624 }
2625 }
2626}
2627
2628bool
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002629ObjCARCOpt::VisitInstructionBottomUp(Instruction *Inst,
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002630 BasicBlock *BB,
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002631 MapVector<Value *, RRInfo> &Retains,
2632 BBState &MyStates) {
2633 bool NestingDetected = false;
2634 InstructionClass Class = GetInstructionClass(Inst);
2635 const Value *Arg = 0;
2636
2637 switch (Class) {
2638 case IC_Release: {
2639 Arg = GetObjCArg(Inst);
2640
2641 PtrState &S = MyStates.getPtrBottomUpState(Arg);
2642
2643 // If we see two releases in a row on the same pointer. If so, make
2644 // a note, and we'll cicle back to revisit it after we've
2645 // hopefully eliminated the second release, which may allow us to
2646 // eliminate the first release too.
2647 // Theoretically we could implement removal of nested retain+release
2648 // pairs by making PtrState hold a stack of states, but this is
2649 // simple and avoids adding overhead for the non-nested case.
2650 if (S.GetSeq() == S_Release || S.GetSeq() == S_MovableRelease)
2651 NestingDetected = true;
2652
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002653 MDNode *ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
Dan Gohman50ade652012-04-25 00:50:46 +00002654 S.ResetSequenceProgress(ReleaseMetadata ? S_MovableRelease : S_Release);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002655 S.RRI.ReleaseMetadata = ReleaseMetadata;
Dan Gohman230768b2012-09-04 23:16:20 +00002656 S.RRI.KnownSafe = S.IsKnownIncremented();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002657 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2658 S.RRI.Calls.insert(Inst);
2659
Dan Gohman230768b2012-09-04 23:16:20 +00002660 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002661 break;
2662 }
2663 case IC_RetainBlock:
2664 // An objc_retainBlock call with just a use may need to be kept,
2665 // because it may be copying a block from the stack to the heap.
2666 if (!IsRetainBlockOptimizable(Inst))
2667 break;
2668 // FALLTHROUGH
2669 case IC_Retain:
2670 case IC_RetainRV: {
2671 Arg = GetObjCArg(Inst);
2672
2673 PtrState &S = MyStates.getPtrBottomUpState(Arg);
Dan Gohman50ade652012-04-25 00:50:46 +00002674 S.SetKnownPositiveRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002675
2676 switch (S.GetSeq()) {
2677 case S_Stop:
2678 case S_Release:
2679 case S_MovableRelease:
2680 case S_Use:
2681 S.RRI.ReverseInsertPts.clear();
2682 // FALL THROUGH
2683 case S_CanRelease:
2684 // Don't do retain+release tracking for IC_RetainRV, because it's
2685 // better to let it remain as the first instruction after a call.
2686 if (Class != IC_RetainRV) {
2687 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
2688 Retains[Inst] = S.RRI;
2689 }
2690 S.ClearSequenceProgress();
2691 break;
2692 case S_None:
2693 break;
2694 case S_Retain:
2695 llvm_unreachable("bottom-up pointer in retain state!");
2696 }
2697 return NestingDetected;
2698 }
2699 case IC_AutoreleasepoolPop:
2700 // Conservatively, clear MyStates for all known pointers.
2701 MyStates.clearBottomUpPointers();
2702 return NestingDetected;
2703 case IC_AutoreleasepoolPush:
2704 case IC_None:
2705 // These are irrelevant.
2706 return NestingDetected;
2707 default:
2708 break;
2709 }
2710
2711 // Consider any other possible effects of this instruction on each
2712 // pointer being tracked.
2713 for (BBState::ptr_iterator MI = MyStates.bottom_up_ptr_begin(),
2714 ME = MyStates.bottom_up_ptr_end(); MI != ME; ++MI) {
2715 const Value *Ptr = MI->first;
2716 if (Ptr == Arg)
2717 continue; // Handled above.
2718 PtrState &S = MI->second;
2719 Sequence Seq = S.GetSeq();
2720
2721 // Check for possible releases.
2722 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00002723 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002724 switch (Seq) {
2725 case S_Use:
2726 S.SetSeq(S_CanRelease);
2727 continue;
2728 case S_CanRelease:
2729 case S_Release:
2730 case S_MovableRelease:
2731 case S_Stop:
2732 case S_None:
2733 break;
2734 case S_Retain:
2735 llvm_unreachable("bottom-up pointer in retain state!");
2736 }
2737 }
2738
2739 // Check for possible direct uses.
2740 switch (Seq) {
2741 case S_Release:
2742 case S_MovableRelease:
2743 if (CanUse(Inst, Ptr, PA, Class)) {
2744 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002745 // If this is an invoke instruction, we're scanning it as part of
2746 // one of its successor blocks, since we can't insert code after it
2747 // in its own block, and we don't want to split critical edges.
2748 if (isa<InvokeInst>(Inst))
2749 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2750 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002751 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002752 S.SetSeq(S_Use);
2753 } else if (Seq == S_Release &&
2754 (Class == IC_User || Class == IC_CallOrUser)) {
2755 // Non-movable releases depend on any possible objc pointer use.
2756 S.SetSeq(S_Stop);
2757 assert(S.RRI.ReverseInsertPts.empty());
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002758 // As above; handle invoke specially.
2759 if (isa<InvokeInst>(Inst))
2760 S.RRI.ReverseInsertPts.insert(BB->getFirstInsertionPt());
2761 else
Francois Pichetb54a5ed2012-03-24 01:36:37 +00002762 S.RRI.ReverseInsertPts.insert(llvm::next(BasicBlock::iterator(Inst)));
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002763 }
2764 break;
2765 case S_Stop:
2766 if (CanUse(Inst, Ptr, PA, Class))
2767 S.SetSeq(S_Use);
2768 break;
2769 case S_CanRelease:
2770 case S_Use:
2771 case S_None:
2772 break;
2773 case S_Retain:
2774 llvm_unreachable("bottom-up pointer in retain state!");
2775 }
2776 }
2777
2778 return NestingDetected;
2779}
2780
2781bool
John McCall9fbd3182011-06-15 23:37:01 +00002782ObjCARCOpt::VisitBottomUp(BasicBlock *BB,
2783 DenseMap<const BasicBlock *, BBState> &BBStates,
2784 MapVector<Value *, RRInfo> &Retains) {
2785 bool NestingDetected = false;
2786 BBState &MyStates = BBStates[BB];
2787
2788 // Merge the states from each successor to compute the initial state
2789 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00002790 BBState::edge_iterator SI(MyStates.succ_begin()),
2791 SE(MyStates.succ_end());
2792 if (SI != SE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002793 const BasicBlock *Succ = *SI;
2794 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Succ);
2795 assert(I != BBStates.end());
2796 MyStates.InitFromSucc(I->second);
2797 ++SI;
2798 for (; SI != SE; ++SI) {
2799 Succ = *SI;
2800 I = BBStates.find(Succ);
2801 assert(I != BBStates.end());
2802 MyStates.MergeSucc(I->second);
2803 }
Dan Gohmandbe266b2012-02-17 18:59:53 +00002804 }
John McCall9fbd3182011-06-15 23:37:01 +00002805
2806 // Visit all the instructions, bottom-up.
2807 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; --I) {
2808 Instruction *Inst = llvm::prior(I);
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002809
2810 // Invoke instructions are visited as part of their successors (below).
2811 if (isa<InvokeInst>(Inst))
2812 continue;
2813
2814 NestingDetected |= VisitInstructionBottomUp(Inst, BB, Retains, MyStates);
2815 }
2816
Dan Gohman447989c2012-04-27 18:56:31 +00002817 // If there's a predecessor with an invoke, visit the invoke as if it were
2818 // part of this block, since we can't insert code after an invoke in its own
2819 // block, and we don't want to split critical edges.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002820 for (BBState::edge_iterator PI(MyStates.pred_begin()),
2821 PE(MyStates.pred_end()); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00002822 BasicBlock *Pred = *PI;
Dan Gohman447989c2012-04-27 18:56:31 +00002823 if (InvokeInst *II = dyn_cast<InvokeInst>(&Pred->back()))
2824 NestingDetected |= VisitInstructionBottomUp(II, BB, Retains, MyStates);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002825 }
John McCall9fbd3182011-06-15 23:37:01 +00002826
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002827 return NestingDetected;
2828}
John McCall9fbd3182011-06-15 23:37:01 +00002829
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002830bool
2831ObjCARCOpt::VisitInstructionTopDown(Instruction *Inst,
2832 DenseMap<Value *, RRInfo> &Releases,
2833 BBState &MyStates) {
2834 bool NestingDetected = false;
2835 InstructionClass Class = GetInstructionClass(Inst);
2836 const Value *Arg = 0;
John McCall9fbd3182011-06-15 23:37:01 +00002837
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002838 switch (Class) {
2839 case IC_RetainBlock:
2840 // An objc_retainBlock call with just a use may need to be kept,
2841 // because it may be copying a block from the stack to the heap.
2842 if (!IsRetainBlockOptimizable(Inst))
2843 break;
2844 // FALLTHROUGH
2845 case IC_Retain:
2846 case IC_RetainRV: {
2847 Arg = GetObjCArg(Inst);
2848
2849 PtrState &S = MyStates.getPtrTopDownState(Arg);
2850
2851 // Don't do retain+release tracking for IC_RetainRV, because it's
2852 // better to let it remain as the first instruction after a call.
2853 if (Class != IC_RetainRV) {
2854 // If we see two retains in a row on the same pointer. If so, make
John McCall9fbd3182011-06-15 23:37:01 +00002855 // a note, and we'll cicle back to revisit it after we've
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002856 // hopefully eliminated the second retain, which may allow us to
2857 // eliminate the first retain too.
John McCall9fbd3182011-06-15 23:37:01 +00002858 // Theoretically we could implement removal of nested retain+release
2859 // pairs by making PtrState hold a stack of states, but this is
2860 // simple and avoids adding overhead for the non-nested case.
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002861 if (S.GetSeq() == S_Retain)
John McCall9fbd3182011-06-15 23:37:01 +00002862 NestingDetected = true;
2863
Dan Gohman50ade652012-04-25 00:50:46 +00002864 S.ResetSequenceProgress(S_Retain);
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002865 S.RRI.IsRetainBlock = Class == IC_RetainBlock;
Dan Gohman230768b2012-09-04 23:16:20 +00002866 S.RRI.KnownSafe = S.IsKnownIncremented();
John McCall9fbd3182011-06-15 23:37:01 +00002867 S.RRI.Calls.insert(Inst);
John McCall9fbd3182011-06-15 23:37:01 +00002868 }
John McCall9fbd3182011-06-15 23:37:01 +00002869
Dan Gohman230768b2012-09-04 23:16:20 +00002870 S.SetKnownPositiveRefCount();
Dan Gohmanc72d3be2012-07-23 19:27:31 +00002871
2872 // A retain can be a potential use; procede to the generic checking
2873 // code below.
2874 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002875 }
2876 case IC_Release: {
2877 Arg = GetObjCArg(Inst);
2878
2879 PtrState &S = MyStates.getPtrTopDownState(Arg);
Dan Gohman230768b2012-09-04 23:16:20 +00002880 S.ClearRefCount();
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002881
2882 switch (S.GetSeq()) {
2883 case S_Retain:
2884 case S_CanRelease:
2885 S.RRI.ReverseInsertPts.clear();
2886 // FALL THROUGH
2887 case S_Use:
2888 S.RRI.ReleaseMetadata = Inst->getMetadata(ImpreciseReleaseMDKind);
2889 S.RRI.IsTailCallRelease = cast<CallInst>(Inst)->isTailCall();
2890 Releases[Inst] = S.RRI;
2891 S.ClearSequenceProgress();
2892 break;
2893 case S_None:
2894 break;
2895 case S_Stop:
2896 case S_Release:
2897 case S_MovableRelease:
2898 llvm_unreachable("top-down pointer in release state!");
2899 }
2900 break;
2901 }
2902 case IC_AutoreleasepoolPop:
2903 // Conservatively, clear MyStates for all known pointers.
2904 MyStates.clearTopDownPointers();
2905 return NestingDetected;
2906 case IC_AutoreleasepoolPush:
2907 case IC_None:
2908 // These are irrelevant.
2909 return NestingDetected;
2910 default:
2911 break;
2912 }
2913
2914 // Consider any other possible effects of this instruction on each
2915 // pointer being tracked.
2916 for (BBState::ptr_iterator MI = MyStates.top_down_ptr_begin(),
2917 ME = MyStates.top_down_ptr_end(); MI != ME; ++MI) {
2918 const Value *Ptr = MI->first;
2919 if (Ptr == Arg)
2920 continue; // Handled above.
2921 PtrState &S = MI->second;
2922 Sequence Seq = S.GetSeq();
2923
2924 // Check for possible releases.
2925 if (CanAlterRefCount(Inst, Ptr, PA, Class)) {
Dan Gohman50ade652012-04-25 00:50:46 +00002926 S.ClearRefCount();
John McCall9fbd3182011-06-15 23:37:01 +00002927 switch (Seq) {
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002928 case S_Retain:
2929 S.SetSeq(S_CanRelease);
2930 assert(S.RRI.ReverseInsertPts.empty());
2931 S.RRI.ReverseInsertPts.insert(Inst);
2932
2933 // One call can't cause a transition from S_Retain to S_CanRelease
2934 // and S_CanRelease to S_Use. If we've made the first transition,
2935 // we're done.
2936 continue;
John McCall9fbd3182011-06-15 23:37:01 +00002937 case S_Use:
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002938 case S_CanRelease:
John McCall9fbd3182011-06-15 23:37:01 +00002939 case S_None:
2940 break;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002941 case S_Stop:
2942 case S_Release:
2943 case S_MovableRelease:
2944 llvm_unreachable("top-down pointer in release state!");
John McCall9fbd3182011-06-15 23:37:01 +00002945 }
2946 }
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002947
2948 // Check for possible direct uses.
2949 switch (Seq) {
2950 case S_CanRelease:
2951 if (CanUse(Inst, Ptr, PA, Class))
2952 S.SetSeq(S_Use);
2953 break;
2954 case S_Retain:
2955 case S_Use:
2956 case S_None:
2957 break;
2958 case S_Stop:
2959 case S_Release:
2960 case S_MovableRelease:
2961 llvm_unreachable("top-down pointer in release state!");
2962 }
John McCall9fbd3182011-06-15 23:37:01 +00002963 }
2964
2965 return NestingDetected;
2966}
2967
2968bool
2969ObjCARCOpt::VisitTopDown(BasicBlock *BB,
2970 DenseMap<const BasicBlock *, BBState> &BBStates,
2971 DenseMap<Value *, RRInfo> &Releases) {
2972 bool NestingDetected = false;
2973 BBState &MyStates = BBStates[BB];
2974
2975 // Merge the states from each predecessor to compute the initial state
2976 // for the current block.
Dan Gohman40e46602012-08-27 18:31:36 +00002977 BBState::edge_iterator PI(MyStates.pred_begin()),
2978 PE(MyStates.pred_end());
2979 if (PI != PE) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002980 const BasicBlock *Pred = *PI;
2981 DenseMap<const BasicBlock *, BBState>::iterator I = BBStates.find(Pred);
2982 assert(I != BBStates.end());
2983 MyStates.InitFromPred(I->second);
2984 ++PI;
2985 for (; PI != PE; ++PI) {
2986 Pred = *PI;
2987 I = BBStates.find(Pred);
2988 assert(I != BBStates.end());
2989 MyStates.MergePred(I->second);
2990 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00002991 }
John McCall9fbd3182011-06-15 23:37:01 +00002992
2993 // Visit all the instructions, top-down.
2994 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
2995 Instruction *Inst = I;
Dan Gohmanc7f5c6e2012-03-22 18:24:56 +00002996 NestingDetected |= VisitInstructionTopDown(Inst, Releases, MyStates);
John McCall9fbd3182011-06-15 23:37:01 +00002997 }
2998
2999 CheckForCFGHazards(BB, BBStates, MyStates);
3000 return NestingDetected;
3001}
3002
Dan Gohman59a1c932011-12-12 19:42:25 +00003003static void
3004ComputePostOrders(Function &F,
3005 SmallVectorImpl<BasicBlock *> &PostOrder,
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003006 SmallVectorImpl<BasicBlock *> &ReverseCFGPostOrder,
3007 unsigned NoObjCARCExceptionsMDKind,
3008 DenseMap<const BasicBlock *, BBState> &BBStates) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003009 /// Visited - The visited set, for doing DFS walks.
3010 SmallPtrSet<BasicBlock *, 16> Visited;
3011
3012 // Do DFS, computing the PostOrder.
3013 SmallPtrSet<BasicBlock *, 16> OnStack;
3014 SmallVector<std::pair<BasicBlock *, succ_iterator>, 16> SuccStack;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003015
3016 // Functions always have exactly one entry block, and we don't have
3017 // any other block that we treat like an entry block.
Dan Gohman59a1c932011-12-12 19:42:25 +00003018 BasicBlock *EntryBB = &F.getEntryBlock();
Dan Gohman0daef3d2012-05-08 23:39:44 +00003019 BBState &MyStates = BBStates[EntryBB];
3020 MyStates.SetAsEntry();
3021 TerminatorInst *EntryTI = cast<TerminatorInst>(&EntryBB->back());
3022 SuccStack.push_back(std::make_pair(EntryBB, succ_iterator(EntryTI)));
Dan Gohman59a1c932011-12-12 19:42:25 +00003023 Visited.insert(EntryBB);
3024 OnStack.insert(EntryBB);
3025 do {
3026 dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003027 BasicBlock *CurrBB = SuccStack.back().first;
3028 TerminatorInst *TI = cast<TerminatorInst>(&CurrBB->back());
3029 succ_iterator SE(TI, false);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003030
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003031 // If the terminator is an invoke marked with the
3032 // clang.arc.no_objc_arc_exceptions metadata, the unwind edge can be
3033 // ignored, for ARC purposes.
3034 if (isa<InvokeInst>(TI) && TI->getMetadata(NoObjCARCExceptionsMDKind))
3035 --SE;
3036
3037 while (SuccStack.back().second != SE) {
3038 BasicBlock *SuccBB = *SuccStack.back().second++;
3039 if (Visited.insert(SuccBB)) {
Dan Gohman0daef3d2012-05-08 23:39:44 +00003040 TerminatorInst *TI = cast<TerminatorInst>(&SuccBB->back());
3041 SuccStack.push_back(std::make_pair(SuccBB, succ_iterator(TI)));
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003042 BBStates[CurrBB].addSucc(SuccBB);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003043 BBState &SuccStates = BBStates[SuccBB];
3044 SuccStates.addPred(CurrBB);
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003045 OnStack.insert(SuccBB);
Dan Gohman59a1c932011-12-12 19:42:25 +00003046 goto dfs_next_succ;
3047 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003048
3049 if (!OnStack.count(SuccBB)) {
3050 BBStates[CurrBB].addSucc(SuccBB);
3051 BBStates[SuccBB].addPred(CurrBB);
3052 }
Dan Gohman59a1c932011-12-12 19:42:25 +00003053 }
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003054 OnStack.erase(CurrBB);
3055 PostOrder.push_back(CurrBB);
3056 SuccStack.pop_back();
Dan Gohman59a1c932011-12-12 19:42:25 +00003057 } while (!SuccStack.empty());
3058
3059 Visited.clear();
3060
Dan Gohman59a1c932011-12-12 19:42:25 +00003061 // Do reverse-CFG DFS, computing the reverse-CFG PostOrder.
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003062 // Functions may have many exits, and there also blocks which we treat
3063 // as exits due to ignored edges.
3064 SmallVector<std::pair<BasicBlock *, BBState::edge_iterator>, 16> PredStack;
3065 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3066 BasicBlock *ExitBB = I;
3067 BBState &MyStates = BBStates[ExitBB];
3068 if (!MyStates.isExit())
3069 continue;
3070
Dan Gohman447989c2012-04-27 18:56:31 +00003071 MyStates.SetAsExit();
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003072
3073 PredStack.push_back(std::make_pair(ExitBB, MyStates.pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003074 Visited.insert(ExitBB);
3075 while (!PredStack.empty()) {
3076 reverse_dfs_next_succ:
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003077 BBState::edge_iterator PE = BBStates[PredStack.back().first].pred_end();
3078 while (PredStack.back().second != PE) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003079 BasicBlock *BB = *PredStack.back().second++;
Dan Gohman59a1c932011-12-12 19:42:25 +00003080 if (Visited.insert(BB)) {
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003081 PredStack.push_back(std::make_pair(BB, BBStates[BB].pred_begin()));
Dan Gohman59a1c932011-12-12 19:42:25 +00003082 goto reverse_dfs_next_succ;
3083 }
3084 }
3085 ReverseCFGPostOrder.push_back(PredStack.pop_back_val().first);
3086 }
3087 }
3088}
3089
John McCall9fbd3182011-06-15 23:37:01 +00003090// Visit - Visit the function both top-down and bottom-up.
3091bool
3092ObjCARCOpt::Visit(Function &F,
3093 DenseMap<const BasicBlock *, BBState> &BBStates,
3094 MapVector<Value *, RRInfo> &Retains,
3095 DenseMap<Value *, RRInfo> &Releases) {
Dan Gohman59a1c932011-12-12 19:42:25 +00003096
3097 // Use reverse-postorder traversals, because we magically know that loops
3098 // will be well behaved, i.e. they won't repeatedly call retain on a single
3099 // pointer without doing a release. We can't use the ReversePostOrderTraversal
3100 // class here because we want the reverse-CFG postorder to consider each
3101 // function exit point, and we want to ignore selected cycle edges.
3102 SmallVector<BasicBlock *, 16> PostOrder;
3103 SmallVector<BasicBlock *, 16> ReverseCFGPostOrder;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003104 ComputePostOrders(F, PostOrder, ReverseCFGPostOrder,
3105 NoObjCARCExceptionsMDKind,
3106 BBStates);
Dan Gohman59a1c932011-12-12 19:42:25 +00003107
3108 // Use reverse-postorder on the reverse CFG for bottom-up.
John McCall9fbd3182011-06-15 23:37:01 +00003109 bool BottomUpNestingDetected = false;
Dan Gohmanb48ef3a2011-08-18 21:27:42 +00003110 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
Dan Gohman59a1c932011-12-12 19:42:25 +00003111 ReverseCFGPostOrder.rbegin(), E = ReverseCFGPostOrder.rend();
3112 I != E; ++I)
3113 BottomUpNestingDetected |= VisitBottomUp(*I, BBStates, Retains);
John McCall9fbd3182011-06-15 23:37:01 +00003114
Dan Gohman59a1c932011-12-12 19:42:25 +00003115 // Use reverse-postorder for top-down.
John McCall9fbd3182011-06-15 23:37:01 +00003116 bool TopDownNestingDetected = false;
Dan Gohman59a1c932011-12-12 19:42:25 +00003117 for (SmallVectorImpl<BasicBlock *>::const_reverse_iterator I =
3118 PostOrder.rbegin(), E = PostOrder.rend();
3119 I != E; ++I)
3120 TopDownNestingDetected |= VisitTopDown(*I, BBStates, Releases);
John McCall9fbd3182011-06-15 23:37:01 +00003121
3122 return TopDownNestingDetected && BottomUpNestingDetected;
3123}
3124
3125/// MoveCalls - Move the calls in RetainsToMove and ReleasesToMove.
3126void ObjCARCOpt::MoveCalls(Value *Arg,
3127 RRInfo &RetainsToMove,
3128 RRInfo &ReleasesToMove,
3129 MapVector<Value *, RRInfo> &Retains,
3130 DenseMap<Value *, RRInfo> &Releases,
Dan Gohman44280692011-07-22 22:29:21 +00003131 SmallVectorImpl<Instruction *> &DeadInsts,
3132 Module *M) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003133 Type *ArgTy = Arg->getType();
Dan Gohman44280692011-07-22 22:29:21 +00003134 Type *ParamTy = PointerType::getUnqual(Type::getInt8Ty(ArgTy->getContext()));
John McCall9fbd3182011-06-15 23:37:01 +00003135
3136 // Insert the new retain and release calls.
3137 for (SmallPtrSet<Instruction *, 2>::const_iterator
3138 PI = ReleasesToMove.ReverseInsertPts.begin(),
3139 PE = ReleasesToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
3140 Instruction *InsertPt = *PI;
3141 Value *MyArg = ArgTy == ParamTy ? Arg :
3142 new BitCastInst(Arg, ParamTy, "", InsertPt);
3143 CallInst *Call =
3144 CallInst::Create(RetainsToMove.IsRetainBlock ?
Dan Gohman44280692011-07-22 22:29:21 +00003145 getRetainBlockCallee(M) : getRetainCallee(M),
John McCall9fbd3182011-06-15 23:37:01 +00003146 MyArg, "", InsertPt);
3147 Call->setDoesNotThrow();
Dan Gohman79522dc2012-01-13 00:39:07 +00003148 if (RetainsToMove.IsRetainBlock)
Dan Gohmana974bea2011-10-17 22:53:25 +00003149 Call->setMetadata(CopyOnEscapeMDKind,
3150 MDNode::get(M->getContext(), ArrayRef<Value *>()));
Dan Gohman79522dc2012-01-13 00:39:07 +00003151 else
John McCall9fbd3182011-06-15 23:37:01 +00003152 Call->setTailCall();
3153 }
3154 for (SmallPtrSet<Instruction *, 2>::const_iterator
3155 PI = RetainsToMove.ReverseInsertPts.begin(),
3156 PE = RetainsToMove.ReverseInsertPts.end(); PI != PE; ++PI) {
Dan Gohmanfbab4a82012-03-23 17:47:54 +00003157 Instruction *InsertPt = *PI;
3158 Value *MyArg = ArgTy == ParamTy ? Arg :
3159 new BitCastInst(Arg, ParamTy, "", InsertPt);
3160 CallInst *Call = CallInst::Create(getReleaseCallee(M), MyArg,
3161 "", InsertPt);
3162 // Attach a clang.imprecise_release metadata tag, if appropriate.
3163 if (MDNode *M = ReleasesToMove.ReleaseMetadata)
3164 Call->setMetadata(ImpreciseReleaseMDKind, M);
3165 Call->setDoesNotThrow();
3166 if (ReleasesToMove.IsTailCallRelease)
3167 Call->setTailCall();
John McCall9fbd3182011-06-15 23:37:01 +00003168 }
3169
3170 // Delete the original retain and release calls.
3171 for (SmallPtrSet<Instruction *, 2>::const_iterator
3172 AI = RetainsToMove.Calls.begin(),
3173 AE = RetainsToMove.Calls.end(); AI != AE; ++AI) {
3174 Instruction *OrigRetain = *AI;
3175 Retains.blot(OrigRetain);
3176 DeadInsts.push_back(OrigRetain);
3177 }
3178 for (SmallPtrSet<Instruction *, 2>::const_iterator
3179 AI = ReleasesToMove.Calls.begin(),
3180 AE = ReleasesToMove.Calls.end(); AI != AE; ++AI) {
3181 Instruction *OrigRelease = *AI;
3182 Releases.erase(OrigRelease);
3183 DeadInsts.push_back(OrigRelease);
3184 }
3185}
3186
Dan Gohmand6bf2012012-04-13 18:57:48 +00003187/// PerformCodePlacement - Identify pairings between the retains and releases,
3188/// and delete and/or move them.
John McCall9fbd3182011-06-15 23:37:01 +00003189bool
3190ObjCARCOpt::PerformCodePlacement(DenseMap<const BasicBlock *, BBState>
3191 &BBStates,
3192 MapVector<Value *, RRInfo> &Retains,
Dan Gohman44280692011-07-22 22:29:21 +00003193 DenseMap<Value *, RRInfo> &Releases,
3194 Module *M) {
John McCall9fbd3182011-06-15 23:37:01 +00003195 bool AnyPairsCompletelyEliminated = false;
3196 RRInfo RetainsToMove;
3197 RRInfo ReleasesToMove;
3198 SmallVector<Instruction *, 4> NewRetains;
3199 SmallVector<Instruction *, 4> NewReleases;
3200 SmallVector<Instruction *, 8> DeadInsts;
3201
Dan Gohmand6bf2012012-04-13 18:57:48 +00003202 // Visit each retain.
John McCall9fbd3182011-06-15 23:37:01 +00003203 for (MapVector<Value *, RRInfo>::const_iterator I = Retains.begin(),
Dan Gohman597fece2011-09-29 22:25:23 +00003204 E = Retains.end(); I != E; ++I) {
3205 Value *V = I->first;
John McCall9fbd3182011-06-15 23:37:01 +00003206 if (!V) continue; // blotted
3207
3208 Instruction *Retain = cast<Instruction>(V);
3209 Value *Arg = GetObjCArg(Retain);
3210
Dan Gohman79522dc2012-01-13 00:39:07 +00003211 // If the object being released is in static or stack storage, we know it's
John McCall9fbd3182011-06-15 23:37:01 +00003212 // not being managed by ObjC reference counting, so we can delete pairs
3213 // regardless of what possible decrements or uses lie between them.
Dan Gohman79522dc2012-01-13 00:39:07 +00003214 bool KnownSafe = isa<Constant>(Arg) || isa<AllocaInst>(Arg);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003215
Dan Gohman1b31ea82011-08-22 17:29:11 +00003216 // A constant pointer can't be pointing to an object on the heap. It may
3217 // be reference-counted, but it won't be deleted.
3218 if (const LoadInst *LI = dyn_cast<LoadInst>(Arg))
3219 if (const GlobalVariable *GV =
3220 dyn_cast<GlobalVariable>(
3221 StripPointerCastsAndObjCCalls(LI->getPointerOperand())))
3222 if (GV->isConstant())
3223 KnownSafe = true;
3224
John McCall9fbd3182011-06-15 23:37:01 +00003225 // If a pair happens in a region where it is known that the reference count
3226 // is already incremented, we can similarly ignore possible decrements.
Dan Gohmane6d5e882011-08-19 00:26:36 +00003227 bool KnownSafeTD = true, KnownSafeBU = true;
John McCall9fbd3182011-06-15 23:37:01 +00003228
3229 // Connect the dots between the top-down-collected RetainsToMove and
3230 // bottom-up-collected ReleasesToMove to form sets of related calls.
3231 // This is an iterative process so that we connect multiple releases
3232 // to multiple retains if needed.
3233 unsigned OldDelta = 0;
3234 unsigned NewDelta = 0;
3235 unsigned OldCount = 0;
3236 unsigned NewCount = 0;
3237 bool FirstRelease = true;
3238 bool FirstRetain = true;
3239 NewRetains.push_back(Retain);
3240 for (;;) {
3241 for (SmallVectorImpl<Instruction *>::const_iterator
3242 NI = NewRetains.begin(), NE = NewRetains.end(); NI != NE; ++NI) {
3243 Instruction *NewRetain = *NI;
3244 MapVector<Value *, RRInfo>::const_iterator It = Retains.find(NewRetain);
3245 assert(It != Retains.end());
3246 const RRInfo &NewRetainRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003247 KnownSafeTD &= NewRetainRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003248 for (SmallPtrSet<Instruction *, 2>::const_iterator
3249 LI = NewRetainRRI.Calls.begin(),
3250 LE = NewRetainRRI.Calls.end(); LI != LE; ++LI) {
3251 Instruction *NewRetainRelease = *LI;
3252 DenseMap<Value *, RRInfo>::const_iterator Jt =
3253 Releases.find(NewRetainRelease);
3254 if (Jt == Releases.end())
3255 goto next_retain;
3256 const RRInfo &NewRetainReleaseRRI = Jt->second;
3257 assert(NewRetainReleaseRRI.Calls.count(NewRetain));
3258 if (ReleasesToMove.Calls.insert(NewRetainRelease)) {
3259 OldDelta -=
3260 BBStates[NewRetainRelease->getParent()].GetAllPathCount();
3261
3262 // Merge the ReleaseMetadata and IsTailCallRelease values.
3263 if (FirstRelease) {
3264 ReleasesToMove.ReleaseMetadata =
3265 NewRetainReleaseRRI.ReleaseMetadata;
3266 ReleasesToMove.IsTailCallRelease =
3267 NewRetainReleaseRRI.IsTailCallRelease;
3268 FirstRelease = false;
3269 } else {
3270 if (ReleasesToMove.ReleaseMetadata !=
3271 NewRetainReleaseRRI.ReleaseMetadata)
3272 ReleasesToMove.ReleaseMetadata = 0;
3273 if (ReleasesToMove.IsTailCallRelease !=
3274 NewRetainReleaseRRI.IsTailCallRelease)
3275 ReleasesToMove.IsTailCallRelease = false;
3276 }
3277
3278 // Collect the optimal insertion points.
3279 if (!KnownSafe)
3280 for (SmallPtrSet<Instruction *, 2>::const_iterator
3281 RI = NewRetainReleaseRRI.ReverseInsertPts.begin(),
3282 RE = NewRetainReleaseRRI.ReverseInsertPts.end();
3283 RI != RE; ++RI) {
3284 Instruction *RIP = *RI;
3285 if (ReleasesToMove.ReverseInsertPts.insert(RIP))
3286 NewDelta -= BBStates[RIP->getParent()].GetAllPathCount();
3287 }
3288 NewReleases.push_back(NewRetainRelease);
3289 }
3290 }
3291 }
3292 NewRetains.clear();
3293 if (NewReleases.empty()) break;
3294
3295 // Back the other way.
3296 for (SmallVectorImpl<Instruction *>::const_iterator
3297 NI = NewReleases.begin(), NE = NewReleases.end(); NI != NE; ++NI) {
3298 Instruction *NewRelease = *NI;
3299 DenseMap<Value *, RRInfo>::const_iterator It =
3300 Releases.find(NewRelease);
3301 assert(It != Releases.end());
3302 const RRInfo &NewReleaseRRI = It->second;
Dan Gohmane6d5e882011-08-19 00:26:36 +00003303 KnownSafeBU &= NewReleaseRRI.KnownSafe;
John McCall9fbd3182011-06-15 23:37:01 +00003304 for (SmallPtrSet<Instruction *, 2>::const_iterator
3305 LI = NewReleaseRRI.Calls.begin(),
3306 LE = NewReleaseRRI.Calls.end(); LI != LE; ++LI) {
3307 Instruction *NewReleaseRetain = *LI;
3308 MapVector<Value *, RRInfo>::const_iterator Jt =
3309 Retains.find(NewReleaseRetain);
3310 if (Jt == Retains.end())
3311 goto next_retain;
3312 const RRInfo &NewReleaseRetainRRI = Jt->second;
3313 assert(NewReleaseRetainRRI.Calls.count(NewRelease));
3314 if (RetainsToMove.Calls.insert(NewReleaseRetain)) {
3315 unsigned PathCount =
3316 BBStates[NewReleaseRetain->getParent()].GetAllPathCount();
3317 OldDelta += PathCount;
3318 OldCount += PathCount;
3319
3320 // Merge the IsRetainBlock values.
3321 if (FirstRetain) {
3322 RetainsToMove.IsRetainBlock = NewReleaseRetainRRI.IsRetainBlock;
3323 FirstRetain = false;
3324 } else if (ReleasesToMove.IsRetainBlock !=
3325 NewReleaseRetainRRI.IsRetainBlock)
3326 // It's not possible to merge the sequences if one uses
3327 // objc_retain and the other uses objc_retainBlock.
3328 goto next_retain;
3329
3330 // Collect the optimal insertion points.
3331 if (!KnownSafe)
3332 for (SmallPtrSet<Instruction *, 2>::const_iterator
3333 RI = NewReleaseRetainRRI.ReverseInsertPts.begin(),
3334 RE = NewReleaseRetainRRI.ReverseInsertPts.end();
3335 RI != RE; ++RI) {
3336 Instruction *RIP = *RI;
3337 if (RetainsToMove.ReverseInsertPts.insert(RIP)) {
3338 PathCount = BBStates[RIP->getParent()].GetAllPathCount();
3339 NewDelta += PathCount;
3340 NewCount += PathCount;
3341 }
3342 }
3343 NewRetains.push_back(NewReleaseRetain);
3344 }
3345 }
3346 }
3347 NewReleases.clear();
3348 if (NewRetains.empty()) break;
3349 }
3350
Dan Gohmane6d5e882011-08-19 00:26:36 +00003351 // If the pointer is known incremented or nested, we can safely delete the
3352 // pair regardless of what's between them.
3353 if (KnownSafeTD || KnownSafeBU) {
John McCall9fbd3182011-06-15 23:37:01 +00003354 RetainsToMove.ReverseInsertPts.clear();
3355 ReleasesToMove.ReverseInsertPts.clear();
3356 NewCount = 0;
Dan Gohmana7f7db22011-08-12 00:26:31 +00003357 } else {
3358 // Determine whether the new insertion points we computed preserve the
3359 // balance of retain and release calls through the program.
3360 // TODO: If the fully aggressive solution isn't valid, try to find a
3361 // less aggressive solution which is.
3362 if (NewDelta != 0)
3363 goto next_retain;
John McCall9fbd3182011-06-15 23:37:01 +00003364 }
3365
3366 // Determine whether the original call points are balanced in the retain and
3367 // release calls through the program. If not, conservatively don't touch
3368 // them.
3369 // TODO: It's theoretically possible to do code motion in this case, as
3370 // long as the existing imbalances are maintained.
3371 if (OldDelta != 0)
3372 goto next_retain;
3373
John McCall9fbd3182011-06-15 23:37:01 +00003374 // Ok, everything checks out and we're all set. Let's move some code!
3375 Changed = true;
Dan Gohmaneeeb7752012-04-24 22:53:18 +00003376 assert(OldCount != 0 && "Unreachable code?");
3377 AnyPairsCompletelyEliminated = NewCount == 0;
John McCall9fbd3182011-06-15 23:37:01 +00003378 NumRRs += OldCount - NewCount;
Dan Gohman44280692011-07-22 22:29:21 +00003379 MoveCalls(Arg, RetainsToMove, ReleasesToMove,
3380 Retains, Releases, DeadInsts, M);
John McCall9fbd3182011-06-15 23:37:01 +00003381
3382 next_retain:
3383 NewReleases.clear();
3384 NewRetains.clear();
3385 RetainsToMove.clear();
3386 ReleasesToMove.clear();
3387 }
3388
3389 // Now that we're done moving everything, we can delete the newly dead
3390 // instructions, as we no longer need them as insert points.
3391 while (!DeadInsts.empty())
3392 EraseInstruction(DeadInsts.pop_back_val());
3393
3394 return AnyPairsCompletelyEliminated;
3395}
3396
3397/// OptimizeWeakCalls - Weak pointer optimizations.
3398void ObjCARCOpt::OptimizeWeakCalls(Function &F) {
3399 // First, do memdep-style RLE and S2L optimizations. We can't use memdep
3400 // itself because it uses AliasAnalysis and we need to do provenance
3401 // queries instead.
3402 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3403 Instruction *Inst = &*I++;
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003404
3405 DEBUG(dbgs() << "ObjCARCOpt: OptimizeWeakCalls: Visiting: " << *Inst <<
3406 "\n");
3407
John McCall9fbd3182011-06-15 23:37:01 +00003408 InstructionClass Class = GetBasicInstructionClass(Inst);
3409 if (Class != IC_LoadWeak && Class != IC_LoadWeakRetained)
3410 continue;
3411
3412 // Delete objc_loadWeak calls with no users.
3413 if (Class == IC_LoadWeak && Inst->use_empty()) {
3414 Inst->eraseFromParent();
3415 continue;
3416 }
3417
3418 // TODO: For now, just look for an earlier available version of this value
3419 // within the same block. Theoretically, we could do memdep-style non-local
3420 // analysis too, but that would want caching. A better approach would be to
3421 // use the technique that EarlyCSE uses.
3422 inst_iterator Current = llvm::prior(I);
3423 BasicBlock *CurrentBB = Current.getBasicBlockIterator();
3424 for (BasicBlock::iterator B = CurrentBB->begin(),
3425 J = Current.getInstructionIterator();
3426 J != B; --J) {
3427 Instruction *EarlierInst = &*llvm::prior(J);
3428 InstructionClass EarlierClass = GetInstructionClass(EarlierInst);
3429 switch (EarlierClass) {
3430 case IC_LoadWeak:
3431 case IC_LoadWeakRetained: {
3432 // If this is loading from the same pointer, replace this load's value
3433 // with that one.
3434 CallInst *Call = cast<CallInst>(Inst);
3435 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3436 Value *Arg = Call->getArgOperand(0);
3437 Value *EarlierArg = EarlierCall->getArgOperand(0);
3438 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3439 case AliasAnalysis::MustAlias:
3440 Changed = true;
3441 // If the load has a builtin retain, insert a plain retain for it.
3442 if (Class == IC_LoadWeakRetained) {
3443 CallInst *CI =
3444 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3445 "", Call);
3446 CI->setTailCall();
3447 }
3448 // Zap the fully redundant load.
3449 Call->replaceAllUsesWith(EarlierCall);
3450 Call->eraseFromParent();
3451 goto clobbered;
3452 case AliasAnalysis::MayAlias:
3453 case AliasAnalysis::PartialAlias:
3454 goto clobbered;
3455 case AliasAnalysis::NoAlias:
3456 break;
3457 }
3458 break;
3459 }
3460 case IC_StoreWeak:
3461 case IC_InitWeak: {
3462 // If this is storing to the same pointer and has the same size etc.
3463 // replace this load's value with the stored value.
3464 CallInst *Call = cast<CallInst>(Inst);
3465 CallInst *EarlierCall = cast<CallInst>(EarlierInst);
3466 Value *Arg = Call->getArgOperand(0);
3467 Value *EarlierArg = EarlierCall->getArgOperand(0);
3468 switch (PA.getAA()->alias(Arg, EarlierArg)) {
3469 case AliasAnalysis::MustAlias:
3470 Changed = true;
3471 // If the load has a builtin retain, insert a plain retain for it.
3472 if (Class == IC_LoadWeakRetained) {
3473 CallInst *CI =
3474 CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
3475 "", Call);
3476 CI->setTailCall();
3477 }
3478 // Zap the fully redundant load.
3479 Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
3480 Call->eraseFromParent();
3481 goto clobbered;
3482 case AliasAnalysis::MayAlias:
3483 case AliasAnalysis::PartialAlias:
3484 goto clobbered;
3485 case AliasAnalysis::NoAlias:
3486 break;
3487 }
3488 break;
3489 }
3490 case IC_MoveWeak:
3491 case IC_CopyWeak:
3492 // TOOD: Grab the copied value.
3493 goto clobbered;
3494 case IC_AutoreleasepoolPush:
3495 case IC_None:
3496 case IC_User:
3497 // Weak pointers are only modified through the weak entry points
3498 // (and arbitrary calls, which could call the weak entry points).
3499 break;
3500 default:
3501 // Anything else could modify the weak pointer.
3502 goto clobbered;
3503 }
3504 }
3505 clobbered:;
3506 }
3507
3508 // Then, for each destroyWeak with an alloca operand, check to see if
3509 // the alloca and all its users can be zapped.
3510 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
3511 Instruction *Inst = &*I++;
3512 InstructionClass Class = GetBasicInstructionClass(Inst);
3513 if (Class != IC_DestroyWeak)
3514 continue;
3515
3516 CallInst *Call = cast<CallInst>(Inst);
3517 Value *Arg = Call->getArgOperand(0);
3518 if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
3519 for (Value::use_iterator UI = Alloca->use_begin(),
3520 UE = Alloca->use_end(); UI != UE; ++UI) {
Dan Gohman447989c2012-04-27 18:56:31 +00003521 const Instruction *UserInst = cast<Instruction>(*UI);
John McCall9fbd3182011-06-15 23:37:01 +00003522 switch (GetBasicInstructionClass(UserInst)) {
3523 case IC_InitWeak:
3524 case IC_StoreWeak:
3525 case IC_DestroyWeak:
3526 continue;
3527 default:
3528 goto done;
3529 }
3530 }
3531 Changed = true;
3532 for (Value::use_iterator UI = Alloca->use_begin(),
3533 UE = Alloca->use_end(); UI != UE; ) {
3534 CallInst *UserInst = cast<CallInst>(*UI++);
Dan Gohmance5d8b02012-05-18 22:17:29 +00003535 switch (GetBasicInstructionClass(UserInst)) {
3536 case IC_InitWeak:
3537 case IC_StoreWeak:
3538 // These functions return their second argument.
3539 UserInst->replaceAllUsesWith(UserInst->getArgOperand(1));
3540 break;
3541 case IC_DestroyWeak:
3542 // No return value.
3543 break;
3544 default:
Dan Gohman4c8f9092012-05-21 17:41:28 +00003545 llvm_unreachable("alloca really is used!");
Dan Gohmance5d8b02012-05-18 22:17:29 +00003546 }
John McCall9fbd3182011-06-15 23:37:01 +00003547 UserInst->eraseFromParent();
3548 }
3549 Alloca->eraseFromParent();
3550 done:;
3551 }
3552 }
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003553
3554 DEBUG(dbgs() << "ObjCARCOpt: Finished visiting weak calls.\n\n");
3555
John McCall9fbd3182011-06-15 23:37:01 +00003556}
3557
3558/// OptimizeSequences - Identify program paths which execute sequences of
3559/// retains and releases which can be eliminated.
3560bool ObjCARCOpt::OptimizeSequences(Function &F) {
3561 /// Releases, Retains - These are used to store the results of the main flow
3562 /// analysis. These use Value* as the key instead of Instruction* so that the
3563 /// map stays valid when we get around to rewriting code and calls get
3564 /// replaced by arguments.
3565 DenseMap<Value *, RRInfo> Releases;
3566 MapVector<Value *, RRInfo> Retains;
3567
3568 /// BBStates, This is used during the traversal of the function to track the
3569 /// states for each identified object at each block.
3570 DenseMap<const BasicBlock *, BBState> BBStates;
3571
3572 // Analyze the CFG of the function, and all instructions.
3573 bool NestingDetected = Visit(F, BBStates, Retains, Releases);
3574
3575 // Transform.
Dan Gohman44280692011-07-22 22:29:21 +00003576 return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
3577 NestingDetected;
John McCall9fbd3182011-06-15 23:37:01 +00003578}
3579
3580/// OptimizeReturns - Look for this pattern:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003581/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003582/// %call = call i8* @something(...)
3583/// %2 = call i8* @objc_retain(i8* %call)
3584/// %3 = call i8* @objc_autorelease(i8* %2)
3585/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003586/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003587/// And delete the retain and autorelease.
3588///
3589/// Otherwise if it's just this:
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003590/// \code
John McCall9fbd3182011-06-15 23:37:01 +00003591/// %3 = call i8* @objc_autorelease(i8* %2)
3592/// ret i8* %3
Dmitri Gribenkoc5252da2012-09-14 14:57:36 +00003593/// \endcode
John McCall9fbd3182011-06-15 23:37:01 +00003594/// convert the autorelease to autoreleaseRV.
3595void ObjCARCOpt::OptimizeReturns(Function &F) {
3596 if (!F.getReturnType()->isPointerTy())
3597 return;
3598
3599 SmallPtrSet<Instruction *, 4> DependingInstructions;
3600 SmallPtrSet<const BasicBlock *, 4> Visited;
3601 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
3602 BasicBlock *BB = FI;
3603 ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003604
3605 DEBUG(dbgs() << "ObjCARCOpt: OptimizeReturns: Visiting: " << *Ret << "\n");
3606
John McCall9fbd3182011-06-15 23:37:01 +00003607 if (!Ret) continue;
3608
3609 const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
3610 FindDependencies(NeedsPositiveRetainCount, Arg,
3611 BB, Ret, DependingInstructions, Visited, PA);
3612 if (DependingInstructions.size() != 1)
3613 goto next_block;
3614
3615 {
3616 CallInst *Autorelease =
3617 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3618 if (!Autorelease)
3619 goto next_block;
Dan Gohman0daef3d2012-05-08 23:39:44 +00003620 InstructionClass AutoreleaseClass = GetBasicInstructionClass(Autorelease);
John McCall9fbd3182011-06-15 23:37:01 +00003621 if (!IsAutorelease(AutoreleaseClass))
3622 goto next_block;
3623 if (GetObjCArg(Autorelease) != Arg)
3624 goto next_block;
3625
3626 DependingInstructions.clear();
3627 Visited.clear();
3628
3629 // Check that there is nothing that can affect the reference
3630 // count between the autorelease and the retain.
3631 FindDependencies(CanChangeRetainCount, Arg,
3632 BB, Autorelease, DependingInstructions, Visited, PA);
3633 if (DependingInstructions.size() != 1)
3634 goto next_block;
3635
3636 {
3637 CallInst *Retain =
3638 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3639
3640 // Check that we found a retain with the same argument.
3641 if (!Retain ||
3642 !IsRetain(GetBasicInstructionClass(Retain)) ||
3643 GetObjCArg(Retain) != Arg)
3644 goto next_block;
3645
3646 DependingInstructions.clear();
3647 Visited.clear();
3648
3649 // Convert the autorelease to an autoreleaseRV, since it's
3650 // returning the value.
3651 if (AutoreleaseClass == IC_Autorelease) {
3652 Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
3653 AutoreleaseClass = IC_AutoreleaseRV;
3654 }
3655
3656 // Check that there is nothing that can affect the reference
3657 // count between the retain and the call.
Dan Gohman27e06662011-09-29 22:27:34 +00003658 // Note that Retain need not be in BB.
3659 FindDependencies(CanChangeRetainCount, Arg, Retain->getParent(), Retain,
John McCall9fbd3182011-06-15 23:37:01 +00003660 DependingInstructions, Visited, PA);
3661 if (DependingInstructions.size() != 1)
3662 goto next_block;
3663
3664 {
3665 CallInst *Call =
3666 dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3667
3668 // Check that the pointer is the return value of the call.
3669 if (!Call || Arg != Call)
3670 goto next_block;
3671
3672 // Check that the call is a regular call.
3673 InstructionClass Class = GetBasicInstructionClass(Call);
3674 if (Class != IC_CallOrUser && Class != IC_Call)
3675 goto next_block;
3676
3677 // If so, we can zap the retain and autorelease.
3678 Changed = true;
3679 ++NumRets;
3680 EraseInstruction(Retain);
3681 EraseInstruction(Autorelease);
3682 }
3683 }
3684 }
3685
3686 next_block:
3687 DependingInstructions.clear();
3688 Visited.clear();
3689 }
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00003690
3691 DEBUG(dbgs() << "ObjCARCOpt: OptimizeReturns: Finished visiting returns.\n\n");
3692
John McCall9fbd3182011-06-15 23:37:01 +00003693}
3694
3695bool ObjCARCOpt::doInitialization(Module &M) {
3696 if (!EnableARCOpts)
3697 return false;
3698
Dan Gohmand6bf2012012-04-13 18:57:48 +00003699 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003700 Run = ModuleHasARC(M);
3701 if (!Run)
3702 return false;
3703
John McCall9fbd3182011-06-15 23:37:01 +00003704 // Identify the imprecise release metadata kind.
3705 ImpreciseReleaseMDKind =
3706 M.getContext().getMDKindID("clang.imprecise_release");
Dan Gohmana974bea2011-10-17 22:53:25 +00003707 CopyOnEscapeMDKind =
3708 M.getContext().getMDKindID("clang.arc.copy_on_escape");
Dan Gohmandbe266b2012-02-17 18:59:53 +00003709 NoObjCARCExceptionsMDKind =
3710 M.getContext().getMDKindID("clang.arc.no_objc_arc_exceptions");
John McCall9fbd3182011-06-15 23:37:01 +00003711
John McCall9fbd3182011-06-15 23:37:01 +00003712 // Intuitively, objc_retain and others are nocapture, however in practice
3713 // they are not, because they return their argument value. And objc_release
Dan Gohman447989c2012-04-27 18:56:31 +00003714 // calls finalizers which can have arbitrary side effects.
John McCall9fbd3182011-06-15 23:37:01 +00003715
3716 // These are initialized lazily.
3717 RetainRVCallee = 0;
3718 AutoreleaseRVCallee = 0;
3719 ReleaseCallee = 0;
3720 RetainCallee = 0;
Dan Gohman44280692011-07-22 22:29:21 +00003721 RetainBlockCallee = 0;
John McCall9fbd3182011-06-15 23:37:01 +00003722 AutoreleaseCallee = 0;
3723
3724 return false;
3725}
3726
3727bool ObjCARCOpt::runOnFunction(Function &F) {
3728 if (!EnableARCOpts)
3729 return false;
3730
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003731 // If nothing in the Module uses ARC, don't do anything.
3732 if (!Run)
3733 return false;
3734
John McCall9fbd3182011-06-15 23:37:01 +00003735 Changed = false;
3736
3737 PA.setAA(&getAnalysis<AliasAnalysis>());
3738
3739 // This pass performs several distinct transformations. As a compile-time aid
3740 // when compiling code that isn't ObjC, skip these if the relevant ObjC
3741 // library functions aren't declared.
3742
3743 // Preliminary optimizations. This also computs UsedInThisFunction.
3744 OptimizeIndividualCalls(F);
3745
3746 // Optimizations for weak pointers.
3747 if (UsedInThisFunction & ((1 << IC_LoadWeak) |
3748 (1 << IC_LoadWeakRetained) |
3749 (1 << IC_StoreWeak) |
3750 (1 << IC_InitWeak) |
3751 (1 << IC_CopyWeak) |
3752 (1 << IC_MoveWeak) |
3753 (1 << IC_DestroyWeak)))
3754 OptimizeWeakCalls(F);
3755
3756 // Optimizations for retain+release pairs.
3757 if (UsedInThisFunction & ((1 << IC_Retain) |
3758 (1 << IC_RetainRV) |
3759 (1 << IC_RetainBlock)))
3760 if (UsedInThisFunction & (1 << IC_Release))
3761 // Run OptimizeSequences until it either stops making changes or
3762 // no retain+release pair nesting is detected.
3763 while (OptimizeSequences(F)) {}
3764
3765 // Optimizations if objc_autorelease is used.
Dan Gohman0daef3d2012-05-08 23:39:44 +00003766 if (UsedInThisFunction & ((1 << IC_Autorelease) |
3767 (1 << IC_AutoreleaseRV)))
John McCall9fbd3182011-06-15 23:37:01 +00003768 OptimizeReturns(F);
3769
3770 return Changed;
3771}
3772
3773void ObjCARCOpt::releaseMemory() {
3774 PA.clear();
3775}
3776
3777//===----------------------------------------------------------------------===//
3778// ARC contraction.
3779//===----------------------------------------------------------------------===//
3780
3781// TODO: ObjCARCContract could insert PHI nodes when uses aren't
3782// dominated by single calls.
3783
John McCall9fbd3182011-06-15 23:37:01 +00003784#include "llvm/Analysis/Dominators.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +00003785#include "llvm/InlineAsm.h"
3786#include "llvm/Operator.h"
John McCall9fbd3182011-06-15 23:37:01 +00003787
3788STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
3789
3790namespace {
3791 /// ObjCARCContract - Late ARC optimizations. These change the IR in a way
3792 /// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
3793 class ObjCARCContract : public FunctionPass {
3794 bool Changed;
3795 AliasAnalysis *AA;
3796 DominatorTree *DT;
3797 ProvenanceAnalysis PA;
3798
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00003799 /// Run - A flag indicating whether this optimization pass should run.
3800 bool Run;
3801
John McCall9fbd3182011-06-15 23:37:01 +00003802 /// StoreStrongCallee, etc. - Declarations for ObjC runtime
3803 /// functions, for use in creating calls to them. These are initialized
3804 /// lazily to avoid cluttering up the Module with unused declarations.
3805 Constant *StoreStrongCallee,
3806 *RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
3807
3808 /// RetainRVMarker - The inline asm string to insert between calls and
3809 /// RetainRV calls to make the optimization work on targets which need it.
3810 const MDString *RetainRVMarker;
3811
Dan Gohman0cdece42012-01-19 19:14:36 +00003812 /// StoreStrongCalls - The set of inserted objc_storeStrong calls. If
3813 /// at the end of walking the function we have found no alloca
3814 /// instructions, these calls can be marked "tail".
Dan Gohman0daef3d2012-05-08 23:39:44 +00003815 SmallPtrSet<CallInst *, 8> StoreStrongCalls;
Dan Gohman0cdece42012-01-19 19:14:36 +00003816
John McCall9fbd3182011-06-15 23:37:01 +00003817 Constant *getStoreStrongCallee(Module *M);
3818 Constant *getRetainAutoreleaseCallee(Module *M);
3819 Constant *getRetainAutoreleaseRVCallee(Module *M);
3820
3821 bool ContractAutorelease(Function &F, Instruction *Autorelease,
3822 InstructionClass Class,
3823 SmallPtrSet<Instruction *, 4>
3824 &DependingInstructions,
3825 SmallPtrSet<const BasicBlock *, 4>
3826 &Visited);
3827
3828 void ContractRelease(Instruction *Release,
3829 inst_iterator &Iter);
3830
3831 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
3832 virtual bool doInitialization(Module &M);
3833 virtual bool runOnFunction(Function &F);
3834
3835 public:
3836 static char ID;
3837 ObjCARCContract() : FunctionPass(ID) {
3838 initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
3839 }
3840 };
3841}
3842
3843char ObjCARCContract::ID = 0;
3844INITIALIZE_PASS_BEGIN(ObjCARCContract,
3845 "objc-arc-contract", "ObjC ARC contraction", false, false)
3846INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
3847INITIALIZE_PASS_DEPENDENCY(DominatorTree)
3848INITIALIZE_PASS_END(ObjCARCContract,
3849 "objc-arc-contract", "ObjC ARC contraction", false, false)
3850
3851Pass *llvm::createObjCARCContractPass() {
3852 return new ObjCARCContract();
3853}
3854
3855void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
3856 AU.addRequired<AliasAnalysis>();
3857 AU.addRequired<DominatorTree>();
3858 AU.setPreservesCFG();
3859}
3860
3861Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
3862 if (!StoreStrongCallee) {
3863 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003864 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
3865 Type *I8XX = PointerType::getUnqual(I8X);
Dan Gohman0daef3d2012-05-08 23:39:44 +00003866 Type *Params[] = { I8XX, I8X };
John McCall9fbd3182011-06-15 23:37:01 +00003867
Bill Wendling034b94b2012-12-19 07:18:57 +00003868 AttributeSet Attribute = AttributeSet()
Bill Wendling99faa3b2012-12-07 23:16:57 +00003869 .addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00003870 Attribute::get(C, Attribute::NoUnwind))
3871 .addAttr(M->getContext(), 1, Attribute::get(C, Attribute::NoCapture));
John McCall9fbd3182011-06-15 23:37:01 +00003872
3873 StoreStrongCallee =
3874 M->getOrInsertFunction(
3875 "objc_storeStrong",
3876 FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Bill Wendling034b94b2012-12-19 07:18:57 +00003877 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00003878 }
3879 return StoreStrongCallee;
3880}
3881
3882Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
3883 if (!RetainAutoreleaseCallee) {
3884 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003885 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00003886 Type *Params[] = { I8X };
3887 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00003888 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00003889 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00003890 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00003891 RetainAutoreleaseCallee =
Bill Wendling034b94b2012-12-19 07:18:57 +00003892 M->getOrInsertFunction("objc_retainAutorelease", FTy, Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00003893 }
3894 return RetainAutoreleaseCallee;
3895}
3896
3897Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
3898 if (!RetainAutoreleaseRVCallee) {
3899 LLVMContext &C = M->getContext();
Jay Foad5fdd6c82011-07-12 14:06:48 +00003900 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Dan Gohman0daef3d2012-05-08 23:39:44 +00003901 Type *Params[] = { I8X };
3902 FunctionType *FTy = FunctionType::get(I8X, Params, /*isVarArg=*/false);
Bill Wendling034b94b2012-12-19 07:18:57 +00003903 AttributeSet Attribute =
Bill Wendling99faa3b2012-12-07 23:16:57 +00003904 AttributeSet().addAttr(M->getContext(), AttributeSet::FunctionIndex,
Bill Wendling034b94b2012-12-19 07:18:57 +00003905 Attribute::get(C, Attribute::NoUnwind));
John McCall9fbd3182011-06-15 23:37:01 +00003906 RetainAutoreleaseRVCallee =
3907 M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
Bill Wendling034b94b2012-12-19 07:18:57 +00003908 Attribute);
John McCall9fbd3182011-06-15 23:37:01 +00003909 }
3910 return RetainAutoreleaseRVCallee;
3911}
3912
Dan Gohman447989c2012-04-27 18:56:31 +00003913/// ContractAutorelease - Merge an autorelease with a retain into a fused call.
John McCall9fbd3182011-06-15 23:37:01 +00003914bool
3915ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
3916 InstructionClass Class,
3917 SmallPtrSet<Instruction *, 4>
3918 &DependingInstructions,
3919 SmallPtrSet<const BasicBlock *, 4>
3920 &Visited) {
3921 const Value *Arg = GetObjCArg(Autorelease);
3922
3923 // Check that there are no instructions between the retain and the autorelease
3924 // (such as an autorelease_pop) which may change the count.
3925 CallInst *Retain = 0;
3926 if (Class == IC_AutoreleaseRV)
3927 FindDependencies(RetainAutoreleaseRVDep, Arg,
3928 Autorelease->getParent(), Autorelease,
3929 DependingInstructions, Visited, PA);
3930 else
3931 FindDependencies(RetainAutoreleaseDep, Arg,
3932 Autorelease->getParent(), Autorelease,
3933 DependingInstructions, Visited, PA);
3934
3935 Visited.clear();
3936 if (DependingInstructions.size() != 1) {
3937 DependingInstructions.clear();
3938 return false;
3939 }
3940
3941 Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
3942 DependingInstructions.clear();
3943
3944 if (!Retain ||
3945 GetBasicInstructionClass(Retain) != IC_Retain ||
3946 GetObjCArg(Retain) != Arg)
3947 return false;
3948
3949 Changed = true;
3950 ++NumPeeps;
3951
3952 if (Class == IC_AutoreleaseRV)
3953 Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
3954 else
3955 Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
3956
3957 EraseInstruction(Autorelease);
3958 return true;
3959}
3960
3961/// ContractRelease - Attempt to merge an objc_release with a store, load, and
3962/// objc_retain to form an objc_storeStrong. This can be a little tricky because
3963/// the instructions don't always appear in order, and there may be unrelated
3964/// intervening instructions.
3965void ObjCARCContract::ContractRelease(Instruction *Release,
3966 inst_iterator &Iter) {
3967 LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman2bc3d522011-09-12 20:23:13 +00003968 if (!Load || !Load->isSimple()) return;
John McCall9fbd3182011-06-15 23:37:01 +00003969
3970 // For now, require everything to be in one basic block.
3971 BasicBlock *BB = Release->getParent();
3972 if (Load->getParent() != BB) return;
3973
Dan Gohman4670dac2012-05-08 23:34:08 +00003974 // Walk down to find the store and the release, which may be in either order.
Dan Gohman95b8cf12012-05-09 23:08:33 +00003975 BasicBlock::iterator I = Load, End = BB->end();
John McCall9fbd3182011-06-15 23:37:01 +00003976 ++I;
3977 AliasAnalysis::Location Loc = AA->getLocation(Load);
Dan Gohman4670dac2012-05-08 23:34:08 +00003978 StoreInst *Store = 0;
3979 bool SawRelease = false;
3980 for (; !Store || !SawRelease; ++I) {
Dan Gohman95b8cf12012-05-09 23:08:33 +00003981 if (I == End)
3982 return;
3983
Dan Gohman4670dac2012-05-08 23:34:08 +00003984 Instruction *Inst = I;
3985 if (Inst == Release) {
3986 SawRelease = true;
3987 continue;
3988 }
3989
3990 InstructionClass Class = GetBasicInstructionClass(Inst);
3991
3992 // Unrelated retains are harmless.
3993 if (IsRetain(Class))
3994 continue;
3995
3996 if (Store) {
3997 // The store is the point where we're going to put the objc_storeStrong,
3998 // so make sure there are no uses after it.
3999 if (CanUse(Inst, Load, PA, Class))
4000 return;
4001 } else if (AA->getModRefInfo(Inst, Loc) & AliasAnalysis::Mod) {
4002 // We are moving the load down to the store, so check for anything
4003 // else which writes to the memory between the load and the store.
4004 Store = dyn_cast<StoreInst>(Inst);
4005 if (!Store || !Store->isSimple()) return;
4006 if (Store->getPointerOperand() != Loc.Ptr) return;
4007 }
4008 }
John McCall9fbd3182011-06-15 23:37:01 +00004009
4010 Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
4011
4012 // Walk up to find the retain.
4013 I = Store;
4014 BasicBlock::iterator Begin = BB->begin();
4015 while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
4016 --I;
4017 Instruction *Retain = I;
4018 if (GetBasicInstructionClass(Retain) != IC_Retain) return;
4019 if (GetObjCArg(Retain) != New) return;
4020
4021 Changed = true;
4022 ++NumStoreStrongs;
4023
4024 LLVMContext &C = Release->getContext();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00004025 Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
4026 Type *I8XX = PointerType::getUnqual(I8X);
John McCall9fbd3182011-06-15 23:37:01 +00004027
4028 Value *Args[] = { Load->getPointerOperand(), New };
4029 if (Args[0]->getType() != I8XX)
4030 Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
4031 if (Args[1]->getType() != I8X)
4032 Args[1] = new BitCastInst(Args[1], I8X, "", Store);
4033 CallInst *StoreStrong =
4034 CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
Jay Foada3efbb12011-07-15 08:37:34 +00004035 Args, "", Store);
John McCall9fbd3182011-06-15 23:37:01 +00004036 StoreStrong->setDoesNotThrow();
4037 StoreStrong->setDebugLoc(Store->getDebugLoc());
4038
Dan Gohman0cdece42012-01-19 19:14:36 +00004039 // We can't set the tail flag yet, because we haven't yet determined
4040 // whether there are any escaping allocas. Remember this call, so that
4041 // we can set the tail flag once we know it's safe.
4042 StoreStrongCalls.insert(StoreStrong);
4043
John McCall9fbd3182011-06-15 23:37:01 +00004044 if (&*Iter == Store) ++Iter;
4045 Store->eraseFromParent();
4046 Release->eraseFromParent();
4047 EraseInstruction(Retain);
4048 if (Load->use_empty())
4049 Load->eraseFromParent();
4050}
4051
4052bool ObjCARCContract::doInitialization(Module &M) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00004053 // If nothing in the Module uses ARC, don't do anything.
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004054 Run = ModuleHasARC(M);
4055 if (!Run)
4056 return false;
4057
John McCall9fbd3182011-06-15 23:37:01 +00004058 // These are initialized lazily.
4059 StoreStrongCallee = 0;
4060 RetainAutoreleaseCallee = 0;
4061 RetainAutoreleaseRVCallee = 0;
4062
4063 // Initialize RetainRVMarker.
4064 RetainRVMarker = 0;
4065 if (NamedMDNode *NMD =
4066 M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
4067 if (NMD->getNumOperands() == 1) {
4068 const MDNode *N = NMD->getOperand(0);
4069 if (N->getNumOperands() == 1)
4070 if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
4071 RetainRVMarker = S;
4072 }
4073
4074 return false;
4075}
4076
4077bool ObjCARCContract::runOnFunction(Function &F) {
4078 if (!EnableARCOpts)
4079 return false;
4080
Dan Gohmanc4bcd4d2011-06-20 23:20:43 +00004081 // If nothing in the Module uses ARC, don't do anything.
4082 if (!Run)
4083 return false;
4084
John McCall9fbd3182011-06-15 23:37:01 +00004085 Changed = false;
4086 AA = &getAnalysis<AliasAnalysis>();
4087 DT = &getAnalysis<DominatorTree>();
4088
4089 PA.setAA(&getAnalysis<AliasAnalysis>());
4090
Dan Gohman0cdece42012-01-19 19:14:36 +00004091 // Track whether it's ok to mark objc_storeStrong calls with the "tail"
4092 // keyword. Be conservative if the function has variadic arguments.
4093 // It seems that functions which "return twice" are also unsafe for the
4094 // "tail" argument, because they are setjmp, which could need to
4095 // return to an earlier stack state.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004096 bool TailOkForStoreStrongs = !F.isVarArg() &&
4097 !F.callsFunctionThatReturnsTwice();
Dan Gohman0cdece42012-01-19 19:14:36 +00004098
John McCall9fbd3182011-06-15 23:37:01 +00004099 // For ObjC library calls which return their argument, replace uses of the
4100 // argument with uses of the call return value, if it dominates the use. This
4101 // reduces register pressure.
4102 SmallPtrSet<Instruction *, 4> DependingInstructions;
4103 SmallPtrSet<const BasicBlock *, 4> Visited;
4104 for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
4105 Instruction *Inst = &*I++;
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00004106
4107 DEBUG(dbgs() << "ObjCARCContract: Visiting: " << *Inst << "\n");
4108
John McCall9fbd3182011-06-15 23:37:01 +00004109 // Only these library routines return their argument. In particular,
4110 // objc_retainBlock does not necessarily return its argument.
4111 InstructionClass Class = GetBasicInstructionClass(Inst);
4112 switch (Class) {
4113 case IC_Retain:
4114 case IC_FusedRetainAutorelease:
4115 case IC_FusedRetainAutoreleaseRV:
4116 break;
4117 case IC_Autorelease:
4118 case IC_AutoreleaseRV:
4119 if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
4120 continue;
4121 break;
4122 case IC_RetainRV: {
4123 // If we're compiling for a target which needs a special inline-asm
4124 // marker to do the retainAutoreleasedReturnValue optimization,
4125 // insert it now.
4126 if (!RetainRVMarker)
4127 break;
4128 BasicBlock::iterator BBI = Inst;
Dan Gohman58fb3402012-06-25 19:47:37 +00004129 BasicBlock *InstParent = Inst->getParent();
4130
4131 // Step up to see if the call immediately precedes the RetainRV call.
4132 // If it's an invoke, we have to cross a block boundary. And we have
4133 // to carefully dodge no-op instructions.
4134 do {
4135 if (&*BBI == InstParent->begin()) {
4136 BasicBlock *Pred = InstParent->getSinglePredecessor();
4137 if (!Pred)
4138 goto decline_rv_optimization;
4139 BBI = Pred->getTerminator();
4140 break;
4141 }
4142 --BBI;
4143 } while (isNoopInstruction(BBI));
4144
John McCall9fbd3182011-06-15 23:37:01 +00004145 if (&*BBI == GetObjCArg(Inst)) {
Dan Gohmand6bf2012012-04-13 18:57:48 +00004146 Changed = true;
John McCall9fbd3182011-06-15 23:37:01 +00004147 InlineAsm *IA =
4148 InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
4149 /*isVarArg=*/false),
4150 RetainRVMarker->getString(),
4151 /*Constraints=*/"", /*hasSideEffects=*/true);
4152 CallInst::Create(IA, "", Inst);
4153 }
Dan Gohman58fb3402012-06-25 19:47:37 +00004154 decline_rv_optimization:
John McCall9fbd3182011-06-15 23:37:01 +00004155 break;
4156 }
4157 case IC_InitWeak: {
4158 // objc_initWeak(p, null) => *p = null
4159 CallInst *CI = cast<CallInst>(Inst);
4160 if (isNullOrUndef(CI->getArgOperand(1))) {
4161 Value *Null =
4162 ConstantPointerNull::get(cast<PointerType>(CI->getType()));
4163 Changed = true;
4164 new StoreInst(Null, CI->getArgOperand(0), CI);
4165 CI->replaceAllUsesWith(Null);
4166 CI->eraseFromParent();
4167 }
4168 continue;
4169 }
4170 case IC_Release:
4171 ContractRelease(Inst, I);
4172 continue;
Dan Gohman0cdece42012-01-19 19:14:36 +00004173 case IC_User:
4174 // Be conservative if the function has any alloca instructions.
4175 // Technically we only care about escaping alloca instructions,
4176 // but this is sufficient to handle some interesting cases.
4177 if (isa<AllocaInst>(Inst))
4178 TailOkForStoreStrongs = false;
4179 continue;
John McCall9fbd3182011-06-15 23:37:01 +00004180 default:
4181 continue;
4182 }
4183
Michael Gottesman8f22c8b2013-01-01 16:05:48 +00004184 DEBUG(dbgs() << "ObjCARCContract: Finished Queue.\n\n");
4185
John McCall9fbd3182011-06-15 23:37:01 +00004186 // Don't use GetObjCArg because we don't want to look through bitcasts
4187 // and such; to do the replacement, the argument must have type i8*.
4188 const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
4189 for (;;) {
4190 // If we're compiling bugpointed code, don't get in trouble.
4191 if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
4192 break;
4193 // Look through the uses of the pointer.
4194 for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
4195 UI != UE; ) {
4196 Use &U = UI.getUse();
4197 unsigned OperandNo = UI.getOperandNo();
4198 ++UI; // Increment UI now, because we may unlink its element.
Dan Gohmand6bf2012012-04-13 18:57:48 +00004199
4200 // If the call's return value dominates a use of the call's argument
4201 // value, rewrite the use to use the return value. We check for
4202 // reachability here because an unreachable call is considered to
4203 // trivially dominate itself, which would lead us to rewriting its
4204 // argument in terms of its return value, which would lead to
4205 // infinite loops in GetObjCArg.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004206 if (DT->isReachableFromEntry(U) && DT->dominates(Inst, U)) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004207 Changed = true;
4208 Instruction *Replacement = Inst;
4209 Type *UseTy = U.get()->getType();
Dan Gohman6c189ec2012-04-13 01:08:28 +00004210 if (PHINode *PHI = dyn_cast<PHINode>(U.getUser())) {
Rafael Espindola2453dff2012-03-15 15:52:59 +00004211 // For PHI nodes, insert the bitcast in the predecessor block.
Dan Gohman0daef3d2012-05-08 23:39:44 +00004212 unsigned ValNo = PHINode::getIncomingValueNumForOperand(OperandNo);
4213 BasicBlock *BB = PHI->getIncomingBlock(ValNo);
Rafael Espindola2453dff2012-03-15 15:52:59 +00004214 if (Replacement->getType() != UseTy)
4215 Replacement = new BitCastInst(Replacement, UseTy, "",
4216 &BB->back());
Dan Gohmand6bf2012012-04-13 18:57:48 +00004217 // While we're here, rewrite all edges for this PHI, rather
4218 // than just one use at a time, to minimize the number of
4219 // bitcasts we emit.
Dan Gohman447989c2012-04-27 18:56:31 +00004220 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
Rafael Espindola2453dff2012-03-15 15:52:59 +00004221 if (PHI->getIncomingBlock(i) == BB) {
4222 // Keep the UI iterator valid.
4223 if (&PHI->getOperandUse(
4224 PHINode::getOperandNumForIncomingValue(i)) ==
4225 &UI.getUse())
4226 ++UI;
4227 PHI->setIncomingValue(i, Replacement);
4228 }
4229 } else {
4230 if (Replacement->getType() != UseTy)
Dan Gohman6c189ec2012-04-13 01:08:28 +00004231 Replacement = new BitCastInst(Replacement, UseTy, "",
4232 cast<Instruction>(U.getUser()));
Rafael Espindola2453dff2012-03-15 15:52:59 +00004233 U.set(Replacement);
John McCall9fbd3182011-06-15 23:37:01 +00004234 }
Rafael Espindola2453dff2012-03-15 15:52:59 +00004235 }
John McCall9fbd3182011-06-15 23:37:01 +00004236 }
4237
Dan Gohman447989c2012-04-27 18:56:31 +00004238 // If Arg is a no-op casted pointer, strip one level of casts and iterate.
John McCall9fbd3182011-06-15 23:37:01 +00004239 if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
4240 Arg = BI->getOperand(0);
4241 else if (isa<GEPOperator>(Arg) &&
4242 cast<GEPOperator>(Arg)->hasAllZeroIndices())
4243 Arg = cast<GEPOperator>(Arg)->getPointerOperand();
4244 else if (isa<GlobalAlias>(Arg) &&
4245 !cast<GlobalAlias>(Arg)->mayBeOverridden())
4246 Arg = cast<GlobalAlias>(Arg)->getAliasee();
4247 else
4248 break;
4249 }
4250 }
4251
Dan Gohman0cdece42012-01-19 19:14:36 +00004252 // If this function has no escaping allocas or suspicious vararg usage,
4253 // objc_storeStrong calls can be marked with the "tail" keyword.
4254 if (TailOkForStoreStrongs)
Dan Gohman0daef3d2012-05-08 23:39:44 +00004255 for (SmallPtrSet<CallInst *, 8>::iterator I = StoreStrongCalls.begin(),
Dan Gohman0cdece42012-01-19 19:14:36 +00004256 E = StoreStrongCalls.end(); I != E; ++I)
4257 (*I)->setTailCall();
4258 StoreStrongCalls.clear();
4259
John McCall9fbd3182011-06-15 23:37:01 +00004260 return Changed;
4261}